|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function arrayJumping(arr) take the |
| 3 | + * array of numbers stored in arr and first determine the largest element in the |
| 4 | + * array, and then determine whether or not you can reach that same element |
| 5 | + * within the array by moving left or right continuously according to whatever |
| 6 | + * integer is in the current spot. If you can reach the same spot within the |
| 7 | + * array, then your program should output the least amount of jumps it took. For |
| 8 | + * example: if the input is [2, 3, 5, 6, 1] you'll start at the spot where 6 is |
| 9 | + * and if you jump 6 spaces to the right while looping around the array you end |
| 10 | + * up at the last element where the 1 is. Then from here you jump 1 space to the |
| 11 | + * left and you're back where you started, so your program should output 2. If |
| 12 | + * it's impossible to end up back at the largest element in the array your |
| 13 | + * program should output -1. The largest element in the array will never equal |
| 14 | + * the number of elements in the array. The largest element will be unique. |
| 15 | + * |
| 16 | + * https://www.coderbyte.com/results/bhanson:Array%20Jumping:JavaScript |
| 17 | + * |
| 18 | + * @param {array} arr |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +function arrayJumping(arr) { |
| 22 | + const max = Math.max(...arr); |
| 23 | + const startIndex = arr.indexOf(max); |
| 24 | + |
| 25 | + // Iterative "breadth-first search" |
| 26 | + // `queue` stores an array of arrays. The inner arrays represent paths of |
| 27 | + // indexes. They all start with the index of the largest number and each |
| 28 | + // jump is appended and the entire new structure is stored in a new queue. |
| 29 | + |
| 30 | + let queue = [[startIndex]]; |
| 31 | + |
| 32 | + while (queue.length !== 0) { |
| 33 | + const nextQueue = []; |
| 34 | + |
| 35 | + for (let i = 0; i < queue.length; i++) { |
| 36 | + const indexList = queue[i]; |
| 37 | + const lastIndex = indexList[indexList.length - 1]; |
| 38 | + |
| 39 | + const left = |
| 40 | + (((lastIndex - arr[lastIndex]) % arr.length) + arr.length) % |
| 41 | + arr.length; |
| 42 | + const right = (lastIndex + arr[lastIndex]) % arr.length; |
| 43 | + |
| 44 | + if (left === startIndex || right === startIndex) { |
| 45 | + // Success! |
| 46 | + return indexList.length; |
| 47 | + } |
| 48 | + |
| 49 | + if (!indexList.includes(left)) { |
| 50 | + const leftArr = indexList.slice(); |
| 51 | + leftArr.push(left); |
| 52 | + nextQueue.push(leftArr); |
| 53 | + } |
| 54 | + |
| 55 | + if (!indexList.includes(right)) { |
| 56 | + const rightArr = indexList.slice(); |
| 57 | + rightArr.push(right); |
| 58 | + nextQueue.push(rightArr); |
| 59 | + } |
| 60 | + } |
| 61 | + queue = nextQueue; |
| 62 | + } |
| 63 | + |
| 64 | + // No path possible |
| 65 | + return -1; |
| 66 | +} |
| 67 | + |
| 68 | +module.exports = arrayJumping; |
0 commit comments