2017-02-16 59 views
-1

這也許是一個javascript數學問題。Javascript Square Multi Array

給定一個說64個項目的線性數組,我需要一個函數來生成像8x8這樣的2d數組作爲棋盤格。雖然陣列不總是64個項目,所以應該相應地分割 - 例如36個項目將是6×6陣列。

我需要做的是用一個未知的線性數組儘可能多地生成一個具有相同行和列的數組,如果有必要的話,將一些值溢出到最後一行。

因此,68項產生8×9行,最後一行有4項。

但它應該總是儘可能的平方,所以行和列應該總是相等的,除了最後一些溢出。

+0

'Math.sqrt'和'Math.floor'將兩種方法你」 d僱用......並且可能是'Array#reduce' +'Array#slice' - 或者'Array#splice' - 你怎麼看? –

+0

如果數組包含16個元素,則輸出將是4x4,對嗎? –

+0

聽起來你正在尋找一個[chunk](https://lodash.com/docs/4.17.4#chunk)函數。 – SimpleJ

回答

1
function square(arr) { 
    var sqrt = Math.sqrt(arr.length);      // square root of arr.length 
    var n = Math.ceil(sqrt);        // number of sub-arrays (ceil) 
    var cols = Math.floor(sqrt);       // number of items in each sub-array (floor) 
    var result = [];          // the result array 
    for(var i = 0; i < n; i++) 
     result.push(arr.slice(i * cols, (i + 1) * cols)); // get the sub-array from array (cut cols elements from arr starting from the index i * cols) 
    return result; 
} 
1

你可以用一大塊功能,Math.sqrt做到這一點,並Math.floor

// create an array of numbers 0-67 
 
const array = Array.from({length: 68}).map((_, i) => i); 
 

 
// Creates an array of elements split into groups the length of chunkSize 
 
function chunk(arr, chunkSize) { 
 
    const chunks = []; 
 
    const {length} = arr; 
 
    const chunkCount = Math.ceil(length/chunkSize); 
 

 
    for(let i = 0; i < chunkCount; i++) { 
 
    chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize)); 
 
    } 
 

 
    return chunks; 
 
} 
 

 
const grid = chunk(array, Math.floor(Math.sqrt(array.length))); 
 

 
console.log(grid);