用javascript實現給出的盒子的序列是否可連為一矩型

來源:互聯網
上載者:User


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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.