Henry Korir
asked on
Determinig Array index when given arrayan Element without using loops; array elements follow a set pattern where next element is twice the current element
Suppose the length of array is dynamic and the elements follow the same pattern where by the next element is half the previous element. For example
I would like to directly determine the index of an element. For example if I have
I have been thinking of using modulus or bit manipulation like shifts but I can't get it to work. How can this be achieved?
1024, 512, 256, 128...
I would like to directly determine the index of an element. For example if I have
512
I would output index
1
without looping through the elements and comparing them with 512 then output 1. i.e not like this:for (int i = 0; i < length; ++i) {
if (array[i] == 512) {
printf("%d\n", i);
break;
}
}
I have been thinking of using modulus or bit manipulation like shifts but I can't get it to work. How can this be achieved?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The solution works well and I have a shortcut:
index=logb2((array[0])/siz e);
where logb2() is a function to find log to base 2, array[0] is the first element in the array and it is the largest value in the array (the array is arranged in descending order), and size is the value which it's index in the array is being determined.
index=logb2((array[0])/siz
where logb2() is a function to find log to base 2, array[0] is the first element in the array and it is the largest value in the array (the array is arranged in descending order), and size is the value which it's index in the array is being determined.
Open in new window
In C the log is natural so you need to convert it to base 2. Then you substract the log result from the current array length, since you store them in descending order. This however depends on the value your array ends on and you might need to adjust to get the correct index. But may I ask why you need this array? Couldn't a function of n that returns the power 2^n achieve what you want to do?