Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count to solve the input lights out board.
The lights out board is a 2d square grid of varying size composed of two characters - . for a light that is off and * for a light that is on.
To solve the board, all "lights" have to be turned off. Toggling a light (i.e. turning off when it is on, turning on when it is off) is made 5 lights at a time - the light selected and the lights surround it in a + (plus) shape.
"Selecting" the middle light will solve the board:
.*.
***
.*.
Since Lights Out! solution order does not matter, the output will be a new board with markings on what bulbs to select. The above board's solution is
...
.X.
...
Turning off a light in a corner where there are no side bulbs to turn off will not overflow:
...
..*
.**
Selecting the lower-right bulb will only turn off 3 bulbs in this case.
Test cases
Input:
**.**
*.*.*
.***.
*.*.*
**.**
Output:
X...X
.....
..X..
.....
X...X
Input:
.*.*.
**.**
.*.*.
*.*.*
*.*.*
Output:
.....
.X.X.
.....
.....
X.X.X
Input:
*...*
**.**
..*..
*.*..
*.**.
Output:
X.X.X
..X..
.....
.....
X.X..
Code count includes input/output (i.e full program).
Perl, 172 characters
Perl, 333 251 203 197 190 172 characters. In this version, we randomly push buttons until all of the lights are out.
map{$N++;$E+=/\*/*1<<$t++for/./g}<>;
$C^=$b=1<<($%=rand$t),
$E^=$b|$b>>$N|($%<$t-$N)*$b<<$N|($%%$N&&$b/2)|(++$%%$N&&$b*2)while$E;
die map{('.',X)[1&$C>>$_-1],$_%$N?"":$/}1..$t
Haskell, 263 characters (277 and 285 before edit) (according to wc)
import List
o x=zipWith4(\a b c i->foldr1(/=)[a,b,c,i])x(f:x)$tail x++[f]
f=0>0
d t=mapM(\_->[f,1>0])t>>=c t
c(l:m:n)x=map(x:)$c(zipWith(/=)m x:n)$o x l
c[k]x=[a|a<-[[x]],not$or$o x k]
main=interact$unlines.u((['.','X']!!).fromEnum).head.d.u(<'.').lines
u=map.map
This includes IO code : you can simply compile it and it works.
This method use the fact that once the first line of the solution is determined, it is easy to determine what the other lines should look like. So we try every solution for the first line, and verify that the all lights are off on the last line, and this algorithm is O(n²*2^n)
Edit : here is an un-shrunk version :
import Data.List
-- xor on a list. /= works like binary xor, so we just need a fold
xor = foldr (/=) False
-- what will be changed on a line when we push the buttons :
changeLine orig chg = zipWith4 (\a b c d -> xor [a,b,c,d]) chg (False:chg) (tail chg ++ [False]) orig
-- change a line according to the buttons pushed one line higher :
changeLine2 orig chg = zipWith (/=) orig chg
-- compute a solution given a first line.
-- if no solution is given, return []
solution (l1:l2:ls) chg = map (chg:) $ solution (changeLine2 l2 chg:ls) (changeLine l1 chg)
solution [l] chg = if or (changeLine l chg) then [] else [[chg]]
firstLines n = mapM (const [False,True]) [1..n]
-- original uses something equivalent to "firstLines (length gris)", which only
-- works on square grids.
solutions grid = firstLines (length $ head grid) >>= solution grid
main = interact $ unlines . disp . head . solutions . parse . lines
where parse = map (map (\c ->
case c of
'.' -> False
'*' -> True))
disp = map (map (\b -> if b then 'X' else '.'))
Ruby, 225 221
b=$<.read.split
d=b.size
n=b.join.tr'.*','01'
f=2**d**2
h=0
d.times{h=h<<d|2**d-1&~1}
f.times{|a|e=(n.to_i(2)^a^a<<d^a>>d^(a&h)>>1^a<<1&h)&f-1
e==0&&(i=("%0*b"%[d*d,a]).tr('01','.X')
d.times{puts i[0,d]
i=i[d..-1]}
exit)}
F#, 672 646 643 634 629 628 chars (incl newlines)
EDIT: priceless: this post triggered Stackoverflow's human verification system. I bet it's because of the code.
EDIT2: more filthy tricks knocked off 36 chars. Reversing an if in the second line shaved off 5 more.
Writing this code made my eyes bleed and my brain melt.
The good: it's short(ish).
The bad: it'll crash on any input square larger than 4x4 (it's an O(be stupid and try everything) algorithm, O(n*2^(n^2)) to be more precise). Much of the ugliness comes from padding the input square with zeroes on all sides to avoid edge and corner cases.
The ugly: just look at it. It's code only a parent could love. Liberal uses of >>> and <<< made F# look like brainfuck.
The program accepts rows of input until you enter a blank line.
This code doesn't work in F# interactive. It has to be compiled inside a project.
open System
let rec i()=[let l=Console.ReadLine()in if l<>""then yield!l::i()]
let a=i()
let m=a.[0].Length
let M=m+2
let q=Seq.sum[for k in 1..m->(1L<<<m)-1L<<<k*M+1]
let B=Seq.sum(Seq.mapi(fun i s->Convert.ToInt64(String.collect(function|'.'->"0"|_->"1")s,2)<<<M*i+M+1)a)
let rec f B x=function 0L->B&&&q|n->f(if n%2L=1L then B^^^(x*7L/2L+(x<<<M)+(x>>>M))else B)(x*2L)(n/2L)
let z=fst<|Seq.find(snd>>(=)0L)[for k in 0L..1L<<<m*m->let n=Seq.sum[for j in 0..m->k+1L&&&(((1L<<<m)-1L)<<<j*m)<<<M+1+2*j]in n,f B 1L n]
for i=0 to m-1 do
for j=0 to m-1 do printf"%s"(if z&&&(1L<<<m-j+M*i+M)=0L then "." else "X")
printfn""
F#, 23 lines
Uses brute force and a liberal amount of bitmasking to find a solution:
open System.Collections
let solve(r:string) =
let s = r.Replace("\n", "")
let size = s.Length|>float|>sqrt|>int
let buttons =
[| for i in 0 .. (size*size)-1 do
let x = new BitArray(size*size)
{ 0 .. (size*size)-1 } |> Seq.iter (fun j ->
let toXY n = n / size, n % size
let (ir, ic), (jr, jc) = toXY i, toXY j
x.[j] <- ir=jr&&abs(ic-jc)<2||ic=jc&&abs(ir-jr)<2)
yield x |]
let testPerm permutation =
let b = new BitArray(s.Length)
s |> Seq.iteri (fun i x -> if x = '*' then b.[i] <- true)
permutation |> Seq.iteri (fun i x -> if x = '1' then b.Xor(buttons.[i]);() )
b |> Seq.cast |> Seq.forall (fun x -> not x)
{for a in 0 .. (1 <<< (size * size)) - 1 -> System.Convert.ToString(a, 2).PadLeft(size * size, '0') }
|> Seq.pick (fun p -> if testPerm p then Some p else None)
|> Seq.iteri (fun i s -> printf "%s%s" (if s = '1' then "X" else ".") (if (i + 1) % size = 0 then "\n" else "") )
Usage:
> solve ".*.
***
.*.";;
...
.X.
...
val it : unit = ()
> solve "**.**
*.*.*
.***.
*.*.*
**.**";;
..X..
X.X.X
..X..
X.X.X
..X..
val it : unit = ()
> solve "*...*
**.**
..*..
*.*..
*.**.";;
.....
X...X
.....
X.X.X
....X
C89, 436 characters
Original source (75 lines, 1074 characters):
#include <stdio.h>
#include <string.h>
int board[9][9];
int zeroes[9];
char presses[99];
int size;
int i;
#define TOGGLE { \
board[i][j] ^= 4; \
if(i > 0) \
board[i-1][j] ^= 4; \
if(j > 0) \
board[i][j-1] ^= 4; \
board[i+1][j] ^= 4; \
board[i][j+1] ^= 4; \
presses[i*size + i + j] ^= 118; /* '.' xor 'X' */ \
}
void search(int j)
{
int i = 0;
if(j == size)
{
for(i = 1; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(board[i-1][j])
TOGGLE
}
}
if(memcmp(board[size - 1], zeroes, size * sizeof(int)) == 0)
puts(presses);
for(i = 1; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(presses[i*size + i + j] & 16)
TOGGLE
}
}
}
else
{
search(j+1);
TOGGLE
search(j+1);
TOGGLE
}
}
int main(int c, char **v)
{
while((c = getchar()) != EOF)
{
if(c == '\n')
{
size++;
i = 0;
}
else
board[size][i++] = ~c & 4; // '.' ==> 0, '*' ==> 4
}
memset(presses, '.', 99);
for(c = 1; c <= size; c++)
presses[c * size + c - 1] = '\n';
presses[size * size + size] = '\0';
search(0);
}
Compressed source, with line breaks added for your sanity:
#define T{b[i][j]^=4;if(i)b[i-1][j]^=4;if(j)b[i][j-1]^=4;b[i+1][j]^=4;b[i][j+1]^=4;p[i*s+i+j]^=118;}
b[9][9],z[9],s,i;char p[99];
S(j){int i=0;if(j-s){S(j+1);T S(j+1);T}else{
for(i=1;i<s;i++)for(j=0;j<s;j++)if(b[i-1][j])T
if(!memcmp(b[s-1],z,s*4))puts(p);
for(i=1;i<s;i++)for(j=0;j<s;j++)if(p[i*s+i+j]&16)T}}
main(c){while((c=getchar())+1)if(c-10)b[s][i++]=~c&4;else s++,i=0;
memset(p,46,99);for(c=1;c<=s;c++)p[c*s+c-1]=10;p[s*s+s]=0;S(0);}
Note that this solution assumes 4-byte integers; if integers are not 4 bytes on your system, replace the 4 in the call to memcmp with your integer size. The maximum sized grid this supports is 8x8 (not 9x9, since the bit flipping ignores two of the edge cases); to support up to 98x98, add another 9 to the array sizes in the declarations of b, z and p and the call to memset.
Also note that this finds and prints ALL solutions, not just the first solution. Runtime is O(2^N * N^2), where N is the size of the grid. The input format must be perfectly valid, as no error checking is performed -- it must consist of only ., *, and '\n', and it must have exactly N lines (i.e. the last character must be a '\n').
Ruby:
class Array
def solve
carry
(0...(2**w)).each {|i|
flip i
return self if solved?
flip i
}
end
def flip(i)
(0...w).each {|n|
press n, 0 if i & (1 << n) != 0
}
carry
end
def solved?
(0...h).each {|y|
(0...w).each {|x|
return false if self[y][x]
}
}
true
end
def carry
(0...h-1).each {|y|
(0...w).each {|x|
press x, y+1 if self[y][x]
}
}
end
def h() size end
def w() self[0].size end
def press x, y
#presses = (0...h).map { [false] * w } if #presses == nil
#presses[y][x] = !#presses[y][x]
inv x, y
if y>0 then inv x, y-1 end
if y<h-1 then inv x, y+1 end
if x>0 then inv x-1, y end
if x<w-1 then inv x+1, y end
end
def inv x, y
self[y][x] = !self[y][x]
end
def presses
(0...h).each {|y|
puts (0...w).map {|x|
if #presses[y][x] then 'X' else '.' end
}.inject {|a,b| a+b}
}
end
end
STDIN.read.split(/\n/).map{|x|x.split(//).map {|v|v == '*'}}.solve.presses
Lua, 499 characters
Fast, uses Strategy to find a quicker solution.
m={46,[42]=88,[46]=1,[88]=42}o={88,[42]=46,[46]=42,[88]=1}z={1,[42]=1}r=io.read
l=r()s=#l q={l:byte(1,s)}
for i=2,s do q[#q+1]=10 l=r()for j=1,#l do q[#q+1]=l:byte(j)end end
function t(p,v)q[p]=v[q[p]]or q[p]end
function u(p)t(p,m)t(p-1,o)t(p+1,o)t(p-s-1,o)t(p+s+1,o)end
while 1 do e=1 for i=1,(s+1)*s do
if i>(s+1)*(s-1)then if z[q[i]]then e=_ end
elseif z[q[i]]then u(i+s+1)end end
if e then break end
for i=1,s do if 42==q[i]or 46==q[i]then u(i)break end u(i)end end
print(string.char(unpack(q)))
Example input:
.....
.....
.....
.....
*...*
Example output:
XX...
..X..
X.XX.
X.X.X
...XX
Some of these have multiple answers. This seems to work but it's not exactly fast.
Groovy: 790 chracters
bd = System.in.readLines().collect{it.collect { it=='*'}}
sl = bd.collect{it.collect{false}}
println "\n\n\n"
solve(bd, sl, 0, 0, 0)
def solve(board, solution, int i, int j, prefix) {
/* println " ".multiply(prefix) + "$i $j"*/
if(done(board)) {
println sl.collect{it.collect{it?'X':'.'}.join("")}.join("\n")
return
}
if(j>=board[i].size) {
j=0; i++
}
if(i==board.size) {
return
}
solve(board, solution, i, j+1, prefix+1)
flip(solution, i, j)
flip(board, i, j)
flip(board, i+1, j)
flip(board, i-1, j)
flip(board, i, j+1)
flip(board, i, j-1)
solve(board, solution, i, j+1, prefix+1)
}
def flip(board, i, j) {
if(i>=0 && i<board.size && j>=0 && j<board[i].size)
board[i][j] = !board[i][j]
}
def done(board) {
return board.every { it.every{!it} }
}
For Haskell, here's a 406 376 342 character solution, though I'm sure there's a way to shrink this. Call the s function for the first solution found:
s b=head$t(b,[])
l=length
t(b,m)=if l u>0 then map snd u else concat$map t c where{i=[0..l b-1];c=[(a b p,m++[p])|p<-[(x,y)|x<-i,y<-i]];u=filter((all(==False)).fst)c}
a b(x,y)=foldl o b[(x,y),(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
o b(x,y)=if x<0||y<0||x>=r||y>=r then b else take i b++[not(b!!i)]++drop(i+1)b where{r=floor$sqrt$fromIntegral$l b;i=y*r+x}
In its more-readable, typed form:
solution :: [Bool] -> [(Int,Int)]
solution board = head $ solutions (board, [])
solutions :: ([Bool],[(Int,Int)]) -> [[(Int,Int)]]
solutions (board,moves) =
if length solutions' > 0
then map snd solutions'
else concat $ map solutions candidates
where
boardIndices = [0..length board - 1]
candidates = [
(applyMove board pair, moves ++ [pair])
| pair <- [(x,y) | x <- boardIndices, y <- boardIndices]]
solutions' = filter ((all (==False)) . fst) candidates
applyMove :: [Bool] -> (Int,Int) -> [Bool]
applyMove board (x,y) =
foldl toggle board [(x,y), (x-1,y), (x+1,y), (x,y-1), (x,y+1)]
toggle :: [Bool] -> (Int,Int) -> [Bool]
toggle board (x,y) =
if x < 0 || y < 0 || x >= boardSize || y >= boardSize then board
else
take index board ++ [ not (board !! index) ]
++ drop (index + 1) board
where
boardSize = floor $ sqrt $ fromIntegral $ length board
index = y * boardSize + x
Note that this is a horrible breadth-first, brute-force algorithm.
F#, 365 370, 374, 444 including all whitespace
open System
let s(r:string)=
let d=r.IndexOf"\n"
let e,m,p=d+1,r.ToCharArray(),Random()
let o b k=m.[k]<-char(b^^^int m.[k])
while String(m).IndexOfAny([|'*';'\\'|])>=0 do
let x,y=p.Next d,p.Next d
o 118(x+y*e)
for i in x-1..x+1 do for n in y-1..y+1 do if i>=0&&i<d&&n>=0&&n<d then o 4(i+n*e)
printf"%s"(String m)
Here's the original readable version before the xor optimization. 1108
open System
let solve (input : string) =
let height = input.IndexOf("\n")
let width = height + 1
let board = input.ToCharArray()
let rnd = Random()
let mark = function
| '*' -> 'O'
| '.' -> 'X'
| 'O' -> '*'
| _ -> '.'
let flip x y =
let flip = function
| '*' -> '.'
| '.' -> '*'
| 'X' -> 'O'
| _ -> 'X'
if x >= 0 && x < height && y >= 0 && y < height then
board.[x + y * width] <- flip board.[x + y * width]
let solved() =
String(board).IndexOfAny([|'*';'O'|]) < 0
while not (solved()) do
let x = rnd.Next(height) // ignore newline
let y = rnd.Next(height)
board.[x + y * width] <- mark board.[x + y * width]
for i in -1..1 do
for n in -1..1 do
flip (x + i) (y + n)
printf "%s" (String(board))
Python — 982
Count is 982 not counting tabs and newlines. This includes necessary spaces. Started learning python this week, so I had some fun :). Pretty straight forward, nothing fancy here, besides the crappy var names to make it shorter.
import re
def m():
s=''
while 1:
y=raw_input()
if y=='':break
s=s+y+'\n'
t=a(s)
t.s()
t.p()
class a:
def __init__(x,y):
x.t=len(y);
r=re.compile('(.*)\n')
x.z=r.findall(y)
x.w=len(x.z[0])
x.v=len(x.z)
def s(x):
n=0
for i in range(0,x.t):
if(x.x(i,0)):
break
def x(x,d,c):
b=x.z[:]
for i in range(1,x.v+1):
for j in range(1,x.w+1):
if x.c():
break;
x.z=b[:]
x.u(i,j)
if d!=c:
x.x(d,c+1)
if x.c():
break;
if x.c():
return 1
x.z=b[:]
return 0;
def y(x,r,c):
e=x.z[r-1][c-1]
if e=='*':
return '.'
elif e=='x':
return 'X'
elif e=='X':
return 'x'
else:
return '*'
def j(x,r,c):
v=x.y(r+1,c)
x.r(r+1,c,v)
def k(x,r,c):
v=x.y(r-1,c)
x.r(r-1,c,v)
def h(x,r,c):
v=x.y(r,c-1)
x.r(r,c-1,v)
def l(x,r,c):
v=x.y(r,c+1)
x.r(r,c+1,v)
def u(x,r,c):
e=x.z[r-1][c-1]
if e=='*' or e=='x':
v='X'
else:
v='x'
x.r(r,c,v)
if r!=1:
x.k(r,c)
if r!=x.v:
x.j(r,c)
if c!=1:
x.h(r,c)
if c!=x.w:
x.l(r,c)
def r(x,r,c,l):
m=x.z[r-1]
m=m[:c-1]+l+m[c:]
x.z[r-1]=m
def c(x):
for i in x.z:
for j in i:
if j=='*' or j=='x':
return 0
return 1
def p(x):
for i in x.z:
print i
print '\n'
if __name__=='__main__':
m()
Usage:
*...*
**.**
..*..
*.*..
*.**.
X.X.X
..X..
.....
.....
X.X..
Related
Currently i'm trying
I have a function to calculate the inverse sum of a number
let inverseSum n =
let rec sI n acc =
match n with
| 1 -> acc
| _ -> sI (n - 1) ((1.0 /. float n) +. acc)
in sI n 1.0;;
For example, inverseSum 2 -> 1/2 + 1 = 3/2 = 1.5
I try to test the function with 2 and 5, it's okay:
inverseSum 2;;
inverseSum 5;;
inverseSum 2;;
- : float = 1.5
inverseSum 5;;
- : float = 2.28333333333333321
For the moment, no problem.
After that, I initialize a list which contains all numbers between 1 and 10000 ([1;…;10000])
let initList = List.init 10000 (fun n -> n + 1);;
no problem.
I code a function so that an element of the list becomes the inverse sum of the element
(e.g. [1;2;3] -> [inverseSum 1; inverseSum 2; inverseSum 3])
let rec invSumLst lst =
match lst with
| [] -> []
| h::t -> (inverseSum h) :: invSumLst t;;
and I use it on the list initList:
let invInit = invSumLst initList;;
So far so good, but I start to have doubts from this stage:
I select the elements of invList strictly inferior to 5.0
let listLess5 = List.filter (fun n -> n < 5.0) invInit;;
And I realize the sum of these elements using fold_left:
let foldLess5 = List.fold_left (+.) 0.0 listLess5;;
I redo the last two steps with floats greater than or equal to 5.0
let moreEg5 = List.filter (fun n -> n >= 5.0) invInit;;
let foldMore5 = List.fold_left (+.) 0.0 moreEg5;;
Finally, I sum all the numbers of the list:
let foldInvInit = List.fold_left (+.) 0.0 invInit;;
but at the end when I try to calculate the absolute error between the numbers less than 5, those greater than 5 and all the elements of the list, the result is surprising:
Float.abs ((foldLess5 +. foldMore5) -. foldInvInit);;
Printf.printf "%f\n" (Float.abs ((foldLess5 +. foldMore5) -. foldInvInit));;
Printf.printf "%b\n" ((foldLess5+.foldMore5) = foldInvInit);;
returns:
let foldMore5 = List.fold_left (+.) 0.0 moreEg5;;
val foldMore5 : float = 87553.6762998474733
let foldInvInit = List.fold_left (+.) 0.0 invInit;;
val foldInvInit : float = 87885.8479664799379
Float.abs ((foldLess5 +. foldMore5) -. foldInvInit);;
- : float = 1.45519152283668518e-11
Printf.printf "%f\n" (Float.abs ((foldLess5 +. foldMore5) -. foldInvInit));;
0.000000
- : unit = ()
Printf.printf "%b\n" ((foldLess5+.foldMore5) = foldInvInit);;
false
- : unit = ()
it's probably a rounding problem, but I would like to know where exactly the error comes from?
Because here I am using an interpreter, so I see the error "1.45519152283668518e-11"
But if I used a compiler like ocamlpro, I would just get 0.000000 and false on the terminal and I wouldn't understand anything.
So I would just like to know if the problem comes from one of the functions of the code, or from a rounding made by the Printf.printf function which wrote the result with a "non scientific" notation.
OCaml is showing you the actual results of the operations you performed. The difference between the two sums is caused by the finite precision of floating values.
When adding up a list of large-ish numbers, by the time you reach the end of the list the number is large enough that the lowest-order bits of the new values simply can't be represented. But when adding a list of small-ish numbers, fewer bits are lost.
A system that shows foldLess5 +. foldMore5 as equal to foldInvInit is most likely lying to you for your convenience.
I find a predicate xml_quote_attribute/2 in a library(sgml)
of SWI-Prolog. This predicate works with the first argument
as input and the second argument as output:
?- xml_quote_attribute('<abc>', X).
X = '<abc>'.
But I couldn't figure out how I can do the reverse conversion.
For example the following query doesn't work:
?- xml_quote_attribute(X, '<abc>').
ERROR: Arguments are not sufficiently instantiated
Is there another predicate that does the job?
Bye
This is how Ruud's solution looks like with DCG notation + pushback lists / semicontext notation.
:- use_module(library(dcg/basics)).
html_unescape --> sgml_entity, !, html_unescape.
html_unescape, [C] --> [C], !, html_unescape.
html_unescape --> [].
sgml_entity, [C] --> "&#", integer(C), ";".
sgml_entity, "<" --> "<".
sgml_entity, ">" --> ">".
sgml_entity, "&" --> "&".
Using DCGs makes the code a bit more readable. It also does away with some of the superfluous backtracking that Cookie Monster noted is the result of using append/3 for this.
Here's the naive solution, using lists of character codes. Most likely it will not give you the best performance possible, but for strings that are not extremely long, it might just be alright.
html_unescape("", "") :- !.
html_unescape(Escaped, Unescaped) :-
append("&", _, Escaped),
!,
append(E1, E2, Escaped),
sgml_entity(E1, U1),
!,
html_unescape(E2, U2),
append(U1, U2, Unescaped).
html_unescape(Escaped, Unescaped) :-
append([C], E2, Escaped),
html_unescape(E2, U2),
append([C], U2, Unescaped).
sgml_entity(Escaped, [C]) :-
append(["&#", L, ";"], Escaped),
catch(number_codes(C, L), error(syntax_error(_), _), fail),
!.
sgml_entity("<", "<").
sgml_entity(">", ">").
sgml_entity("&", "&").
You will have to complete the list of SGML entities yourself.
Sample output:
?- html_unescape("<a> 曹操", L), format('~s', [L]).
<a> 曹操
L = [60, 97, 62, 32, 26361, 25805].
If you don't mind linking a foreign module, then you can make a very efficient implementation in C.
html_unescape.pl:
:- module(html_unescape, [ html_unescape/2 ]).
:- use_foreign_library(foreign('./html_unescape.so')).
html_unescape.c:
#include <stdio.h>
#include <string.h>
#include <SWI-Prolog.h>
static int to_utf8(char **unesc, unsigned ccode)
{
int ok = 1;
if (ccode < 0x80)
{
*(*unesc)++ = ccode;
}
else if (ccode < 0x800)
{
*(*unesc)++ = 192 + ccode / 64;
*(*unesc)++ = 128 + ccode % 64;
}
else if (ccode - 0xd800u < 0x800)
{
ok = 0;
}
else if (ccode < 0x10000)
{
*(*unesc)++ = 224 + ccode / 4096;
*(*unesc)++ = 128 + ccode / 64 % 64;
*(*unesc)++ = 128 + ccode % 64;
}
else if (ccode < 0x110000)
{
*(*unesc)++ = 240 + ccode / 262144;
*(*unesc)++ = 128 + ccode / 4096 % 64;
*(*unesc)++ = 128 + ccode / 64 % 64;
*(*unesc)++ = 128 + ccode % 64;
}
else
{
ok = 0;
}
return ok;
}
static int numeric_entity(char **esc, char **unesc)
{
int consumed;
unsigned ccode;
int ok = (sscanf(*esc, "&#%u;%n", &ccode, &consumed) > 0 ||
sscanf(*esc, "&#x%x;%n", &ccode, &consumed) > 0) &&
consumed > 0 &&
to_utf8(unesc, ccode);
if (ok)
{
*esc += consumed;
}
return ok;
}
static int symbolic_entity(char **esc, char **unesc, char *name, int ccode)
{
int ok = strncmp(*esc, name, strlen(name)) == 0 &&
to_utf8(unesc, ccode);
if (ok)
{
*esc += strlen(name);
}
return ok;
}
static foreign_t pl_html_unescape(term_t escaped, term_t unescaped)
{
char *esc;
if (!PL_get_chars(escaped, &esc, CVT_ATOM | REP_UTF8))
{
PL_fail;
}
else if (strchr(esc, '&') == NULL)
{
return PL_unify(escaped, unescaped);
}
else
{
char buffer[strlen(esc) + 1];
char *unesc = buffer;
while (*esc != '\0')
{
if (*esc != '&' || !(numeric_entity(&esc, &unesc) ||
symbolic_entity(&esc, &unesc, "<", '<') ||
symbolic_entity(&esc, &unesc, ">", '>') ||
symbolic_entity(&esc, &unesc, "&", '&')))
// TODO: more entities...
{
*unesc++ = *esc++;
}
}
return PL_unify_chars(unescaped, PL_ATOM | REP_UTF8, unesc - buffer, buffer);
}
}
install_t install_html_unescape()
{
PL_register_foreign("html_unescape", 2, pl_html_unescape, 0);
}
The following statement will build a shared library html_unescape.so from html_unescape.c. Tested on Ubuntu 14.04; may be different on Windows.
swipl-ld -shared -o html_unescape html_unescape.c
Start up SWI-Prolog:
swipl html_unescape.pl
Sample output:
?- html_unescape('<a> 曹操', S).
S = '<a> 曹操'.
With special thanks to the SWI-Prolog documentation and source code, and to C library to convert unicode code points to UTF8?
Not aspiring as being the ultimate answer, since it doesn't give
a solution for SWI-Prolog. For a Java based interpreter the problem
is that XML escaping is not part of J2SE, at least not in a simple
form (didn't figure out how to use Xerxes or the like).
A possible route would be to interface to StringEscapeUtils ( * ) from
Apache Commons. But then again this would not be necessary on
Android since there is a class TextUtil. So we rolled our own ( * * )
little conversion. It works as follows:
?- text_escape('<abc>', X).
X = '<abc>'
?- text_escape(X, '<abc>').
X = '<abc>'
Note the use of the Java methods codePointAt() and charCount()
respectively appendCodePoint() in the Java source code. So it
could also escape and unescape code points above the basic
plane, i.e. in a range >0xFFFF (currently not implemented,
left as an exercise).
On the other hand the Apache libraries, at least version 2.6, are
NOT surrogate pair aware and will place two decimal entities per
code point instead as one.
Bye
( * ) Java: Class StringEscapeUtils Source
http://grepcode.com/file/repo1.maven.org/maven2/commons-lang/commons-lang/2.6/org/apache/commons/lang/Entities.java#Entities.escape%28java.io.Writer,java.lang.String%29
( * * ) Jekejeke Prolog: Module xml
http://www.jekejeke.ch/idatab/doclet/prod/en/docs/05_run/10_docu/05_frequent/07_theories/20_system/03_xml.html
The point is to guess a random number choosen from an interval of integers and do it within a fixed numbers of attempts.
The main function asks the upper limit of the interval and the number of guesses the user can give. The core function then should return the guessed value so when the number is right the function should terminate immediately.
I put some print statement while debugging and I understood that the y value is not returned to the while statement from the core function.
# -*- coding: utf-8 -*-
def main():
from random import choice
p = input("choose upper limit: ")
t = input("how many attempts: ")
pool = range(p+1)
x = choice(pool)
i = 1
while ((x != y) and (i < t)):
core(x,y)
i += 1
def core(x,y):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
You want to assign the return value of core back to the local y variable, it's not passed by reference:
y = core(x)
You'll also need to set y before you go into the loop. Local variables in functions are not available in other functions.
As a result, you don't need to pass y to core(x) at all:
def core(x):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
and the loop becomes:
y = None
while (x != y) and (i < t):
y = core(x)
i += 1
It doesn't much matter what you set y to in the main() function to start with, as long as it'll never be equal to x before the user has made a guess.
y = -1
while ((x != y) and (i < t)):
y = core(x,y)
i += 1
You "initialize" y before the loop. Inside the loop you set y equal to the result of core() function.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Challenge:
Without using the modulus divide operator provided already by your language, write a program that will take two integer inputs from a user and then displays the result of the first number modulus divided number by the second number. Assume all input is positive.
Example:
Input of first number:2
Input of second number:2
Result:0
Who wins:
In case you don't know how Code Golf works, the winner is the person who writes this program in the least amount of characters.
CSS: 107 chars :)
CSS (ungolfed):
li {
counter-increment: a;
}
li:after {
content: counter(a);
}
li:nth-child(3n) { /* replace 3 with 2nd input ("b" in "a % b") */
counter-reset: a;
counter-increment: none;
}
Accompanying HTML:
<ol> <li></li> <li></li> <li></li> <!-- etc. --> </ol>
This doesn't work in IE (surprise surprise!).
J, 10 characters
([-]*<.#%)
Usage:
10 ([-]*<.#%) 3
1
J, 17 characters (with input as a list)
({.-{:*[:<.{.%{:)
Usage:
({.-{:*[:<.{.%{:) 10 3
1
({.-{:*[:<.{.%{:) 225 13
4
Explanation:
I took a totem pole and turned it into a smiley, and it worked.
Golfscript, 6 7 13 chars:
2*~/*-
Usage (only way to input into golfscript):
echo 14 3 | ruby golfscript.rb modulo.gs
2
Explanation:
2*~ #double the input string and eval (so now 14 3 14 3 are on the stack)
/ #int divide 14 / 3, gives quotient
*- #multiply that result by 3, subtract from 14, gives remainder
RePeNt, 5 chars
2?/*-
Run using:
RePeNt mod.rpn 17 3
RePeNt "2?/*-" 17 3
RePeNt is a stack-based toy language I made myself where every operator/command/loop is entered in Reverse Polish Notation (RPN). I will release the interpreter when I have tidied it up a bit.
Command Explanation Stack
------- ----------- -----
n/a The program takes 2 parameters ( 17 3 ) and pushes them 17 3
onto the stack
2 Pushes a 2 onto the stack 17 3 2
? Pops a number (x) off the stack + copies the last x 17 3 17 3
stack items onto the stack
/ Divides on stack 17 3 5
* Multiplies on stack 17 15
- Subtracts on stack 2
Ruby (32):
p(a=gets.to_i)-a/(b=gets.to_i)*b
Sure I won't win, but here goes nothing:
<?php
$a=readline("#1:");
$b=readline("#2:");
while($b<=$a)$a-=$b;
echo "Result: $a";
I know there's already two Ruby answers, but why not; getting the input this way is a different enough approach to knock off a few characters.
Ruby 1.8.7+, 29 chars
a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
1
C: 52
main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
Python: 25 chars
Behaves with negative numbers, identically to modulus operator. Takes two comma-separated numbers.
x,y=input()
print x-x/y*y
Clojure: 30 characters
#(if(>%2%1)%1(recur(-%1%2)%2)))
Unefunge-98: 14 13 22 chars
&:7p&:' \/*-.#
Unefunge is the 1-dimensional instance of Funge-98: http://quadium.net/funge/spec98.html
Explanation (Command <- Explaination [Stack]):
& <- Get integer input of value A and store on stack.
[A]
: <- Duplicate top of stack.
[A A]
7 <- Push 7 on stack. Used for the `p` command.
[A A 7]
p <- Pop top two values (7 then A). Place the character whose ASCII value
is A at position 7 in the code (where the space is).
[A]
& <- Get integer input of value B and store on stack.
[A B]
: <- Duplicate top of stack.
[A B B]
' <- Jump over next character and grap the ASCII value of the jumped character.
[A B B A]
<- Because of the `p` command, this is actually the character whose ASCII
value is A at this point in the code. This was jumped over by the
previous instruction.
\ <- Swap top two values of stack.
[A B A B]
/ <- Pop top two values (B then A). Push (A/B) (integer division) onto stack.
[A B (A/B)]
* <- Pop top two values ((A/B) then B). Push (B*(A/B)) onto stack.
[A (B*(A/B))]
- <- Pop top two values ((B*(A/B)) then A). Push (A-(B*(A/B))) onto stack.
[(A-(B*(A/B)))]
. <- Pop top value and print it as an integer.
[]
# <- Exit program.
Code tested is this incomplete (but complete enough) Unefunge-98 interpreter I wrote to test the code:
module Unefunge where
import Prelude hiding (subtract)
import qualified Data.Map as Map
import Control.Exception (handle)
import Control.Monad
import Data.Char (chr, ord)
import Data.Map (Map)
import System.Environment (getArgs)
import System.Exit (exitSuccess, exitFailure, ExitCode (..))
import System.IO (hSetBuffering, BufferMode (..), stdin, stdout)
-----------------------------------------------------------
iterateM :: (Monad m) => (a -> m a) -> m a -> m b
iterateM f m = m >>= iterateM f . f
-----------------------------------------------------------
data Cell = Integer Integer | Char Char
-----------------------------------------------------------
newtype Stack = Stack [Integer]
mkStack = Stack []
push :: Integer -> Stack -> Stack
push x (Stack xs) = Stack (x : xs)
pop :: Stack -> Stack
pop (Stack xs) = case xs of
[] -> Stack []
_:ys -> Stack ys
top :: Stack -> Integer
top (Stack xs) = case xs of
[] -> 0
y:_ -> y
-----------------------------------------------------------
data Env = Env {
cells :: Map Integer Cell
, position :: Integer
, stack :: Stack
}
withStack :: (Stack -> Stack) -> Env -> Env
withStack f env = env { stack = f $ stack env }
pushStack :: Integer -> Env -> Env
pushStack x = withStack $ push x
popStack :: Env -> Env
popStack = withStack pop
topStack :: Env -> Integer
topStack = top . stack
-----------------------------------------------------------
type Instruction = Env -> IO Env
cellAt :: Integer -> Env -> Cell
cellAt n = Map.findWithDefault (Char ' ') n . cells
currentCell :: Env -> Cell
currentCell env = cellAt (position env) env
lookupInstruction :: Cell -> Instruction
lookupInstruction cell = case cell of
Integer n -> pushInteger n
Char c -> case c of
'\''-> fetch
'\\'-> swap
'0' -> pushInteger 0
'1' -> pushInteger 1
'2' -> pushInteger 2
'3' -> pushInteger 3
'4' -> pushInteger 4
'5' -> pushInteger 5
'6' -> pushInteger 6
'7' -> pushInteger 7
'8' -> pushInteger 8
'9' -> pushInteger 9
' ' -> nop
'+' -> add
'-' -> subtract
'*' -> multiply
'/' -> divide
'#' -> trampoline
'&' -> inputDecimal
'.' -> outputDecimal
':' -> duplicate
'p' -> put
'#' -> stop
instructionAt :: Integer -> Env -> Instruction
instructionAt n = lookupInstruction . cellAt n
currentInstruction :: Env -> Instruction
currentInstruction = lookupInstruction . currentCell
runCurrentInstruction :: Instruction
runCurrentInstruction env = currentInstruction env env
nop :: Instruction
nop = return
swap :: Instruction
swap env = return $ pushStack a $ pushStack b $ popStack $ popStack env
where
b = topStack env
a = topStack $ popStack env
inputDecimal :: Instruction
inputDecimal env = readLn >>= return . flip pushStack env
outputDecimal :: Instruction
outputDecimal env = putStr (show n ++ " ") >> return (popStack env)
where
n = topStack env
duplicate :: Instruction
duplicate env = return $ pushStack (topStack env) env
pushInteger :: Integer -> Instruction
pushInteger n = return . pushStack n
put :: Instruction
put env = return env' { cells = Map.insert loc c $ cells env'}
where
loc = topStack env
n = topStack $ popStack env
env' = popStack $ popStack env
c = Char . chr . fromIntegral $ n
trampoline :: Instruction
trampoline env = return env { position = position env + 1 }
fetch :: Instruction
fetch = trampoline >=> \env -> let
cell = currentCell env
val = case cell of
Char c -> fromIntegral $ ord c
Integer n -> n
in pushInteger val env
binOp :: (Integer -> Integer -> Integer) -> Instruction
binOp op env = return $ pushStack (a `op` b) $ popStack $ popStack env
where
b = topStack env
a = topStack $ popStack env
add :: Instruction
add = binOp (+)
subtract :: Instruction
subtract = binOp (-)
multiply :: Instruction
multiply = binOp (*)
divide :: Instruction
divide = binOp div
stop :: Instruction
stop = const exitSuccess
tick :: Instruction
tick = trampoline
-----------------------------------------------------------
buildCells :: String -> Map Integer Cell
buildCells = Map.fromList . zip [0..] . map Char . concat . eols
eols :: String -> [String]
eols "" = []
eols str = left : case right of
"" -> []
'\r':'\n':rest -> eols rest
_:rest -> eols rest
where
(left, right) = break (`elem` "\r\n") str
data Args = Args { sourceFileName :: String }
processArgs :: IO Args
processArgs = do
args <- getArgs
case args of
[] -> do
putStrLn "No source file! Exiting."
exitFailure
fileName:_ -> return $ Args { sourceFileName = fileName }
runUnefunge :: Env -> IO ExitCode
runUnefunge = iterateM round . return
where
round = runCurrentInstruction >=> tick
main :: IO ()
main = do
args <- processArgs
contents <- readFile $ sourceFileName args
let env = Env {
cells = buildCells contents
, position = 0
, stack = mkStack
}
mapM_ (`hSetBuffering` NoBuffering) [stdin, stdout]
handle return $ runUnefunge env
return ()
Ruby: 36 chars
a,b=gets.split.map(&:to_i);p a-a/b*b
Scheme: 38
(define(m a b)(- a(*(quotient a b)b)))
JavaScript, 11 chars
a-b*(0|a/b)
Assumes input integers are contained the variables a and b:
a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
PHP, 49 chars
Assuming query string input in the form of script.php?a=27&b=7 and short tags turned on:
<?echo($a=$_GET['a'])-(int)($a/$b=$_GET['b'])*$b;
(That could be shortened by four by taking out the single-quotes, but that would throw notices.)
With the vile register_globals turned on you can get it down to 25 chars:
<?echo $a-(int)($a/$b)*b;
Perl, 33 chars
Reading the inputs could probably be shortened further.
($a,$b)=#ARGV;print$a-$b*int$a/$b
Usage
$ perl -e "($a,$b)=#ARGV;print$a-$b*int$a/$b" 2457 766
159
Java. Just for fun
Assuming that s[0] and s[1] are ints. Not sure this is worth anything but it was a bit of fun.
Note that this won't suffer from the loop effect (large numbers) but will only work on whole numbers. Also this solution is equally fast no matter how large the numbers are. A large percentage of the answers provided will generate a huge recursive stack or take infinitely long if givin say a large number and a small divisor.
public class M
{
public static void main(String [] s)
{
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
System.out.println(a-a/b*b);
}
}
Bash, 21 chars
echo $(($1-$1/$2*$2))
C, 226 chars
Late entry: I decided to go for the least number of characters while avoiding arithmetic operations altogether. Instead, I use the file system to compute the result:
#include <stdio.h>
#define z "%d"
#define y(x)x=fopen(#x,"w");
#define g(x)ftell(x)
#define i(x)fputs(" ",x);
main(a,b){FILE*c,*d;scanf(z z,&a,&b);y(c)y(d)while(g(c)!=a){i(c)i(d)if(g(d)==b)fseek(d,0,0);}printf(z,g(d));}
Java: 127 Chars
import java.util.*;enum M{M;M(){Scanner s=new Scanner(System.in);int a=s.nextInt(),b=s.nextInt();System.out.println(a-a/b*b);}}
Note the program does work, but it also throws
Exception in thread "main" java.lang.NoSuchMethodError: main
after the inputs are entered and after the output is outputted.
Common Lisp, 170 chars (including indentation):
(defun mod-divide()
(flet((g(p)(format t"Input of ~a number:"p)(read)))
(let*((a(g"first"))(b(g"second")))
(format t "Result:~d~%"(- a(* b(truncate a b)))))))
Old version (187 characters):
(defun mod-divide()
(flet((g(p)(format t"Input of ~a number:"p)(read)))
(let*((a(g"first"))(b(g"second")))
(multiple-value-bind(a b)(truncate a b)(format t "Result:~d~%"b)))))
DC: 8 chars
odO/O*-p
$ echo '17 3 odO/O*-p' | dc
2
Java, 110 chars
class C{public static void main(String[]a){Long x=new Long(a[0]),y=x.decode(a[1]);System.out.print(x-x/y*y);}}
Rebmu: 10 chars (no I/O) and 15 chars (with I/O)
If I/O is not required as part of the program source and you're willing to pass in named arguments then we can get 10 characters:
>> rebmu/args [sbJmpDVjKk] [j: 20 k: 7]
== 6
If I/O is required then that takes it to 15:
>> rebmu [rJrKwSBjMPdvJkK]
Input Integer: 42
Input Integer: 13
3
But using multiplication and division isn't as interesting (or inefficient) as this 17-character solution:
rJrKwWGEjK[JsbJk]
Which under the hood is turned into the equivalent:
r j r k w wge j k [j: sb j k]
Documented:
r j ; read j from user
r k ; read k from user
; write out the result of...
w (
; while j is greater than or equal to k
wge j k [
; assign to j the result of subtracting k from j
j: sb j k
]
; when a while loop exits the expression of the while will have the
; value of the last calculation inside the loop body. In this case,
; that last calculation was an assignment to j, and will have the
; value of j
)
Perl 25 characters
<>=~/ /;say$`-$'*int$`/$'
usage:
echo 15 6 | perl modulo.pl
3
Haskell, 30 chars
m a b=a-last((a-b):[b,2*b..a])
This is my first code golf, be free to comment on code and post improvements. ;-)
I know I won't win, but I just wanted to share my solution using lists.
In ruby with 38 chars
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
Not a winner :(
DC: 7 Chars (maybe 5 ;)
??37axp
Used as follows:
echo "X\nY" | dc -e "??37axp"
[And, referencing some other examples above, if input is allowed to be inserted into the code, it can be 5 chars:
37axp
as in:
dc -e "17 3 37axp"
Just thought it worth a mention]
F#, 268 chars
Did I win?
printf "Input of first number:"
let x = stdin.ReadLine() |> int
printf "Input of second number:"
let y = stdin.ReadLine() |> int
let mutable z = x
while z >= 0 do
z <- z - y
// whoops, overshot
z <- z + y
// I'm not drunk, really
printfn "Result:%d" z
I was reading Joel's book where he was suggesting as interview question:
Write a program to reverse the "ON" bits in a given byte.
I only can think of a solution using C.
Asking here so you can show me how to do in a Non C way (if possible)
I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means:
return 0;
What specifically does that question mean?
Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing all the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, ~, that does this. For example:
unsigned char b = 102; /* 0x66, 01100110 */
unsigned char reverse = ~b; /* 0x99, 10011001 */
What specifically does that question mean?
Does reverse mean setting 1's to 0's and vice versa?
Or does it mean 00001100 --> 00110000 where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie. 00110101 --> 00101011?
Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version:
; al is input register
; bl is output register
xor bl, bl ; clear output
; first bit
rcl al, 1 ; rotate al through carry
rcr bl, 1 ; rotate carry into bl
; duplicate above 2-line statements 7 more times for the other bits
not the most optimal solution, a table lookup is faster.
Reversing the order of bits in C#:
byte ReverseByte(byte b)
{
byte r = 0;
for(int i=0; i<8; i++)
{
int mask = 1 << i;
int bit = (b & mask) >> i;
int reversedMask = bit << (7 - i);
r |= (byte)reversedMask;
}
return r;
}
I'm sure there are more clever ways of doing it but in that precise case, the interview question is meant to determine if you know bitwise operations so I guess this solution would work.
In an interview, the interviewer usually wants to know how you find a solution, what are you problem solving skills, if it's clean or if it's a hack. So don't come up with too much of a clever solution because that will probably mean you found it somewhere on the Internet beforehand. Don't try to fake that you don't know it neither and that you just come up with the answer because you are a genius, this is will be even worst if she figures out since you are basically lying.
If you're talking about switching 1's to 0's and 0's to 1's, using Ruby:
n = 0b11001100
~n
If you mean reverse the order:
n = 0b11001100
eval("0b" + n.to_s(2).reverse)
If you mean counting the on bits, as mentioned by another user:
n = 123
count = 0
0.upto(8) { |i| count = count + n[i] }
♥ Ruby
I'm probably misremembering, but I
thought that Joel's question was about
counting the "on" bits rather than
reversing them.
Here you go:
#include <stdio.h>
int countBits(unsigned char byte);
int main(){
FILE* out = fopen( "bitcount.c" ,"w");
int i;
fprintf(out, "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n");
fprintf(out, "int bitcount[256] = {");
for(i=0;i<256;i++){
fprintf(out, "%i", countBits((unsigned char)i));
if( i < 255 ) fprintf(out, ", ");
}
fprintf(out, "};\n\n");
fprintf(out, "int main(){\n");
fprintf(out, "srand ( time(NULL) );\n");
fprintf(out, "\tint num = rand() %% 256;\n");
fprintf(out, "\tprintf(\"The byte %%i has %%i bits set to ON.\\n\", num, bitcount[num]);\n");
fprintf(out, "\treturn 0;\n");
fprintf(out, "}\n");
fclose(out);
return 0;
}
int countBits(unsigned char byte){
unsigned char mask = 1;
int count = 0;
while(mask){
if( mask&byte ) count++;
mask <<= 1;
}
return count;
}
The classic Bit Hacks page has several (really very clever) ways to do this, but it's all in C. Any language derived from C syntax (notably Java) will likely have similar methods. I'm sure we'll get some Haskell versions in this thread ;)
byte ReverseByte(byte b)
{
return b ^ 0xff;
}
That works if ^ is XOR in your language, but not if it's AND, which it often is.
And here's a version directly cut and pasted from OpenJDK, which is interesting because it involves no loop. On the other hand, unlike the Scheme version I posted, this version only works for 32-bit and 64-bit numbers. :-)
32-bit version:
public static int reverse(int i) {
// HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
64-bit version:
public static long reverse(long i) {
// HD, Figure 7-1
i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
i = (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
return i;
}
pseudo code..
while (Read())
Write(0);
I'm probably misremembering, but I thought that Joel's question was about counting the "on" bits rather than reversing them.
Here's the obligatory Haskell soln for complementing the bits, it uses the library function, complement:
import Data.Bits
import Data.Int
i = 123::Int
i32 = 123::Int32
i64 = 123::Int64
var2 = 123::Integer
test1 = sho i
test2 = sho i32
test3 = sho i64
test4 = sho var2 -- Exception
sho i = putStrLn $ showBits i ++ "\n" ++ (showBits $complement i)
showBits v = concatMap f (showBits2 v) where
f False = "0"
f True = "1"
showBits2 v = map (testBit v) [0..(bitSize v - 1)]
If the question means to flip all the bits, and you aren't allowed to use C-like operators such as XOR and NOT, then this will work:
bFlipped = -1 - bInput;
I'd modify palmsey's second example, eliminating a bug and eliminating the eval:
n = 0b11001100
n.to_s(2).rjust(8, '0').reverse.to_i(2)
The rjust is important if the number to be bitwise-reversed is a fixed-length bit field -- without it, the reverse of 0b00101010 would be 0b10101 rather than the correct 0b01010100. (Obviously, the 8 should be replaced with the length in question.) I just got tripped up by this one.
Asking here so you can show me how to do in a Non C way (if possible)
Say you have the number 10101010. To change 1s to 0s (and vice versa) you just use XOR:
10101010
^11111111
--------
01010101
Doing it by hand is about as "Non C" as you'll get.
However from the wording of the question it really sounds like it's only turning off "ON" bits... In which case the answer is zero (as has already been mentioned) (unless of course the question is actually asking to swap the order of the bits).
Since the question asked for a non-C way, here's a Scheme implementation, cheerfully plagiarised from SLIB:
(define (bit-reverse k n)
(do ((m (if (negative? n) (lognot n) n) (arithmetic-shift m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (arithmetic-shift rvs 1) (logand 1 m))))
((negative? k) (if (negative? n) (lognot rvs) rvs))))
(define (reverse-bit-field n start end)
(define width (- end start))
(let ((mask (lognot (ash -1 width))))
(define zn (logand mask (arithmetic-shift n (- start))))
(logior (arithmetic-shift (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n))))
Rewritten as C (for people unfamiliar with Scheme), it'd look something like this (with the understanding that in Scheme, numbers can be arbitrarily big):
int
bit_reverse(int k, int n)
{
int m = n < 0 ? ~n : n;
int rvs = 0;
while (--k >= 0) {
rvs = (rvs << 1) | (m & 1);
m >>= 1;
}
return n < 0 ? ~rvs : rvs;
}
int
reverse_bit_field(int n, int start, int end)
{
int width = end - start;
int mask = ~(-1 << width);
int zn = mask & (n >> start);
return (bit_reverse(width, zn) << start) | (~(mask << start) & n);
}
Reversing the bits.
For example we have a number represented by 01101011 . Now if we reverse the bits then this number will become 11010110. Now to achieve this you should first know how to do swap two bits in a number.
Swapping two bits in a number:-
XOR both the bits with one and see if results are different. If they are not then both the bits are same otherwise XOR both the bits with XOR and save it in its original number;
Now for reversing the number
FOR I less than Numberofbits/2
swap(Number,I,NumberOfBits-1-I);