開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Safari(Web browser)
Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 4.(Arrays - Putting Some Order in Your Data)、Putting it all together… の EXERCISE(No. 2764) を取り組んでみる。
EXERCISE(No. 2764)
コード(Emacs)
HTML5
<button id="run0">run</button><button id="clear0">clear</button> <pre id="output0"></pre> <script src="sample7.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'), p = (x) => pre0.textContent += x + '\n'; let getMostCostEffectiveSolution = (scores, costs, highScore) => { let cost = 100, index = -1; scores.forEach((score, i) => { if (score === highScore && cost > costs[i]) { index = i; cost = costs[i]; } }); return index; }; let getBestResults = (scores, highScore) => { let bestSolutions = []; scores.forEach((score, i) => { if (score === highScore) { bestSolutions.push(i); } }); return bestSolutions; }; let output = () => { let scores = [], costs = []; for (let i = 0; i < 36; i += 1) { scores.push(Math.floor(Math.random() * 10)); costs.push(Math.random()); } let highScore = -1; let output; scores.forEach((score, i) => { output = `Bubble solution #${i} score: ${scores[i]} cost: ${costs[i]}\n`; pre0.textContent += output; if (score > highScore) { highScore = score; } }); let cost = getMostCostEffectiveSolution(scores, costs, highScore); p(`Bubbles tests: ${scores.length}`); p(`Best solutions: ${getBestResults(scores, highScore)}`); p(`Most cost effective solution: ${cost}`); }; btn0.onclick = output; btn1.onclick = () => { pre0.textContent = ''; }; output();
0 コメント:
コメントを投稿