My goal is to create a behavior similar to that of a radio group, where only one option can be selected at a time. For instance, if we start with the array [0, 1, 1, 1, 1, 1]
, the elements should be rearranged as follows:
index | array |
---|---|
0 |
[0, 1, 1, 1, 1, 1] |
1 |
[1, 0, 1, 1, 1, 1] |
2 |
[1, 1, 0, 1, 1, 1] |
3 |
[1, 1, 1, 0, 1, 1] |
4 |
[1, 1, 1, 1, 0, 1] |
5 |
[1, 1, 1, 1, 1, 0] |
I have developed a solution for this, but I believe it involves "extra work" in certain scenarios due to unnecessary loops.
function rearrange(array: number[], idx: number) {
let arr = array.slice();
let l = arr.length;
if (arr.indexOf(0) === idx) return arr;
while (arr.indexOf(0) !== idx) {
let swap;
for (let i = 0; i < l; i++) {
if (arr[i] === 0 || arr[i + 1] === 0) {
swap = arr[i];
if (i + 1 < l) {
arr[i] = arr[i + 1];
arr[i + 1] = swap;
}
if (i + 1 > l) {
arr[i] = arr[i - 1];
arr[i - 1] = swap;
}
}
}
}
return arr;
}
If you have any ideas on how to simplify or improve this process, please share them.