Advertisement
Notimecelduv

getArraysOfDigits (challenge)

Dec 20th, 2021 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Create a function `getArraysOfDigits(subarrayLength, step)` to generate an array of arrays of digits.
  3.  * Each subarray must be the same length (`subarrayLength`) and contain numbers increasing by 1,
  4.  * unless that number exceeds 9, in which case it must wrap back around to (number - 9).
  5.  * The first subarray starts at 1.
  6.  * The first digit of each subsequent subarray must be equal to the sum of `step` and the first digit in the previous subarray.
  7.  * There must be as many subarrays as needed so that the first digit in the last subarray equals 1 again.
  8.  * Examples and solution below.
  9.  * /
  10.  
  11. /*
  12. getArraysOfDigits(3, 3)
  13. [
  14.   [1, 2, 3],
  15.   [4, 5, 6],
  16.   [7, 8, 9],
  17.   [1, 2, 3]
  18. ]
  19.  
  20. getArraysOfDigits(1, 2)
  21. [
  22.   [1],
  23.   [3],
  24.   [5],
  25.   [7],
  26.   [9],
  27.   [2],
  28.   [4],
  29.   [6],
  30.   [8],
  31.   [1]
  32. ]
  33.  
  34. getArraysOfDigits(5, 2)
  35. [
  36.   [1, 2, 3, 4, 5],
  37.   [3, 4, 5, 6, 7],
  38.   [5, 6, 7, 8, 9],
  39.   [7, 8, 9, 1, 2],
  40.   [9, 1, 2, 3, 4],
  41.   [2, 3, 4, 5, 6],
  42.   [4, 5, 6, 7, 8],
  43.   [6, 7, 8, 9, 1],
  44.   [8, 9, 1, 2, 3],
  45.   [1, 2, 3, 4, 5]
  46. ]
  47. */
  48.  
  49. /**
  50.  *
  51.  * @param {number} subarrayLength The length of each nested array.
  52.  * @param {number} step By how much the first element in the current subarray will increase in the next subarray.
  53.  * @returns {number[][]} An array as described above.
  54.  */
  55. function getArraysOfDigits(subarrayLength, step) {
  56.   const result = [];
  57.   const toDigit = (num) => (num - 1) % 9 + 1;
  58.  
  59.   for (let i = 1; ; i = toDigit(i + step)) {
  60.     const newSubarray = Array.from({ length: subarrayLength }, (_, j) => {
  61.       return toDigit(i + j);
  62.     });
  63.     result.push(newSubarray);
  64.  
  65.     if (result.length > 1 && i === 1)
  66.       break;
  67.   }
  68.  
  69.   return result;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement