Given inputs 1-32 how can I generate the below output?
in. out
- 1
- 1
- 1
- 1
- 2
- 2
- 2
- 2
- 1
- 1
- 1
- 1
- 2
- 2
- 2
- 2
…
Edit Not Homework.. just lack of sleep.
I am working in C#, but I was looking for a language agnostic algorithm.
Edit 2 To provide a bit more background… I have an array of 32 items that represents a two dimensional checkerboard. I needed the last part of this algorithm to convert between the vector and the graph, where the index aligns on the black squares on the checkerboard.
Final Code:
--Index;
int row = Index >> 2;
int col = 2 * Index - (((Index & 0x04) >> 2 == 1) ? 2 : 1);
Assuming that you can use bitwise operators you can check what the numbers with same output have in common, in this case I preferred using input 0-31 because it’s simpler (you can just subtract 1 to actual values)
What you have?
It’s quite easy if you notice that third bit is always
0when output should be1and viceversa it’s always1when output should be2so:
EDIT
As suggested by comment it should work also with
because in some languages (like C)
0will evaluate tofalseand any other value totrue. I’m not sure if it works in C# too because I’ve never programmed in that language. Of course this is not a language-agnostic answer but it’s more C-elegant!