Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given an nested Array of winning conditions which are indexes compare another fixed length array and return true if given symbol matches those index

 let testArray = Array(9).fill("") 
 
  const winConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  let xValue = "X";
  let oValue = "O";

The testArray gets populated with "X" and "O" on button click one at a time. So the end result should be for eg. if "X" is there on testArray index 0, 1, 2 return true

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function checkWin(value, array) {
    return winConditions.some((cond) =>
        cond.every((index) => array[index] == value));
}

console.log(checkWin(xValue, testArray));
console.log(checkWin(oValue, testArray));

some returns true if any of the values is true,
every returns true if all of the values is true.

Therefore we check on each conditions if the value matches the all of the array values, and return true if any of these conditions is met.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading