将数字数组与“数字数组数组”进行比较以查找匹配项

时间:2019-07-28 13:16:50

标签: javascript jquery arrays loops

我正在尝试一些以前从未尝试过的方法,却为寻找解决方案而烦恼(希望我没有尝试不可能的事情!)。

我有一个包含24个单独数组的数组,每个数组包含4个数字值。

var arrayOfArrays = [
    [ 0, 7, 14, 21 ],
    [ 1, 8, 15, 22 ],
    [ 2, 9, 16, 23 ],
    [ 6, 13, 20, 27 ] and so on for 24 arrays.

我还有一个空数组,在单击事件中有一个新数字被推入其中。每次点击都会添加一个新数字,即

var userGeneratedArray = []
- click
[7]
- click
[7, 32]
-click
[7, 32, 14]
-click
[7, 32, 14, 24]
-click
[7, 32, 14, 24, 34]

我想做的是:

1)每次将新数字添加到userGeneratedArray时,我都要遍历arrayOfArrays并比较数字。

2)一旦userGeneratedArray中的任何四个数字与arrayOfArrays中的任何数组中的所有数字匹配,就返回true。

关于如何构造此循环的任何想法?任何帮助将不胜感激:)。

这是我完整的数组数组

    var arrayOfArrays = [
        [ 0, 7, 14, 21 ],
        [ 1, 8, 15, 22 ],
        [ 2, 9, 16, 23 ],
        [ 6, 13, 20, 27 ],

        [ 7, 14, 21, 28 ],
        [ 8, 15, 22, 29 ],
        [ 12, 19, 26, 33 ],
        [ 14, 21, 28, 35 ],

        [ 18, 25, 32, 39 ],
        [ 19, 26, 33, 40 ],
        [ 20, 27, 34, 41 ],
        [ 36, 31, 26, 21 ],

        [ 37, 32, 27, 22 ],
        [ 38, 33, 28, 23 ],
        [ 30, 25, 20, 15 ],
        [ 31, 26, 21, 16 ],

        [ 32, 27, 22, 17 ],
        [ 24, 19, 13, 9 ],
        [ 25, 20, 15, 10 ],
        [ 26, 21, 16, 11 ],

        [ 18, 13, 8, 3 ],
        [ 19, 14, 9, 4 ],
        [ 20, 15, 10, 5 ],
        [ 13, 20, 27, 34 ]
    ];

4 个答案:

答案 0 :(得分:0)

您可以创建一个数据结构,以有效地标识其中出现选定编号的数组(避免一遍又一遍地搜索它们):每个可选编号到包含该编号的数组对象列表的映射。在每个此类对象上添加一个计数器,以跟踪是否已全部选中。

这是看起来的样子。我添加了可以选择数字的按钮:

const arrayOfArrays = [[ 0, 7, 14, 21 ],[ 1, 8, 15, 22 ],[ 2, 9, 16, 23 ],[ 6, 13, 20, 27 ],[ 7, 14, 21, 28 ],[ 8, 15, 22, 29 ],[ 12, 19, 26, 33 ],[ 14, 21, 28, 35 ],[ 18, 25, 32, 39 ],[ 19, 26, 33, 40 ],[ 20, 27, 34, 41 ],[ 36, 31, 26, 21 ],[ 37, 32, 27, 22 ],[ 38, 33, 28, 23 ],[ 30, 25, 20, 15 ],[ 31, 26, 21, 16 ],[ 32, 27, 22, 17 ],[ 24, 19, 13, 9 ],[ 25, 20, 15, 10 ],[ 26, 21, 16, 11 ],[ 18, 13, 8, 3 ],[ 19, 14, 9, 4 ],[ 20, 15, 10, 5 ],[ 13, 20, 27, 34 ]];

// Create efficient data structure for counting the selections
const numberToCounters = Array.from({length: 42}, () => []);
arrayOfArrays.map((arr) => ({ arr, selected: 0 }))
    .forEach(counter => counter.arr.forEach(k => 
        numberToCounters[k].push(counter))
    );

// Function to process a selection and see if 4 of the same array
const select = num => 
    numberToCounters[num].find(counter => ++counter.selected == counter.arr.length);

// I/O handling
for (let k = 0; k <= 41; k++) {
    let button = document.createElement("button");
    button.textContent = k;
    button.className = "choice";
    document.body.append(button);
}

document.addEventListener("click", function (e) {
    const button = e.target;
    if (button.className !== "choice") return;
    button.disabled = true;
    const counter = select(button.textContent);
    if (counter) { // game over
        for (let button of document.querySelectorAll(".choice")) button.disabled = true;
        document.querySelector("#output").textContent = "Matched all values in " + counter.arr;
    }
});
<div id="output"></div>

答案 1 :(得分:0)

