检查和排列两个不同的对

时间:2019-05-07 20:28:56

标签: javascript

我想为两个不同的对检查一个长度为5的数组,如果存在两个对,则将它们加起来。我的思考过程是这样的:

  1. 对数组进行排序。

  2. 如果数组中的第一个和第二个或第二个和第三个位置相同,请将其值添加到新数组中,然后从第一个数组中删除它们。

  3. 重新开始并再次执行相同的操作,但是如果不等于第一对,则仅添加下一对。

  4. 如果第二个数组的长度为4,则求和该数组。如果长度不是4,则原始数组不包含两个不同的对。

这是我想出的代码:

/*temp is the array i test, it's just an array with length 5 
filled with random integer values.*/
var score = 0;
var scoreArray = new Array();
var flag = 0;
/*My thought is, that's it's only necessary 
to check the first two position to find a pair, 
as the array only has a length of 5. */
for(i = 0; i <= 1; i++){
    if(temp[i] == temp[i+1] && flag != temp[i]){
        flag = temp[i]
        scoreArray.push(temp[i], temp[i+1]);
        temp.splice(i, 2);
        i = -1;
    }
}
if(scoreArray.length == 4){
    for(i = 0; i < scoreArray.length; i++){
        score += scoreArray[i];
    }
} 

如果我在数组中找到两对,则在上一次遍历中,我会超出for循环的范围,但是我不知道该如何解决。

2 个答案:

答案 0 :(得分:0)

我不能很好地理解这个问题,但我怀疑您可以使用 .map()或.filter()方法实现您想要的

.map()遍历数组并返回新数组,因此您可以使用以下方法检查和修改每个元素: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

.filter()扫描整个数组,并返回通过扫描条件的新元素数组: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

例如,这是使用.map()方法的东西:

const temp = [1, 2, 3, 4, 5];

console.log(temp);

// loop through temp array to populate new array
const updatedTemp = temp.map(element => {
    // if element have this value
  if (element === 1 || element === 2) {
      // do something to it
    return (element += 1);
  }
  // else just return the element
  return element;
});
// console.log the results
console.log(updatedTemp);

希望这会有所帮助

答案 1 :(得分:0)

您忘了完成检查,因此在找到两对之后,循环开始检查第三对,并从其余数组(当时具有0或1个元素)中索引出来。

function getScore(temp){
  temp.sort();
  var scoreArray = [];
  var flag = 0;
  for(i = 0; i <= 1 && scoreArray.length < 4; i++){
    if(temp[i] == temp[i+1] && flag != temp[i]){
      flag = temp[i]
      scoreArray.push(temp[i], temp[i+1]);
      temp.splice(i, 2);
      i = -1;
    }
  }
  var score = 0;
  if(scoreArray.length == 4){
    for(i = 0; i < scoreArray.length; i++){
      score += scoreArray[i];
    }
  }
  return score;
}

function test(){
  var arr=inp.value.split(" ").map(x => parseInt(x));
  if(arr.length===5 && !isNaN(arr[4]))
    res.innerText=getScore(arr);
  else
    res.innerText="Type 5 numbers with 1-1 space between them";
}

test();
<input id="inp" type="text" oninput="test()" onchange="test()" value="1 2 3 2 1"><br>
<div id="res"></div>