Skip to content

Instantly share code, notes, and snippets.

@balakrishnangithub
Created December 9, 2019 10:44
Show Gist options
  • Save balakrishnangithub/7a74b28d0ac400d5c164d4938a1bff0e to your computer and use it in GitHub Desktop.
Save balakrishnangithub/7a74b28d0ac400d5c164d4938a1bff0e to your computer and use it in GitHub Desktop.
Challenge Emerion
<!DOCTYPE html>
<html>
<head>
<title>House Energy Coins</title>
</head>
<body>
<div>
<label>Input: </label>
<textarea id="userInput"></textarea>
<button onclick="run()">Run</button>
</div>
<div>
Result: <span id="result"></span>
</div>
<script>
class House {
constructor(energy, coins) {
this.energy = energy || 0;
this.coins = coins || 0;
}
}
class Traveler {
constructor(initialEnergy, houseList) {
this.initialEnergy = initialEnergy;
this.houseList = houseList;
this.earned = 0;
}
maxCoinsReachable(firstIndex, lastIndex, energy) {
if ((firstIndex == lastIndex) || energy < 0)
return 0;
if ((lastIndex - firstIndex) < energy) {
return this.houseList.slice(firstIndex, lastIndex).reduce((a, b) => ({ coins: a.coins + b.coins })).coins;
}
return Math.max(
this.maxCoinsReachable(firstIndex + 1, lastIndex, energy + this.houseList[firstIndex].energy - 1),
this.houseList[firstIndex].coins + this.maxCoinsReachable(firstIndex + 1, lastIndex, energy - 1)
);
}
getRich() {
this.earned = this.maxCoinsReachable(0, this.houseList.length, this.initialEnergy);
}
}
</script>
<script>
function run() {
let userInputList = document.querySelector('#userInput').value.split('\n');
let initialEnergy = Number(userInputList[0]);
let houseEnergyCount = Number(userInputList[1]);
let energyEndIndex = 2 + houseEnergyCount;
let houseEnergyList = userInputList.slice(2, energyEndIndex).map(e => Number(e));
let houseCoinsCount = Number(userInputList[energyEndIndex]);
let houseCoinsList = userInputList.slice(energyEndIndex + 1, energyEndIndex + 1 + houseCoinsCount).map(e => Number(e));
let houseCount = Math.max(houseEnergyCount, houseCoinsCount);
let houseList = [];
for (i = 0; i < houseCount; i++) {
houseList.push(new House(houseEnergyList[i], houseCoinsList[i]))
}
let alex = new Traveler(initialEnergy, houseList);
alex.getRich();
document.querySelector('#result').innerHTML = alex.earned;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment