1

This is a function of bypassing the two-dimensional array (matrix) in a spiral clockwise: (demo)

entryArray = [
  [ 1,  2,  3, 4],
  [12, 13, 14, 5],
  [11, 16, 15, 6],
  [10,  9,  8, 7]
]

def f(a)
  a.empty? ? [] : a.shift+f(a.transpose.reverse)
end

f(entryArray)
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

I tried to make an analog in JavaScript:

function transpose(a) {
    return a.length === 0 ? a : a[0].map((col, i) => a.map((row) => row[i]))
}

function f(a) {
    return a.length === 0 ? [] : a.shift + f(transpose(a).reverse());
} 

f([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]);

but it did not work, an error appears in the console:

Error

Please tell me what the problem is, and is it possible to do it on JS?

1 Answer 1

2

You need to call the shift function with shift(). Without that you don't remove en element from the array and get a stack overflow because you keep sending the same array through the recursion:

function transpose(a) {
    return a.length === 0 ? a : a[0].map((col, i) => a.map((row) => row[i]))
}

function f(a) {
    return a.length === 0 ? [] : a.shift() + f(transpose(a).reverse());
} 

console.log(f([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));

You can fix the commas by keeping the return value as a flat array until the end, then making a string:

function transpose(a) {
    return a.length === 0 ? a : a[0].map((col, i) => a.map((row) => row[i]))
}

function f(a) {
    return a.length === 0 ? [] : [...a.shift(), ...f(transpose(a).reverse())];
} 
let arr = f([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]])
console.log(arr.join(','));

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll be more attentive. Prompt, and whether it is possible to return result in the form: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], now the output is comma-separated and in a strange way?
Hey @AdamCobain -- I noticed that too. See the second code snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.