1 Star 0 Fork 0

jimgo/Three Plus One Game

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
3n+1 machine.html 3.11 KB
一键复制 编辑 原始数据 按行查看 历史
jimgo 提交于 2020-02-19 11:45 . refactor init done
<!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: '', 1: '', 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>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/jimgo/ThreePlusOneGame.git
git@gitee.com:jimgo/ThreePlusOneGame.git
jimgo
ThreePlusOneGame
Three Plus One Game
master

搜索帮助