Does the array contain specific numbers?

  • 0
    Hello, I don't understand how to solve the problem. Let's say there is a two-dimensional array of integers.
    [
    [2, 1, 3, 2, 7],
    [8, 7, 6, 8, 1],
    [5, 4, 9, 4, 5],
    ];
    I need to determine if each section 3 * 3 contains all numbers from in the range from 1 to 9
    I don’t understand how to check with such sections in all arrays together. And how to check the presence of exactly all numbers in the range from 1 to 9
    JavaScript Anonymous, Feb 10, 2020

  • 2 Answers
  • 0
    Everett Reyes

  • 0
    The simple option is to iterate over all 3x3 areas (see the upper left corner - this is 2 cycles from 0 to width-3 and from 0 to height-3) and check that they are good.



    To check, you can either 1) check that all numbers from 1 to 9 are different, or 2) check that each of the digits occurs there exactly once. The second option is shorter and faster, but for it you have to create an array of counters from 0 to 9. It is zeroed out before each check. Walk around your 3x3 block and increment the corresponding counter (something like count [a [beg_x + i] [beg_y + j]] ++ ). Just do not forget to check that the number is from 1 to 9, so as not to get out of the array boundaries. Then go through the array of counters in a loop from 1 to 9 and check that there are ones everywhere.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!