How do I unescape a html attribute value in Prolog? - html

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

Related

Encode an image as a base64 string in MATLAB

Currently, I have an image stored as an MxNx3 uint8 array in MATLAB. However, I need to embed it in an HTML document, and I can't include the image separately.
Instead, I've decided to try and encode the image as a base64 string. However, I can't seem to find a way to encode the image as a string without having to first save the image to disk. I tried looking into writebmp and the like, but I can't seem to get it to work.
I'd really rather not write the image to a file, just to read it back using fread. The computer I'm using has very low Disk I/O, so that will take way too long.
Any help would be appreciated!
Edit:
I looked here, but that errors in R2018b due to "no method found". When I linearize the image, the returned string is incorrect
From an image matrix to HTML
1 Convert the image to the bytes of a BMP
function [header] = writeBMP(IM)
header = uint8([66;77;118;5;0;0;0;0;0;0;54;0;0;0;40;0;0;0;21;0;0;0;21;0;0;0;1;0;24;0;0;0;0;0;64;5;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0]);
IMr = IM(:,:,1);
IMg = IM(:,:,2);
IMb = IM(:,:,3);clear IM;
IM(:,:,1)=IMb';
IM(:,:,2)=IMg';
IM(:,:,3)=IMr';
IM(:,:,:)=IM(:,end:-1:1,:);
[i,j,~]=size(IM);
header(19:22) = typecast(int32(i),'uint8'); %width
header(23:26) = typecast(int32(j),'uint8'); %height
IM = permute(IM,[3,1,2]);
IM = reshape(IM,[i*3,j]);
W = double(i)*3;
W = ceil(W/4)*4;
IM(3*i+1:W,:)=0; %padd zeros
IM = IM(:); %linear
header(35:38) = typecast(uint32(length(IM)),'uint8'); %datasize
header = [header;IM];
header(3:6) = typecast(uint32(length(header)),'uint8'); %filesize
end
You can also look into ...\toolbox\matlab\imagesci\private\writebmp.m for a more detailed example.
2 Encode the bytes to base64 characters
This is best done in a mex-file.
Save this code as encodeB64.c and run mex encodeB64.c
/*==========================================================
* encodeB64.c - converts a byte vector to base64
*
* The calling syntax is:
*
* [B] = encodeB64(B)
*
* input: - B : vector of uint8
*
* output: - B : vector of base64 char
*
* This is a MEX-file for MATLAB.
*
*========================================================*/
#include "mex.h"
/* The computational routine */
void Convert(unsigned char *in, unsigned char *out,unsigned long Nin, unsigned long Nout)
{
int temp;
static unsigned char alphabet[64] = {65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47};
for (int i=0;i<(Nin-2);i+=3){
temp = in[i+2] | (int)in[i+1]<<8 | (int)in[i]<<16;
for (int j=0;j<4;j++){
out[3+(i/3)*4-j] = alphabet[(temp >> (j*6)) & 0x3f];
}
}
if (Nin%3==1){
temp = (int)in[Nin-1]<<16;
out[Nout-1] = 61;
out[Nout-2] = 61;
out[Nout-3] = alphabet[(temp >> 12) & 0x3f];
out[Nout-4] = alphabet[(temp >> 18) & 0x3f];
}
if (Nin%3==2){
temp = in[Nin-1]<<8 | (int)in[Nin-2]<<16;
out[Nout-1] = 61;
out[Nout-2] = alphabet[(temp >> 6) & 0x3f];
out[Nout-3] = alphabet[(temp >> 12) & 0x3f];
out[Nout-4] = alphabet[(temp >> 18) & 0x3f];
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
unsigned char *InputV; /* input vector 1*/
unsigned char *OutputV; /* output vector 1*/
unsigned long Nin;
unsigned long Nout;
/* check for proper number of arguments */
if(nrhs!=1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","One inputs required.");
}
if(nlhs!=1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One output required.");
}
/* make sure the first input argument is scalar integer*/
if( !mxIsClass(prhs[0],"uint8") || mxGetNumberOfElements(prhs[0]) == 1 || mxGetN(prhs[0]) != 1) {
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notRowInteger","Input one must be uint8 column vector.");
}
/* get the value of the scalar input */
InputV = mxGetPr(prhs[0]);
Nin = mxGetM(prhs[0]); /*number of input bytes */
Nout = 4*((Nin+2)/3);
/* create the output matrix */
plhs[0] = mxCreateNumericMatrix((mwSize)Nout,1,mxUINT8_CLASS,mxREAL);
/* get a pointer to the real data in the output matrix */
OutputV = (unsigned char *) mxGetData(plhs[0]);
/* call the computational routine */
Convert(InputV,OutputV,Nin,Nout);
}
To test it you can run
T = randi(255,[2^28,1],'uint8'); %250MB random data
tic;Res=encodeB64(T);t=toc %convert
(length(T)/2^20) / t %read in MB/s
(length(Res)/2^20) / t %write in MB/s
My result:
read: 467 MB/s write: 623 MB/s
3 Put it all together and test
file = 'test.html';
fid = fopen(file,'wt');
fwrite(fid,sprintf('<html>\n<header> </header>\n<body>\n'));
fwrite(fid,sprintf('<p>%s</p>\n','Show the Matlab demo image street1.jpg'));
IM = imread('street1.jpg');figure(1);clf;image(IM);
B = writeBMP(IM);
str = encodeB64(B);
fwrite(fid,sprintf('<img src="data:image/bmp;base64,%s"/>\n',str));
fwrite(fid,sprintf('</body>\n</html>'));
fclose(fid);
this should generate a 1,229,008 byte HTML file with an image encoded.

Reversing every character in a file

I'm in a little trouble here.
Can anyone help me implement a solution that reverses every byte so 0xAB becomes 0xBA but not so "abcd" becomes "dcba". I need it so AB CD EF becomes BA DC FE.
Preferably in C or C++ but it doesn't really matter provided it can run.
So far, I've implemented a UBER CRAPPY solution that doesn't even work (and yes, I know that converting to string and back to binary is a crappy solution) in PureBasic.
OpenConsole()
filename$ = OpenFileRequester("Open File","","All types | *.*",0)
If filename$ = ""
End
EndIf
OpenFile(0,filename$)
*Byte = AllocateMemory(1)
ProcessedBytes = 0
Loc=Loc(0)
Repeat
FileSeek(0,Loc(0)+1)
PokeB(*Byte,ReadByte(0))
BitStr$ = RSet(Bin(Asc(PeekS(*Byte))),16,"0")
FirstStr$ = Left(BitStr$,8)
SecondStr$ = Right(BitStr$,8)
BitStr$ = SecondStr$ + FirstStr$
Bit.b = Val(BitStr$)
WriteByte(0,Bit)
ProcessedBytes = ProcessedBytes + 1
ClearConsole()
Print("Processed Bytes: ")
Print(Str(ProcessedBytes))
Loc=Loc(0)
Until Loc = Lof(0)
Delay(10000)
Thanks for reading.
Reading your PureBasic code (I skipped it at first), it does seem you want to swap endian, even though it's not what your text is asking—0xAB practically always means a byte with decimal value 171, not two bytes, and it's extremely common to display a byte as two hex digits, where you use A-F in your example.
#include <iostream>
int main() {
using namespace std;
for (char a; cin.get(a);) {
char b;
if (!cin.get(b)) {
cout.put(a); // better to write it than lose it
cerr << "Damn it, input ends with an odd byte, is it in "
"the right format?\n";
return 1;
}
cout.put(b);
cout.put(a);
}
return 0;
}
// C version is a similar easy translation from the original code
import numpy
import sys
numpy.fromfile(sys.stdin, numpy.int16).byteswap(True).tofile(sys.stdout)
Original answer:
I'm not sure why you want this (it doesn't convert endian, for example, if you want that), but here you go:
#include <stdio.h>
int main() {
for (char c; (c == getchar()) != EOF;) {
putchar((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
}
return 0;
}
#include <iostream>
int main() {
for (char c; std::cin.get(c);) {
std::cout.put((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
}
return 0;
}
import sys
for line in sys.stdin:
sys.stdout.write("".join(
chr((ord(c) & 0xF << 4) | (ord(c) & 0xF0 >> 4))
for c in line
))
All assume that text translations don't occur (such as \n to \r\n and vice versa); you'll have to change them to opening files in binary mode if that's the case. They read from stdin and write to stdout, if you're unfamiliar with that, so just use programname < inputfile > outputfile to run them.
Reversing the high and low half-byte is possible through a simple arithmetic formula (assuming you operate on unsigned bytes):
reversed = (original % 16) * 16 + (original / 16);
A Haskell solution:
module ReverseBytes where
import qualified Data.ByteString as B
import Data.Bits
import Data.Word
-----------------------------------------------------------
main :: IO ()
main = B.getContents >>= B.putStr . B.map reverseByte
reverseByte :: Word8 -> Word8
reverseByte = flip rotate 4
runghc ReverseBytes.hs < inputfile > outputfile

Code Golf: Hourglass

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 output an hourglass according to user input.
Input is composed of two numbers: First number is a greater than 1 integer that represents the height of the bulbs, second number is a percentage (0 - 100) of the hourglass' capacity.
The hourglass' height is made by adding more lines to the hourglass' bulbs, so size 2 (the minimal accepted size) would be:
_____
\ /
\ /
/ \
/___\
Size 3 will add more lines making the bulbs be able to fit more 'sand'.
Sand will be drawn using the character x. The top bulb will contain N percent 'sand' while the bottom bulb will contain (100 - N) percent sand, where N is the second variable.
'Capacity' is measured by the amount of spaces () the hourglass contains. Where percentage is not exact, it should be rounded up.
Sand is drawn from outside in, giving the right side precedence in case percentage result is even.
Test cases
Input:
3 71%
Output:
_______
\x xx/
\xxx/
\x/
/ \
/ \
/__xx_\
Input:
5 52%
Output:
___________
\ /
\xx xx/
\xxxxx/
\xxx/
\x/
/ \
/ \
/ \
/ xxx \
/xxxxxxxxx\
Input:
6 75%
Output:
_____________
\x x/
\xxxxxxxxx/
\xxxxxxx/
\xxxxx/
\xxx/
\x/
/ \
/ \
/ \
/ \
/ \
/_xxxxxxxxx_\
Code count includes input/output (i.e full program).
C/C++, a dismal 945 characters...
Takes input as parameters:
a.out 5 52%
#include<stdio.h>
#include<memory.h>
#include<stdlib.h>
#define p printf
int h,c,*l,i,w,j,*q,k;const char*
z;int main(int argc,char**argv)
{h=atoi(argv[1]);c=(h*h*atoi(
argv[2])+99)/100;l=new int[
h*3];for(q=l,i=0,w=1;i<h;
i++,c=(c-w)&~((c-w)>>31
),w+=2)if(c>=w){*q++=
0;*q++ =0;* q++=w;}
else {*q++=(c+1)/
2;*q++=w-c;*q++
=c/2;}p("_");
for(i=0;i<h
;i ++)p (
"__");p
("\n"
);q
=
l+h
*3-1;
for (i=
--h;i>=0;
i--){p("%*"
"s\\",h-i,"")
; z= "x\0 \0x";
for(k=0;k<3;k++,q
--,z+=2)for(j=0;j<*
q;j++)p(z);q-=0;p("/"
"\n");}q=l;for(i=0;i<=h
;i++){z =i==h? "_\0x\0_":
" \0x\0 ";p("%*s/",h-i,"");
for(k=0;k<3;k++,q++,z+=2)for(
j=0;j<*q;j++)p(z);p("\\\n") ;}}
...and the decrypted version of this for us mere humans:
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#define p printf
int h, c, *l, i, w, j, *q, k;
const char *z;
int main(int argc, char** argv)
{
h = atoi(argv [1]);
c = (h*h*atoi(argv[2])+99)/100;
l = new int[h*3];
for (q = l,i = 0,w = 1; i<h; i++,c = (c-w)&~((c-w)>>31),w += 2) {
if (c>=w) {
*q++ = 0;
*q++ = 0;
*q++ = w;
} else {
*q++ = (c+1)/2;
*q++ = w-c;
*q++ = c/2;
}
}
p("_");
for (i = 0; i<h; i++) {
p("__");
}
p("\n");
q = l+h*3-1;
for (i = --h; i>=0; i--) {
p("%*s\\",h-i,"");
z = "x\0 \0x";
for (k = 0; k<3; k++,q--,z += 2) {
for (j = 0; j<*q; j++) {
p(z);
}
}
p("/\n");
}
q = l;
for (i = 0; i<=h; i++) {
z = i==h ? "_\0x\0_" : " \0x\0 ";
p("%*s/",h-i,"");
for (k = 0; k<3; k++,q++,z += 2) {
for (j = 0; j<*q; j++) {
p(z);
}
}
p("\\\n") ;
}
}
Perl, 191 char
205 199 191 chars.
$S=-int((1-.01*pop)*($N=pop)*$N)+$N*$N;$S-=$s=$S>++$r?$r:$S,
$\=$/.$"x$N."\\".x x($v=$s/2).$"x($t=$r++-$s).x x($w=$v+.5)."/$\
".$"x$N."/".($^=$N?$":_)x$w.x x$t.$^x$v."\\"while$N--;print$^x++$r
Explicit newline required between the 2nd and 3rd lines.
And with help of the new Acme::AsciiArtinator module:
$S=-int((1-.01*pop)*($N=pop
) *
$ N
) +
$ N
*$N;( ${B},$
F,${x})=qw(\\ / x
);while($N){;/l
ater/g;$S-=$s
=$S>++$r?$r
:$S;'than
you';#o
=(" "
x--
$ N
. $
B .
x x
( $
v =
$ s
/ 2
) .$"x($t= $
r++-$s).x x($w=$v+.5)
.$F,#o,$"x$N.$F.($^=$N?
$":_)x$w.x x$t.$^x$v.$B);
$,=$/}print$^x++$r,#o;think
Golfscript - 136 Chars (Fits in a Tweet)
Be sure not to have a newline after the % for the input
eg
$ echo -n 3 71%|./golfscript.rb hourglass.gs
You can animate the hourglass like this:
$ for((c=100;c>=0;c--));do echo -n "15 $c%"|./golfscript.rb hourglass.gs;echo;sleep 0.1;done;
Golfscript - 136 Chars
Make sure you don't save it with an extra newline on the end or it will print an extra number
);' ': /(~:
;0=~100.#-
.**\/:t;'_':&&
*.n
,{:y *.'\\'+{[&'x':x]0t(:t>=}:S~
(y-,{;S\+S+.}%;'/'++\+}%.{&/ *}%\-1%{-1%x/ *&/x*}%) /&[*]++n*
Golfscript - 144 Chars
);' ':|/(~:^.*:X
;0=~100.#-X*\/
X'x':x*'_':&
#*+:s;&&&+
^*n^,{:y
|*.[92
]+{s
[)
\#
:s;]
}:S~^(
y-,{;S\+
S+.}%;'/'+
+\+}%.{&/|*}
%\-1%{-1%x/|*&
/x*}%)|/&[*]++n*
How it works
First do the top line of underscores which is 2n+1
Create the top half of the hourglass, but use '_' chars instead of spaces, so for the 3 71% we would have.
\x__xx/
\xxx/
\x/
Complete the top half by replacing the "_" with " " but save a copy to generate the bottom half
The bottom half is created by reversing the whole thing
/x\
/xxx\
/xx__x\
Replacing all the 'x' with ' ' and then then '_' with 'x'
/ \
/ \
/ xx \
Finally replace the ' ' in the bottom row with '_'
/ \
/ \
/__xx_\
Roundabout but for me, the code turned out shorter than trying to generate both halves at once
Python, 213 char
N,p=map(int,raw_input()[:-1].split())
S=N*N-N*N*(100-p)/100
_,e,x,b,f,n=C='_ x\/\n'
o=""
r=1
while N:N-=1;z=C[N>0];s=min(S,r);S-=s;t=r-s;v=s/2;w=s-v;r+=2;o=n+e*N+b+x*v+e*t+x*w+f+o+n+e*N+f+z*w+x*t+z*v+b
print _*r+o
Rebmu: 188 chars
rJ N 0% rN Wad1mpJ2 S{ \x/ }D0 Hc&[u[Z=~wA Qs^RTkW[isEL0c[skQdvK2][eEV?kQ[tlQ]]pcSeg--B0[eZ1 5]3]prRJ[si^DspSCsQfhS]eZ1[s+DcA+wMPc2no]]]Va|[mpAj**2]prSI^w{_}Ls+W2 h1tiVsb1n -1 chRVs{_}hLceVn1
It's competitive with the shorter solutions here, though it's actually solving the problem in a "naive" way. More or less it's doing the "sand physics" instead of exploiting symmetries or rotating matrices or anything.
H defines a function for printing a half of an hourglass, to which you pass in a number which is how many spaces to print before you start printing "x" characters. If you're on the top half, the sand string is constructed by alternating appends to the head and the tail. If you're on the bottom it picks the insertion source by skipping into the middle of the string. Commented source available at:
http://github.com/hostilefork/rebmu/blob/master/examples/hourglass.rebmu
But the real trick up Rebmu's sleeve is it's a thin dialect that doesn't break any of the parsing rules of its host language (Rebol). You can turn this into a Doomsday visualization by injecting ordinary code right in the middle, as long you code in lowercase:
>> rebmu [rJ birthday: to-date (ask "When were you born? ") n: (21-dec-2012 - now/date) / (21-dec-2012 - birthday) Wad1mpJ2 S{ \x/ }D0 Hc~[u[Ze?Wa Qs^RTkW[isEL0c[skQdvK2][eEV?kQ[tlQ]]pcSeg--B0[eZ1 5]3]prRJ[si^DspSCsQfhS]eZ1[s+DcA+wMPc2no]]]Va|[mpAj**2]prSI^w{_}Ls+W2h1tiVsb1n -1 chRVs{_}hLceVn1]
Input Integer: 10
When were you born? 23-May-1974
_____________________
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\x xx/
\xxx/
\x/
/ \
/ \
/ xx \
/xxxxxxx\
/xxxxxxxxx\
/xxxxxxxxxxx\
/xxxxxxxxxxxxx\
/xxxxxxxxxxxxxxx\
/xxxxxxxxxxxxxxxxx\
/xxxxxxxxxxxxxxxxxxx\
O noes! :)
(Note: A major reason I'm able to write and debug Rebmu programs is because I can break into ordinary coding at any point to use the existing debugging tools/etc.)
Haskell. 285 characters. (Side-effect-free!)
x n c=h s++'\n':reverse(h(flip s)) where h s=r w '-'++s '+' b(w-2)0 p;w=(t n);p=d(n*n*c)100
s x n i o p|i>0='\n':l++s x n(i-2)(o+1)(max(p-i)0)|True=[] where l=r o b++'\\':f d++r(i#p)n++f m++'/':r o b;f g=r(g(i-(i#p))2)x
b=' '
r=replicate
t n=1+2*n
d=div
(#)=min
m=(uncurry(+).).divMod
Run with e.g. x 5 50
A c++ answer, is 592 chars so far, still having reasonable formatting.
#include<iostream>
#include<string>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef string S;
typedef int I;
typedef char C;
I main(I,C**v){
I z=atoi(v[1]),c=z*z,f=ceil(c*atoi(v[2])/100.);
cout<<S(z*2+1,'_')<<'\n';
for(I i=z,n=c;i;--i){
I y=i*2-1;
S s(y,' ');
C*l=&s[0];
C*r=&s[y];
for(I j=0;j<y;++j)
if(n--<=f)*((j&1)?l++:--r)='x';
cout<<S(z-i,' ')<<'\\'<<s<<"/\n";
}
for(I i=1,n=c-f;i<=z;++i){
I y=i*2-1;
S s(y,'x');
C*l=&s[0];
C*r=&s[y];
for(I j=0;j<y;++j)
if(n++<c)*(!(j&1)?l++:--r)=(i==z)?'_':' ';
cout<<S(z-i,' ')<<'/'<<s<<"\\\n";
}
}
If i decide to just forget formatting it reasonably, i can get it as low as 531:
#include<iostream>
#include<string>
#include<cstdlib>
#include<cmath>
using namespace std;typedef string S;typedef int I;typedef char C;I main(I,C**v){I z=atoi(v[1]),c=z*z,f=ceil(c*atoi(v[2])/100.);cout<<S(z*2+1,'_')<<'\n';for(I i=z,n=c;i;--i){I y=i*2-1;S s(y,' ');C*l=&s[0];C*r=&s[y];for(I j=0;j<y;++j)if(n--<=f)*((j&1)?l++:--r)='x';cout<<S(z-i,' ')<<'\\'<<s<<"/\n";}for(I i=1,n=c-f;i<=z;++i){I y=i*2-1;S s(y,'x');C*l=&s[0];C*r=&s[y];for(I j=0;j<y;++j)if(n++<c)*(!(j&1)?l++:--r)=(i==z)?'_':' ';cout<<S(z-i,' ')<<'/'<<s<<"\\\n";}}
Bash: 639 - 373 characters
I thought I would give bash a try (haven't seen much code-golfing in it). (my version: GNU bash, version 3.2.48(1)-release (i486-pc-linux-gnu))
Based on Mobrule's nice python answer.
Optimizations must still be available, so all suggestions are welcome!
Start from the command line, e.g. : ./hourglass.sh 7 34%
function f () { for i in `seq $1`;do printf "$2";done; }
N=$1;S=$[$1*$1-$1*$1*$[100-${2/\%/}]/100]
b='\';o=$b;n="\n";r=1;while [ $N -gt 0 ];do
N=$[N-1];z=" ";s=$r;[ $N -eq 0 ]&& z=_;[ $S -lt $r ]&& s=$S
S=$[S-s];t=$[r-s];v=$[s/2];w=$[s-v];r=$[r+2]
o=$n`f $N " "`$b`f $v x;f $t " ";f $w x`/$o$b$n`f $N " "`/`f $w "$z";f $t x;f $v "$z"`$b
done;f $r _;echo -e "${o/\/\\\\//}"
Java; 661 characters
public class M{public static void main(String[] a){int h=Integer.parseInt(a[0]);int s=(int)Math.ceil(h*h*Integer.parseInt(a[1])/100.);r(h,h-1,s,true);r(h,h-1,s,false);}static void r(int h,int c,int r,boolean t){if(c<0)return;int u=2*(h-c)-1;if(t&&c==h-1)p(2*h+1,0,'_','_',true,0,false);int z=r>=u?u:r;r-=z;if(t)r(h,c-1,r,true);p(u,z,t?'x':((c==0)?'_':' '),t?' ':'x',t,c,true);if(!t)r(h,c-1,r,false);}static void p(int s,int n,char o,char i,boolean t,int p,boolean d){int f=(s-n);int q=n/2+(!t&&(f%2==0)?1:0);int e=q+f;String z = "";int j;for(j=0;j<p+4;j++)z+=" ";if(d)z+=t?'\\':'/';for(j=0;j<s;j++)z+=(j>=q&&j<e)?i:o;if(d)z+=t?'/':'\\';System.out.println(z);}}
I need to find a better set of golf clubs.
PHP - 361
<?$s=$argv[1];$x='str_pad';$w=$s*2-1;$o[]=$x('',$w+2,'_');
$r=$s*ceil($w/2);$w=$r-($r*substr($argv[2],0,-1)/100);$p=0;
$c=-1;while($s){$k=$s--*2-1;$f=$x($x('',min($k,$w),' '),$k,'x',2);
$g=$x($x('',min($k,$w),'x'),$k,' ',2);$w-=$k;$o[]=$x('',$p)."\\$f/";
$b[]=$x('',$p++)."/$g\\";}$b[0]=str_replace(' ','_',$b[0]);
krsort($b);echo implode("\n",array_merge($o,$b));?>
Python - 272 chars
X,p=map(int,raw_input()[:-1].split())
k=X*X;j=k*(100-p)/100
n,u,x,f,b,s='\n_x/\ '
S=list(x*k+s*j).pop;T=list(s*k+u*(2*X-j-1)+x*j).pop
A=B=""
for y in range(X):
r=S();q=T()
for i in range(X-y-1):r=S()+r+S();q+=T();q=T()+q
A+=n+s*y+b+r+f;B=n+s*y+f+q+b+B
print u+u*2*X+A+B
Exabyte18's java converted to C#, 655 bytes:
public class M {public static void Main(){int h = Convert.ToInt32(Console.ReadLine());
int s = Convert.ToInt32(h * h * Convert.ToInt32(Console.ReadLine()) / 100);r(h,h-1,s,true);
r(h,h-1,s,false);Console.ReadLine();}static void r(int h, int c, int r, bool t){
if(c<0) return;int u=2*(h-c)-1;if (t&&c==h-1)p(2*h+1,0,'_','_',true,0,false);
int z=r>=u?u:r; r-=z;if (t)M.r(h,c-1,r,true); p(u,z,t?'x':((c==0)?'_':' '), t?' ':'x',t,c,true);
if(!t)M.r(h,c-1,r,false);}static void p(int s, int n, char o, char i, bool t, int p, bool d)
{int f=(s-n);int q=n/2+(!t&&(f%2==0)?1:0);int e=q+f;string z="";int j;for(j=0;j<p+4;j++) z+=" ";if(d)z+=t?'\\':'/';
for (j=0;j<s;j++) z+=(j>=q&&j<e)?i:o; if(d)z+=t?'/':'\\';Console.WriteLine(z);}}
Ruby, 297 254 (after compression)
Run both with ruby -a -p f.rb
n,p = $F.map{|i|i.to_i}
r="\n"
y=''
g,s,u,f,b=%w{x \ _ / \\}
$> << u*2*n+u+r # draw initial underbar line
a=u
c=100.0/n/n # amount of sand a single x represents
e = 100.0 # percentage floor to indicate sand at this level
n.times{ |i|
d=2*n-1-2*i # number of spaces at this level
e-= c*d # update percentage floor
x = [((p - e)/c+0.5).to_i,d].min
x = 0 if x<0
w = x/2 # small half count
z = x-w # big half count
d = d-x # total padding count
$> << s*i+b+g*w+s*d+g*z+f+r
y=s*i+f+a*z+g*d+a*w+b+r+y
a=s
}
$_=y
Ruby, 211
This is mobrule's tour de force, in Ruby. (And still no final newline. :-)
m,p=$F.map{|i|i.to_i}
q=m*m-m*m*(100-p)/100
_,e,x,b,f=%w{_ \ x \\ /}
n="\n"
o=''
r=1
while m>0
m-=1
z=m>0?e:_
s=q<r ?q:r
q-=s
t=r-s
v=s/2
w=s-v
r=r+2
o=n+e*m+b+x*v+e*t+x*w+f+o+n+e*m+f+z*w+x*t+z*v+b
end
$_=_*r+o

Code Golf: Lights out

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..

How can I reverse the ON bits in a byte?

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);