您希望用户在输入中输入某个数组,并与您完全给定的数组匹配,然后返回匹配的数组。这非常简单,可以分步完成

  1. 首先,在输入中添加forEach,然后在用户键入内容时,将字符串拆分为一个数组。在那里输入
  2. 然后在arrayOfArrays上方forEach内获取每个值。
  3. arrayOfArrays放在every的元素上,然后在数组上进行var arrayOfArrays = [ [0, 7, 14, 21], [1, 8, 15, 22], [2, 9, 16, 23], [6, 13, 20, 27], [7, 14, 21, 28], [8, 15, 22, 29], [12, 19, 26, 33], [14, 21, 28, 35], [18, 25, 32, 39], [19, 26, 33, 40], [20, 27, 34, 41], [36, 31, 26, 21], [37, 32, 27, 22], [38, 33, 28, 23], [30, 25, 20, 15], [31, 26, 21, 16], [32, 27, 22, 17], [24, 19, 13, 9], [25, 20, 15, 10], [26, 21, 16, 11], [18, 13, 8, 3], [19, 14, 9, 4], [20, 15, 10, 5], [13, 20, 27, 34] ]; let answer = [] document.querySelector("#val").onkeyup = function() { let array_user = this.value.split(',') // convert input value to array arrayOfArrays.forEach((array) => { // for every array inside arrayOfArrays let trues = array.every((val, index) => { // match every element inside the arrays of the variable arrayOfArrays and then return the condition return val == array_user[index] }) if (trues){ // if your answer is correct then say yes console.log("ANSWER IS THIS => " + array) } }) }循环。检查每个值是否与数组匹配,然后返回答案

<input id="val">
13, 20, 27, 34

例如,在输入中键入double x; cin >> x; // <-- reading from cin only once // initing a vector object named homework vector<double> homework; // show debug on the vector while (homework.size() != 3) homework.push_back(x); // <- inserting same value three times (或数组字典中的任何其他值),这将匹配其中的数组。

答案 2 :(得分:0)

此代码段中的方法是通过针对输入数组值的每个元素使用过滤器来减少arrayOfArrays来创建频率数组。如果结果频率之一总计为4,则输入数组中的四个数字与arrayOfArrays数组之一匹配。

const arrayFromInput = [23,55,22,0,7,13,7,22,16,13,21,14];
const otherArrayFromInput = [23,55,22,1,14,15,98,6,7];
const arrayOfArrays = [
    [ 0, 7, 14, 21 ],
    [ 1, 8, 15, 22 ],
    [ 2, 9, 16, 23 ],
    [ 6, 13, 20, 27 ],
];

checkArrayExistence(arrayFromInput);
checkArrayExistence(otherArrayFromInput);

function checkArrayExistence(inputValues) {
  let report = `Check: any 4 of [${inputValues}] in one of arrayOfArrays?`;
  
  // from a HTML input field the values may be strings, so convert first
  intermediateArray = inputValues.map(Number);
  
  // for every array of arrayOfArrays, filter for every value of [input]
  // and add length of result to array [checked]
  const checked = arrayOfArrays.reduce( (frequencies, arrayElem) => 
    frequencies.concat([arrayElem.filter(v => inputValues.indexOf(v) >= 0).length]),
    []
  );
  
  // if a value (frequency) of [checked] is 4, four numbers of input are found
  // in one of the arrays of [arrayOfArrays]
  console.log(`${report} ${checked.filter(v => v == 4).length ? "YEP" : "NOPE"}`);
};

答案 3 :(得分:-1)

 var arrayOfArrays = [
        [ 0, 7, 14, 21 ],
        [ 1, 8, 15, 22 ],
        [ 2, 9, 16, 23 ],
        [ 6, 13, 20, 27 ],

        [ 7, 14, 21, 28 ],
        [ 8, 15, 22, 29 ],
        [ 12, 19, 26, 33 ],
        [ 14, 21, 28, 35 ],

        [ 18, 25, 32, 39 ],
        [ 19, 26, 33, 40 ],
        [ 20, 27, 34, 41 ],
        [ 36, 31, 26, 21 ],

        [ 37, 32, 27, 22 ],
        [ 38, 33, 28, 23 ],
        [ 30, 25, 20, 15 ],
        [ 31, 26, 21, 16 ],

        [ 32, 27, 22, 17 ],
        [ 24, 19, 13, 9 ],
        [ 25, 20, 15, 10 ],
        [ 26, 21, 16, 11 ],

        [ 18, 13, 8, 3 ],
        [ 19, 14, 9, 4 ],
        [ 20, 15, 10, 5 ],
        [ 13, 20, 27, 34 ]
    ];
    newArrays = [];
    var noMatch = false;
    var addedNumbers = [];
    function addNumber() {
      if(noMatch || addedNumbers.length === 4) {
        return;
      }
      let value = document.querySelector('input').value;
      if(value) {
        addedNumbers.push(value);
        document.querySelector('span').textContent = [...addedNumbers];
        value = parseInt(value);
        if(newArrays.length == 0) {
          newArrays =  arrayOfArrays.filter(array => {
          return array.some(item => item == value);
          });
        } else {
          newArrays =  newArrays.filter(array => {
          return array.some(item => item == value);
          });
        }
        document.querySelector('input').value = '';
        if(addedNumbers.length === 4 && newArrays.length > 0) {
          alert('match found');
        }
        if(newArrays.length === 0) {
          noMatch = true;
          alert('No match found');
        }
        console.log(newArrays);
      }
    }
<input type="number">
  <button onclick="addNumber()">Add Numbers</button>
  <span></span>