Created
October 10, 2018 18:50
-
-
Save bialesdaniel/8652ba81f9d55f12ce0effc46fd68102 to your computer and use it in GitHub Desktop.
Check if an array is a cycle where each value references how far away the next value is. A cycle must touch every value and end where it starts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isCycle(arr){ | |
let i = 0 | |
let itemsToTouch = arr.length | |
while(arr[i]!==0){ | |
itemsToTouch-- | |
const val = arr[i] | |
arr[i]=0 | |
if(i +val >=arr.length){ | |
i = (i + val) % arr.length | |
}else if(i+val <0){ | |
i = arr.length + ((i + val)% arr.length) | |
}else{ | |
i=i+val | |
} | |
} | |
return arr.every(item=>item===0) && itemsToTouch === 0 && i === 0 | |
} | |
console.log(isCycle([1,1])) | |
console.log(isCycle([2,2,2])) | |
console.log(isCycle([1,-4])) | |
console.log(isCycle([1,-4,2,2,-1])) | |
console.log(isCycle([1,1,1,-2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment