用javascript实现给出的盒子的序列是否可连为一矩型

2018-10-15 17:06

阅读:541


by cpglkg
<script>
var arr=[5,10,15];


function rect(arr,width)
{
arr.sort(function(a,b){return a-b;});
var len = arr.length;
var temp = arr[0];
var w = null;
var h = null;
for(var i = 0; i < len; i++)
{
if((temp + i) != arr[i])
{
w = i;
if (len % w != 0)
return false;
h = len/w;
break;
}
}
var r = width - w;
temp += r;
for(var i = w; i < len; i++)
{
if(arr[i] != temp + i)
{
temp += r;
if(arr[i] != temp + i)
{
return false;
}
}
}

return true;
}
alert(rect(arr,6));
</script>

by 无殇
<script>
var rows=6;
function ch(array){
array=array.sort(function(a,b){return a-b;})
var n,c=0;
for(var i=1;i<array.length;i++)
if(array[i]-array[i-1]==1)
c++;
else
break;
if(array.length%(c+1)!=0)return false;
for(var i=1;i<array.length;i++)
{
n=array[i]-array[i-1];
if(n!=1 && n+c!=rows)
return false;
}
return true;
}
alert(ch([1,2,3]))
alert(ch([5,6,11,12,17,18,23,24]))
alert(ch([19,25,31]))
alert(ch([1,2,3,4,7,8]))
</script>

by 秦皇也爱JS

<script>
var arr = [5,10,15];
var width = 6;

arr = arr.sort(function(a,b){ return a-b});
var row = Math.ceil((arr[arr.length-1]-arr[0]+1)/width);
var col = Math.floor(arr.length / row);

check();
function check(){
for(var i=0;i<arr.length-1;i++){
if(arr[i+1] - arr[i] !=1 && i%col!=col-1 i%col==col-1 && arr[i+1] - arr[i] != width-col+1){
alert(false);
return;
}
}
alert(true);
}
</script>


评论


亲,登录后才可以留言!