Here is a snippet from this answer to a related question:
const data = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0
]
function divide(data, size) {
const result = []
for (let i = 0; i < data.length; i += size) {
const chunk = data.slice(i, i + size);
result.push(chunk)
}
if (result.length > size) {
return divide(result, size)
}
return result;
}
const result = divide(data, 5);
console.log(result)
The data
array is simply an array of integers. However, when you run it through divide
, it produces a tree of nested arrays with a maximum size
of each array. How can I say "give me item number 42" in the tree version of the "compiled" array? For example, I want this 2 value right here, which is number 42 (index 41), if this is sorta what the tree looks like:
[ ]
[ ],[ ],[ ],[ ]
[ ],[ ],[ ],[ ],[ ] [ ],[ ],[ ],[ ],[ ] [ ],[ ],[ ],[ ],[ ] [ ],[ ],[ ],[ ],[ ]
1 6 1 6 1 6 1 6 1 6 1 6 1 6 1 6 1 6 1 6
2 7 2 7 2 7 2 7 (2) 7 2 7 2 7 2 7 2 7 2 7
3 8 3 8 3 8 3 8 3 8 3 8 3 8 3 8 3 8 3 8
4 9 4 9 4 9 4 9 4 9 4 9 4 9 4 9 4 9 4 9
5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0 5 0
The path to it is [0, 1, 3, 1]
. How can I quickly and most optimally get this path given the index 41 in the array? What is the general equation given the divide
function above and arbitrary chunking of the array into different sized bins?
This is as best as I can start so far, based on @Quade's answer:
let i = 42
let s = 5
let d = 3
let x = 0
let v = new Array(d)
while (d) {
if (i < s ** d) {
v[x] = 0
} else {
v[x] = Math.floor(i / (s ** d))
}
d--
x++
}