javascript 代码2017年出现 - 第3天
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 代码2017年出现 - 第3天相关的知识,希望对你有一定的参考价值。
function getFirstValueAbove(num) {
const grid = {0:{0:1}};
const getNum = (x, y) => (grid[x] || {})[y] || 0;
const setNum = (x, y, n) => {
grid[x] = grid[x] || {};
grid[x][y] = n;
return n;
};
const sumAroundPos = (x, y) => (
getNum(x, y-1) + getNum(x+1, y-1) + getNum(x-1, y-1)
+ getNum(x+1, y) + getNum(x-1, y)
+ getNum(x, y+1) + getNum(x+1, y+1) + getNum(x-1, y+1)
);
const calculateNextMove = (x, y) => {
const [north, south, east, west] = [[x, y+1], [x, y-1], [x+1, y], [x-1, y]];
const [n, s, e, w] = [north, south, east, west].map(([px, py]) => getNum(px, py));
if (n && !s && !e) { return east; }
if (!n && w && !e) { return north; }
if (!n && !w && s) { return west; }
if (!w && !s && e) { return south; }
};
let n = getNum(0, 0);
for(let x = 0, y = 0; n < num;) {
// decide what square is next in line
const [nextX, nextY] = calculateNextMove(x, y);
// calculate and fill square amount
n = setNum(nextX, nextY, sumAroundPos(nextX, nextY));
// set new current position to the new square
x = nextX; y = nextY;
}
return n;
}
function getDist(num) {
let sqrt = Math.ceil(Math.sqrt(num));
let sideLengthOfSq = (sqrt % 2 === 0 ? sqrt + 1 : sqrt);
let highestNumInSq = sideLengthOfSq * sideLengthOfSq;
let targetDistFromCorner = (highestNumInSq - num) % (sideLengthOfSq - 1);
let targetDistFromSideCenter = Math.abs(targetDistFromCorner - Math.floor(sideLengthOfSq/2));
const closestDistFromSq = (sideLengthOfSq - 1) / 2;
return closestDistFromSq + targetDistFromSideCenter;
}
以上是关于javascript 代码2017年出现 - 第3天的主要内容,如果未能解决你的问题,请参考以下文章
javascript 代码2017年出现 - 第5天
javascript 代码2017年出现 - 第4天
javascript 2017年AoC - 第2天
javascript-Array(数组)
前端资讯2017 年 JavaScript 框架报告前端框架
2017年软件工程第三次作业-3功能测试