JSFiddle - React, Tailwind, and code Playground
by asdf
JavaScript
// Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index. Discuss the runtime of the algorithm and how you can be sure there won't be any infinite loops.
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var indices = [ 2, 3, 4, 0, 5, 1];
function rearrangeArray(arr, indices) {
var temp, current, i;
if (arr.length !== indices.length) {
return arr;
}
current = arr[0];
i = indices[0];
count = 0;
while (i<indices.length) {
if (i < 0 || i === null) {
i = indices[++count];
current = arr[i];
continue;
}
temp = arr[i];
arr[i] = current;
current = temp;
temp = indices[i];
indices[i] ? (indices[i] *= -1) : indices[i]=null;
i=temp;
}
return arr;
}
console.log(rearrangeArray(arr, indices));