代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> 3n + 1 Game </title>
<link rel="stylesheet" href="./machine_plus.css">
<style>
th {
height: 26px;
text-align: right;
font-family: 'arial black';
}
thead th{
min-width: 10em;
text-align: center;
background-color: #FE3;
}
</style>
</head>
<body>
<a href="http://www.matrix67.com/blog/archives/6756">根据 Matrix67 博客中的题目所做的练习。</a>
<p>任意取一个正整数 n 。如果 n 是奇数,则把 n 变为 3 · n + 1 ;如果 n 是偶数,则把 n 变为 n/2 。不断重复操作,则最终一定会得到 1 。</p>
Input Number: <input type="number" id="ipt" />
<div id="insertCount"></div>
<table>
<thead>
<tr>
<th>Decimal</th>
<th>Ternary</th>
</tr>
</thead>
<tbody id="insertRow"> </tbody>
</table>
<script type="text/javascript" src="./ternary.js"></script>
<script>
'use strict';
const TRACK_SIGN = { 0: '▁', 1: '▄', 2: '█' };
const ROBOT_SIGN = { 0: '□', 1: '■' };
const WIDTH_SIGN = { 0: '0', 1: '1', 2: '2' };
const insertRow = document.querySelector('#insertRow');
const insertCount = document.querySelector('#insertCount');
let track = [];
let robot = 0;
// one trip
function trip() {
robot = 0;
// single move
for (let i = 0; i < track.length; i++) {
if (robot) {
switch (track[i]) {
case 0:
track[i] = 1;
break;
case 1:
track[i] = 2;
robot = 0;
break;
case 2:
break;
default:
break;
}
} else {
switch (track[i]) {
case 0:
break;
case 1:
track[i] = 0;
robot = 1;
break;
case 2:
track[i] = 1;
break;
default:
break;
}
}
}
// terminal move
if (robot) track.push(2)
}
// Show Step In Web
function showSteps(num) {
insertRow.textContent = '';
// checkSteps(num);
// initial track;
track = Array.from(num.toString(3)).map(e => +e);
let cnt = 0;
while (num >= 2) {
let tr = document.createElement("tr");
let td1 = document.createElement("th");
td1.textContent = num;
let td2 = document.createElement("td");
td2.innerHTML = '<tt>' + track.map(e => TRACK_SIGN[e]).join('')
+ '</tt><tt>' + track.map(e => WIDTH_SIGN[e]).join('') + '</tt>';
tr.appendChild(td1);
tr.appendChild(td2);
insertRow.appendChild(tr);
trip();
num = step(num);
// keep test
if (num !== Number.parseInt(track.join(''), 3)) {
alert('Wrong During trip');
console.error(num, num.toString(3), track.join(''));
break;
}
cnt++;
}
insertCount.textContent = cnt + ' rows, ' + track.length + ' width';
}
// add Event Listener
(() => {
document.getElementById('ipt').addEventListener('change', function (evn) {
showSteps(Math.abs(parseInt(this.value, 10)));
}, false);
})();
</script>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。