Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Create a function `getArraysOfDigits(subarrayLength, step)` to generate an array of arrays of digits.
- * Each subarray must be the same length (`subarrayLength`) and contain numbers increasing by 1,
- * unless that number exceeds 9, in which case it must wrap back around to (number - 9).
- * The first subarray starts at 1.
- * The first digit of each subsequent subarray must be equal to the sum of `step` and the first digit in the previous subarray.
- * There must be as many subarrays as needed so that the first digit in the last subarray equals 1 again.
- * Examples and solution below.
- * /
- /*
- getArraysOfDigits(3, 3)
- [
- [1, 2, 3],
- [4, 5, 6],
- [7, 8, 9],
- [1, 2, 3]
- ]
- getArraysOfDigits(1, 2)
- [
- [1],
- [3],
- [5],
- [7],
- [9],
- [2],
- [4],
- [6],
- [8],
- [1]
- ]
- getArraysOfDigits(5, 2)
- [
- [1, 2, 3, 4, 5],
- [3, 4, 5, 6, 7],
- [5, 6, 7, 8, 9],
- [7, 8, 9, 1, 2],
- [9, 1, 2, 3, 4],
- [2, 3, 4, 5, 6],
- [4, 5, 6, 7, 8],
- [6, 7, 8, 9, 1],
- [8, 9, 1, 2, 3],
- [1, 2, 3, 4, 5]
- ]
- */
- /**
- *
- * @param {number} subarrayLength The length of each nested array.
- * @param {number} step By how much the first element in the current subarray will increase in the next subarray.
- * @returns {number[][]} An array as described above.
- */
- function getArraysOfDigits(subarrayLength, step) {
- const result = [];
- const toDigit = (num) => (num - 1) % 9 + 1;
- for (let i = 1; ; i = toDigit(i + step)) {
- const newSubarray = Array.from({ length: subarrayLength }, (_, j) => {
- return toDigit(i + j);
- });
- result.push(newSubarray);
- if (result.length > 1 && i === 1)
- break;
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement