check if array is a loop

check if array is a loop

by Yurii Predborskyi

JavaScript

function checkForLoop(arr) {
  let p = arr[0], q = 0, inc = 1;
  while (p !== q) {
    if (p < 0 || p >= arr.length) {
      return false;
    }
    p = arr[p];
    if (p === q) break;
    if (inc++ % 2 === 0) {
      q = arr[q];
      inc = 1;
    }
  }
  return true;
}

let test = [1, 2, 1, 3, 4, 8];
let test2 = [1, 2, 3, 4, 5, 6];
let test3 = [0];
let test4 = [1, 2, 0];

console.log('expected true', checkForLoop(test));
console.log('expected false', checkForLoop(test2));
console.log('expected true', checkForLoop(test3));
console.log('expected true', checkForLoop(test4));