I'm working on this problem. Math is not one of strong suites. Any tips would be great. It is supposed to return an array of indices that are powers of 2.
function secondPower(arr) {
// Return an array containing all indices that are powers of 2
newArray = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] % (2 ** i) === 0 && arr[i] != 1){
newArray.push(arr[i]);
}
}
return newArray;
}
An example of the solution is
secondPower([1, 2, 3, 4, 5, 6, 7, 8])
returns
[2,3,5]
Using What is the best way to determine if a given number is a power of two?
const isPowerOf2 = v => v && !(v & (v - 1));
[1, 2, 3, 4, 5, 6, 7, 8].filter(isPowerOf2);
yields
[1, 2, 4, 8]
You can start at index 1 and keep multiplying by 2 until the value reaches the length of the array. This solution runs in logarithmic time and avoids a linear loop over all of the indexes.
function secondPower(arr) {
const res = [];
for(let i = 1; i < arr.length; i <<= 1) res.push(arr[i]);
return res;
}
console.log(secondPower([1, 2, 3, 4, 5, 6, 7, 8]));
// if a number is a power of 2 its base 2 logarithm is an integer
const result = [1, 2, 3, 4, 5, 6, 7, 8].reduce((a, v, i) => Number.isInteger(Math.log2(v)) ? a.concat(i) : a, []);
console.log(result);