1

function calWinner(arr) {
  //winning combination
  const winningIds = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]

  for (let i = 0; i < winningIds.length; i++) {
    calculate(arr, winningIds[i])
  }
}

function calculate(sup, sub) {
  sup.sort()
  sub.sort()
  let i = 0
  let j = 0
  for (i, j; i < sup.length && j < sub.length;) {
    if (sup[i] < sub[j]) {
      ++i
    } else if (sup[i] == sub[j]) {
      ++i, ++j
    } else {
      return false
    }
  }
  return j == sub.length;
}


calWinner([1, 3, 7, 4])

I'm trying to write a function that takes an array, and check if it has every element in a nested array in an object inside of the function.

I've added a function I found from this post, but not sure why i am getting undefined instead of true.

bom
  • 83
  • 1
  • 8
  • In the old days of Yore I had been studiyng Pascal, and there there was an excellent relational operator ‘IN’. One could use it to determine whether one array is a subset of another one. If Pascal could do it, modern languages should have similar features too. – wintermute Feb 12 '18 at 04:27
  • 1
    @wintermute you are right - using a modern search engine reveals the presence of array.includes in JavaScript – Adnan S Feb 12 '18 at 04:30
  • your `calWinner` function is not returning anything! – diogenesgg Feb 12 '18 at 04:36
  • thanks @diogenesgg, i thought it was, as the nested calculate function returns either true or false. could you tell me how calWinner can return something? – bom Feb 12 '18 at 04:39

1 Answers1

2

Assuming you want to return true if any array from winningIds is inside arr, this is the code:

function calWinner(arr) {
  //winning combination
  const winningIds = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]

  var containsWinner = false;

  for (let i = 0; i < winningIds.length && !containsWinner; i++) {
     containsWinner = calculate(arr, winningIds[i])
  }

  return containsWinner;
}

function calculate(sup, sub) {
  sup.sort()
  sub.sort()

  for (var i = 0; i < sub.length; i++) {
    if (sup.indexOf(sub[i]) == -1) {
        return false;
    }
  }
  return true;
}

calWinner([1, 3, 7, 4]);
diogenesgg
  • 2,601
  • 2
  • 20
  • 29
  • 1
    To make it stop at the the first winningId it finds; After checking that `[1, 4, 7]` is inside `arr`, `containsWinner` becomes `true`, and the loop stops; – diogenesgg Feb 12 '18 at 05:06
  • thanks so much! totally missed the part that `containsWinner` was assigned to the result of `calculate()`! – bom Feb 12 '18 at 05:10