簡體   English   中英

向對象添加唯一的數組,並確保它們不同

[英]Add unique arrays to object and make sure they are different

我想要一個由包含整數的數組組成的對象,作為另一個方法使用的指標。 每個整數數組都必須不同,但是我的函數必須隨機創建它們,並在添加新數組時確保它不存在,但同時必須添加特定數量的數組。

可以說我想要一個看起來像這樣的對象:

arr = { 
  0: [0,0],
  1: [0,1],
  2: [1,1],
  3: [1,0]
}

當然,根據下面Math.random的隨機方面,上述對象可以采用不同的順序。 那是我的代碼:

let arrayOfPositions = [];
let i = 0;
let position = [];

do {
  let randX = Math.round(Math.random());
  let randY = Math.round(Math.random());
  position = [randX, randY];
  arrayOfPositions[i] = position;
  i++;
}

while (arrayOfPositions.length < 4 );

有什么東西在我的同時condtition缺少檢查,如果position在已經存在arrayOfPositions 我嘗試了indexOflastIndexOf但是在添加第一個數組之后它總是停止。

問題是,您在搜索對象(在本例中為數組)的索引時使用indexOflastIndexOf ,並且它們兩者都僅適用於圖元

您可以對值進行字符串化 (1),也可以檢查內部Array值是否相等(2)。

(1)有點棘手且緩慢,因為您必須將原始數組值( arrayOfPositions ),要添加的新position都進行字符串化,然后才能使用indexOf及其派生類。 所以我要跳過那個。

對於(2),我將稍作更改,並假設您可以在使用let同時使用ES6 Array.find

let positions = []
do {
  const position = createUniquePos(positions)
  positions.push(position)
}
while (positions.length < 4)

function createUniquePos(positions) {
  const x = Math.round(Math.random())
  const y = Math.round(Math.random())
  // here we check if that pair already exists in the array
  return positions.find( pos => pos[0] === x && pos[1] === y )
    // if it does exist, then we do another attempt with recursion
    ? createUniquePos(positions)
    // if it doesn't, then we return the unique position
    : [x, y]
}
const positionSet = new Set();
while(positionSet.size < 4){
  const randX = Math.round(Math.random());
  const randY = Math.round(Math.random());
  const position = [randX, randY];
  positionSet.add(position);
}

集合是唯一的,因此,如果添加相同的值,則它將被忽略。

如果要使用諸如mapfilterreduce數組函數,則可以執行Array.from(positionSet); 或者,如果沒有ES7,則可以編寫Array.prototype.slice.call(positionSet);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM