繁体   English   中英

比较两个 arrays 并返回有效和错位的元素

[英]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 循环。 并正确命名您的变量: inputscondition

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM