
[英]comparing two arrays of different lengths and returning an array with the uncommon elements
[英]Comparing two arrays and returning valid and misplaced elements
我想為我的第一個項目制作一個簡單的游戲,但我在其背后的邏輯上遇到了一些問題。 游戲應該比較兩個 arrays,其中一個存儲用戶輸入,另一個隨機生成。 arrays 的長度均為 n(假設 n=3)並接受 n 個唯一字符作為它們的值。 假設用戶輸入是 ['A','A', 'B'],獲勝組合是 ['B', 'A', 'C']。 獲勝條件很簡單,用戶輸入數組中的所有三個元素都必須有效。 如果一個元素的值和索引都對應於第二個數組中的元素,則該元素有效。 檢查這個很簡單:
for (let i = 0; i<arr1.length; i++) {
for (let j = 0; j<arr1.length; j++){
if (arr[i] === arr1[j] && getIndices(arr[i], arr1[j]) === true){
valid ++;
}
但是,我還想跟蹤放錯位置的元素,其中 arr[i] 與 arr[j] 的值匹配,但對它們索引的相等性檢查返回 false。 這就是問題所在,如果我將其放在 else 語句中,並將 ['A', 'B', 'A'] 與 ['A', 'C', 'C'] 進行比較,它將返回 1 valid as它應該,但也有 1 個錯位,這是不正確的,因為 'A' 在第二個數組中只出現一次。 您將如何設置語句來避免這種情況?
我對此很陌生,所以我沒有嘗試太多。
這就是 JS 的方式。
const userList = ['A', 'B', 'C'];
const winList = ['A', 'B', 'A'];
const scoreCalculator = ({ user, win }) => {
let points = 0;
user.forEach((value, index) => {
if (value === win[index]) {
points++;
}
});
return points;
}
console.log(scoreCalculator({user: userList, win: winList}));
成本將為 O(n)。
執行正常。
const userList = ['A', 'B', 'C'];
const winList = ['A', 'B', 'A'];
const scoreCalculator = ({ user, win }) => {
let points = 0;
for(let i = 0; user.list; i++) {
if (user[i] === win[i]) {
points++;
}
});
return points;
}
console.log(scoreCalculator({user: userList, win: winList}));
如您所見,Array.prototype.forEach() 的工作方式與 for 正常。
如果輸入值和獲勝條件的長度相同,則不需要兩個 for 循環。 並正確命名您的變量: inputs
和condition
。
var points = 0 var misplacedElements = [] for (let i = 0; i<inputs.length; i++) { //findIndex returns index of the element on the condition array //If element don't exist returns -1 const indexOfInput = condition.findIndex(e=> e === inputs[i]) if(indexOfInput.= -1){ //Element contains but might not be on the same index if(indexOfInput == i){ //On the same index so give a point points++ }else{ //Hold the index or the element depends to your need misplacedElements.push( i ) } }
不懂的可以問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.