int* binary (int nBits, int number)
{
int* bits = calloc(abs(number)+1, sizeof(int));
int i = 0;
int l = nBits - 1;
while(number > 0)
{
while(l >= 0)
{
int ln = 1 << l;
if(ln < number)
{
bits[i] = ln;
i++;
number -= ln;
}
else if(ln > number)
{
l--;
}
else /* Equal */
{
bits[i] = ln;
i++;
number -= ln;
return bits;
}
}
}
return bits;
}
I wrote this function in one go so it is probably quite rustic and I was curious to see what will happen if I subjected it to a review.
Provided any decimal @number and number of bits @nBits (for example 3 would mean that the function has to work with 1, 2, 4 bit representations) the function shall return the smallest sequence of bit representations (as an array of int
s) that when added, makes up to @number
In case the number is too big, bits may repeat.
I only tested it with the numbers 0-20 for which the result is:
0:
1: 1
2: 2
3: 2 1
4: 4
5: 4 1
6: 4 2
7: 4 2 1
8: 4 4
9: 4 4 1
10: 4 4 2
11: 4 4 2 1
12: 4 4 4
13: 4 4 4 1
14: 4 4 4 2
15: 4 4 4 2 1
16: 4 4 4 4
17: 4 4 4 4 1
18: 4 4 4 4 2
19: 4 4 4 4 2 1
20: 4 4 4 4 4
I am pretty sure the code can be optimized in terms of code quality, performance and memory. I intend to use it as an optimization for a large quantity of small entities in a game that I've been working on.
Example purpose:
Imagine in a game two objects A and B and we must create N number of entities E between them depending on the distance between A and B. Now to do that, C must be 1 pixel wide or tall (depending on the direction), which can result in a lot of C being created, which is inefficient. I figured I can draw the C entities with varying length (1, 2, 4, as much as I find for sufficient) and use such a function to distribute the appropriate number of them with the appropriate length. That way I will have much less entities created, but the line Cs make across A and B will be the same.
I was curious to see what will happen if I subjected it to a review
CR is about insights into working code (from one of your projects). You may be prompted to tell more about what the code is intended for (How does this[optimise large quantities] of small entities
?), and what makes you think it works. How aboutbinary(30, 987654321)
? \$\endgroup\$decimal @number
, how do you pass it tobinary()
, and how would you pass a non-decimal one? \$\endgroup\$