|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function gasStation(strArr) take |
| 3 | + * strArr which will be an an array consisting of the following elements: N |
| 4 | + * which will be the number of gas stations in a circular route and each |
| 5 | + * subsequent element will be the string g:c where g is the amount of gas in |
| 6 | + * gallons at that gas station and c will be the amount of gallons of gas needed |
| 7 | + * to get to the following gas station. For example strArr may be: |
| 8 | + * ["4","3:1","2:2","1:2","0:1"]. Your goal is to return the index of the |
| 9 | + * starting gas station that will allow you to travel around the whole route |
| 10 | + * once, otherwise return the string impossible. For the example above, there |
| 11 | + * are 4 gas stations, and your program should return the string 1 because |
| 12 | + * starting at station 1 you receive 3 gallons of gas and spend 1 getting to the |
| 13 | + * next station. Then you have 2 gallons + 2 more at the next station and you |
| 14 | + * spend 2 so you have 2 gallons when you get to the 3rd station. You then have |
| 15 | + * 3 but you spend 2 getting to the final station, and at the final station you |
| 16 | + * receive 0 gallons and you spend your final gallon getting to your starting |
| 17 | + * point. Starting at any other gas station would make getting around the route |
| 18 | + * impossible, so the answer is 1. If there are multiple gas stations that are |
| 19 | + * possible to start at, return the smallest index (of the gas station). N will |
| 20 | + * be >= 2. |
| 21 | + * |
| 22 | + * https://www.coderbyte.com/results/bhanson:Gas%20Station:JavaScript |
| 23 | + * |
| 24 | + * @param {array} strArr |
| 25 | + * @return {string} |
| 26 | + */ |
| 27 | +function gasStation(strArr) { |
| 28 | + // Get all possible route orders by shifting array |
| 29 | + const possibleRoutes = new Map(); |
| 30 | + for (let i = 1; i < strArr.length; i++) { |
| 31 | + const route = strArr.slice(i); |
| 32 | + route.push(...strArr.slice(1, i)); |
| 33 | + possibleRoutes.set(i, route); |
| 34 | + } |
| 35 | + |
| 36 | + const routeIter = possibleRoutes[Symbol.iterator](); |
| 37 | + |
| 38 | + for (const route of routeIter) { |
| 39 | + const [routeIndex, routeArr] = route; |
| 40 | + |
| 41 | + if (routeValid(routeArr)) { |
| 42 | + return routeIndex.toString(); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return 'impossible'; |
| 47 | +} |
| 48 | + |
| 49 | +function routeValid(route) { |
| 50 | + for (let i = 0, gasInTank = 0; i < route.length; i++) { |
| 51 | + const [gas, distance] = route[i].split(':').map(Number); |
| 52 | + gasInTank += gas; |
| 53 | + |
| 54 | + if (gasInTank < distance) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + gasInTank -= distance; |
| 58 | + } |
| 59 | + return true; |
| 60 | +} |
| 61 | + |
| 62 | +module.exports = gasStation; |
0 commit comments