開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js, Safari(JavaScript エンジン)
- Learning JavaScript [邦訳](参考書籍)
Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)の Part 1(Starting with the basics)、Chapter 8(Case Study: Word Play)の Exercise 8-7、8-8、8-9.を JavaScript で取り組んでみる。
Exercise 8-7、8-8、8-9.
コード(Emacs)
HTML5
<pre id="output0"></pre> <input id="file0" type="file"> <br> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample7.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'), input_file0 = document.querySelector('#file0'), p = (x) => pre0.textContent += x + '\n', range = (start, end, step=1) => { let result = []; for (let i = start; i < end; i += 1) { result.push(i); } return result; }; let isPalindrome = (word) => word === word.split('').reverse().join(''); let output = () => { let file = input_file0.files[0], reader = new FileReader(); reader.onload = () => { let words = reader.result .split('\n') .map((word) => word.trim()) .filter((word) => word !== ''); p('7.'); p( words.filter((word) => /(.)\1(.)\2(.)\3/.test(word)) .join('\n') ); p('8.'); p( range(100000, 1000000) .filter((n) => isPalindrome(`${n}`.substring(2)) && isPalindrome(`${n + 1}`.substring(1)) && isPalindrome(`${n + 2}`.substring(1, 5)) && isPalindrome(`${n + 3}`)) .join('\n') ); p('9.'); let age1 = 20, age2 = 50; range(age1, age2 + 1) .forEach((diff) => { let count = 0; range(0, 100 - diff + 1) .forEach((i) => { let mum = i + diff; if (`${i}` === `${mum}`.split('').reverse().join('')) { p(`ME: ${i}, MUM: ${mum}`); count += 1; } }); if (count > 0) { p(`${count}: ${diff}`); } }) }; reader.readAsText(file); }; btn0.onclick = output; btn1.onclick = () => pre0.textContent = ''; output();
0 コメント:
コメントを投稿