Created
February 2, 2017 21:00
-
-
Save jasonwaters/642f299fcce657f336163cbc42d3edd7 to your computer and use it in GitHub Desktop.
Ice Cream Purchases
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
| // https://www.hackerrank.com/challenges/ctci-ice-cream-parlor | |
| // find 2 distinct flavors that would take up all of the money m | |
| // for each trip print the id numbers of the two types of ice cream | |
| // some ice creams may have the same price | |
| function purchase(indexed, product) { | |
| let result = Object.assign({}, indexed); | |
| if(result[product.value]) { | |
| result[product.value] = result[product.value].filter(p => p !== product) | |
| } | |
| return result; | |
| } | |
| function purchaseTwo(cash, products, purchases=[]) { | |
| let indexed = products.reduce((tot, next) => { | |
| if(!tot[next.value]) { | |
| tot[next.value] = []; | |
| } | |
| tot[next.value].push(next) | |
| return tot; | |
| }, {}); | |
| for(let product of products) { | |
| let cashRemaining = cash - product.value; | |
| let remainingProducts = purchase(indexed, product); | |
| if(remainingProducts[cashRemaining]) { | |
| return [product, remainingProducts[cashRemaining][0]]; | |
| break; | |
| } | |
| } | |
| } | |
| let input = `2 | |
| 4 | |
| 5 | |
| 1 4 5 3 2 | |
| 4 | |
| 4 | |
| 2 2 4 3`; | |
| let lines = input.split('\n'); | |
| let numTrips = parseInt(lines.shift()); | |
| while(lines.length) { | |
| let purchasePower = parseInt(lines.shift()); | |
| let numProducts = parseInt(lines.shift()); | |
| let products = lines.shift().trim().split(' ').map((value, index) => ({id: index+1, value: parseInt(value)})).sort((a,b) => { | |
| return a.value - b.value; | |
| }); | |
| console.log(purchaseTwo(purchasePower, products).map(product => product.id).sort((a,b) => a-b).join(' ')); | |
| } | |
| //output | |
| // 1 4 | |
| // 1 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment