2017年4月12日水曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 4.(Arrays - Putting Some Order in Your Data)、How to iterate over an array の SHARPEN YOUR PENCIL(No. 2573) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 2573)

コード(Emacs)

HTML5

<button id="run0">run</button><button id="clear0">clear</button>
<pre id="output0"></pre>

<script src="sample5.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0');

let output = () => {
    let scores = [];

    for (let i = 0; i < 36; i += 1) {
        scores.push(Math.floor(Math.random() * 10));
    }

    let highScore = -1;

    let output;
    scores.forEach((score, i) => {
        output = `Bubble solution #${i} scores: ${scores[i]}\n`;
        pre0.textContent += output;
        if (score > highScore) {
            highScore = score;
        }
    });

    let bestSolutions1 = [],
        bestSolutions2 = [],
        bestSolutions3 = [];

    for (let i = 0; i < scores.length; i += 1) {
        if (scores[i] === highScore) {
            bestSolutions1.push(i);
        }
    }
    scores.forEach((score, i) => {
        if (score === highScore) {
            bestSolutions2.push(i);
        }
    });
    
    pre0.textContent += `Bubbles tests: ${scores.length}\n`;
    pre0.textContent += `best solutions 1: ${bestSolutions1}\n`;
    pre0.textContent += `best solutions 2: ${bestSolutions2}\n`;
};

btn0.onclick = output;

btn1.onclick = () => {
    pre0.textContent = '';
};

output();



    







						

0 コメント:

コメントを投稿