Created
November 8, 2021 21:40
-
-
Save cagataycali/666f73350d9674ffce036e3801846668 to your computer and use it in GitHub Desktop.
[JavaScript] Graph single cycle check
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
| const assert = require('assert'); | |
| function hasSingleCycle(array) { | |
| let numberOfVisitedNodes = 0; | |
| let currentIndex = 0; | |
| while (numberOfVisitedNodes < array.length) { | |
| // If we go back to the first element, | |
| // That shows, we have an infinite loop before our loop ends. | |
| if (currentIndex === 0 && numberOfVisitedNodes > 0) return false; | |
| currentIndex = jump(currentIndex, array); | |
| numberOfVisitedNodes++ | |
| } | |
| return currentIndex === 0; | |
| } | |
| function jump(currentIndex, array) { | |
| const nextIndex = (array[currentIndex] + currentIndex) % array.length | |
| // Cross the other side of array, | |
| if (nextIndex < 0) { | |
| return nextIndex + array.length; | |
| } | |
| return nextIndex; | |
| } | |
| assert.deepStrictEqual(hasSingleCycle([2, 3, 1, -4, -4, 2]), true) | |
| assert.deepStrictEqual(hasSingleCycle([1, 1, 1, -3]), true) | |
| assert.deepStrictEqual(hasSingleCycle([1, 1, 1, -2]), false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment