算法面试题:
形如一下:
横向右为x正坐标
竖向下为y正坐标
(0,0)= 1
(1,0)=2
(1,1)=3
(0,1)=4
(-1,1)=5
…
计算坐标(-7,5)对应值
var Point = function (x,y) {
this.x = x;
this.y = y;
}
function getValue(x,y) {
// 求绝对值
var ceilX = Math.abs(x);
var ceilY = Math.abs(y);
var compareMin = compareMax = new Point(0,0);
var compare = ceilX;
if (ceilX < ceilY) { //横向比对,y值固定
compare = y;
compareMin.y = compareMax.y = y;
compareMin.x = y
if (y < 0) {
compareMax.x = -y + 1;
}else
{
compareMax.x = -y;
}
}else
{
compare = x;
compareMin.x = compareMax.x = x;
compareMax.y = x;
if (x > 0 ) {
compareMin.y = -x+1;
}
else{
compareMin.y = -x;
}
}
console.log("compareMin:"+compareMin.x+",y= "+compareMin.y);
var count = 1;
function checkValue(checkX,checkY) {
count ++;
if (count > 1000) {
console.log("error=====")
return true
}
// console.log("========================================="+count);
if (x == checkX && y == checkY ) {
return true ;
}
}
var gradientX = gradientY = 0 ;
var ret = 1;
var breakCount = 10;
var checkOver = false ;
while (!checkOver) {
checkOver = checkValue(gradientX,gradientY)
var ceilGX = Math.abs(gradientX)
var ceilGY = Math.abs(gradientY);
// x递增,
while (!checkOver && gradientY<= 0 && ceilGX <= ceilGY ) {
gradientX ++
ret ++;
ceilGX = Math.abs(gradientX)
checkOver = checkValue(gradientX,gradientY)
// console.log("ceilX == "+ceilGX +",....ceilY == "+ceilGY);
// console.log("1111,minX== "+gradientX+",minY == " + gradientY +"....ret = "+ret);
}
//(1,0)=>(1,1)
//y 递增
while (!checkOver && gradientX > 0 && ceilGX > ceilGY ) {
gradientY ++;
ret ++;
ceilGY = Math.abs(gradientY)
checkOver = checkValue(gradientX,gradientY)
// console.log("2222,minX== "+gradientX+",minY == " + gradientY +"....ret = "+ret);
}
//x 递降
//(1,1)=》(-1,1)
while (!checkOver && gradientY>0 && (ceilGX < ceilGY||gradientX == gradientY) ) {
gradientX --
ret ++;
ceilGX = Math.abs(gradientX)
checkOver = checkValue(gradientX,gradientY)
// console.log("ceilX == "+ceilGX +",....ceilY == "+ceilGY);
// console.log("333,minX== "+gradientX+",minY == " + gradientY +"....ret = "+ret);
}
//(-1,1)=>(-1,-1)
while (!checkOver && gradientX < 0 && (ceilGX > ceilGY || gradientX == -gradientY) ) {
gradientY --;
ret ++;
ceilGY = Math.abs(gradientY)
checkOver = checkValue(gradientX,gradientY)
// console.log("444444,minX== "+gradientX+",minY == " + gradientY +"....ret = "+ret);
}
}
return ret;
}
var v = getValue(-2,-2);
console.log("value == "+v);