4 回答

TA貢獻1829條經驗 獲得超7個贊
使用 Set 或數組或對象來跟蹤已經看到的值,并使用 while 循環來獲取新的唯一值
const arr = [5, 5, 5, 4, 4];
const seen = new Set();// only holds unique values, even when add duplicates
arr.forEach((n,i) => {
while(seen.has(n)){
arr[i] = n = Math.floor(Math.random() * 10);
}
seen.add(n);
});
console.log(arr)

TA貢獻1887條經驗 獲得超5個贊
previousElements 包含 arr 中位于當前索引之前的元素,而 otherElements 包含 arr 中除當前索引之外的所有其他元素。如果已經有一個實例,則會生成一個新的隨機數。然后將新的隨機數與 arr 的所有其余元素進行比較,以避免更改數字的第一個實例。在提供的示例中,索引 3 將始終保持為 4。
var arr = [5, 5, 5, 4, 4];
for (let i = 0; i < arr.length; i++) {
let previousElements = arr.slice(0, i);
let otherElements = JSON.parse(JSON.stringify(arr));
otherElements.splice(3, 1);
if (previousElements.includes(arr[i])) {
arr[i] = Math.floor(Math.random() * 10);
while (otherElements.includes(arr[i])) {
arr[i] = Math.floor(Math.random() * 10);
}
}
}
console.log('arr: ' + JSON.stringify(arr));
示例輸出:[5,8,2,4,3]
示例輸出:[5,0,1,4,8]

TA貢獻1809條經驗 獲得超8個贊
這是解決方案:
var arr = [5, 5, 5, 4, 4];
const replaceduplicates=(arr)=>{
let i =1;
while(i < arr.length -1 ){
const currentElement=arr[i]
const indexOfcurrentElement= arr.indexOf(currentElement)
if(indexOfcurrentElement > -1) {
let newValue=Math.floor(Math.random() * 10 + arr[i-1])
while( arr.indexOf(newValue) > -1)
{
newValue=Math.floor(Math.random() * 10 )
}
arr[i] = newValue;
i++
}
}
return arr
}
//this is how I tested basically this will run for ever
let found=false
while(!found ){
const arrResponse =replaceduplicates(arr)
for (let i = 0; i < arrResponse.length; i++) {
for (let j = i+1; j < arrResponse.length; j++) {
if(arrResponse[i] == arrResponse[j]) found = true
}
}
console.log('no duplicates')
}

TA貢獻1777條經驗 獲得超10個贊
使用while循環而不是if語句來不斷檢查該值,直到它不等于先前的值。
雖然您需要在將數字更改為隨機數之后添加額外的檢查,以查看該隨機數是否已經不在數組中。
const hasDuplicateNumbers = (number, numbers) =>
numbers.filter(item => item === number).length > 1;
let arr = [5, 5, 5, 4, 4];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (i === j) {
continue;
}
while(hasDuplicateNumbers(arr[j], arr)) {
arr[j] = Math.floor(Math.random() * 10);
}
}
}
console.log(arr);
添加回答
舉報