Here is some code to visualize Project Euler Problem 502. The code scans for runs of bits in the binary representation of an integer, and outputs the beginning position of each run and the length of each run. The code is written in naive procedural style.
binaryRowGenAnalyze[w_,i_]:=Block[
{bits,state,newstate,c,starts,lengths},
bits=Reverse@PadLeft[IntegerDigits[i,2],w+1];
state="outside";
c=0;
Do[
newstate=bits[[j]]/.{0->"outside",1->"inside"};
If[{state,newstate}==={"outside","inside"},
c++;starts[c]=j
];
If[{state,newstate}==={"inside","outside"},
lengths[c]=j-starts[c]
];
state=newstate,
{j,w+1}
];
{
ArrayPlot[{Drop[bits,-1]/.{0->None,1->Brown}},Mesh->True,
Background->White],
Thread[{starts/@Range[c],lengths/@Range[c]}]
}
]
The only advantage of the code is that it runs correctly. Here is a tiny test suite:
binaryRowGenAnalyze[4,15]
(* {XXXX,{{1,4}}} *)
binaryRowGenAnalyze[4,5]
(* {XOXO,{{1,1},{3,1}}} *)
binaryRowGenAnalyze[4,10]
(* {OXOX,{{2,1},{4,1}}} *)
binaryRowGenAnalyze[4,11]
(* {XXOX,{{1,2},{4,1}}} *)
binaryRowGenAnalyze[4,14]
(* {OXXX,{{2,3}}} *)
The function Split
(Edit: not Gather
) seems tailor made for this problem, but I need some wizardry to recognize runs of ones over runs of zero, and to calculate the start positions.