Rotation of a section of a two-dimensional matrix

I read this SO question about how to rotate a two-dimensional array many times, and I was curious how you could expand this situation to work with the cross-section of a two-dimensional array. I thought about this for a while, and I can't come up with a good equation. Essentially, what I want to do is something like this:

1 2 3   4 5 6             13 7 1   4 5 6
 7 8 9   10 11 12            14 8 2   10 11 12
 13 14 15 16 17 18            15 9 3   16 17 18
19 20 21 22 23 24 ----> 19 20 21 22 23 24
25 26 27 28 29 30 25 26 27 28 29 30
31 32 33 34 35 36 31 32 33 34 35 36

Now I am writing this in Ruby, but I don’t particularly like what language this solution will solve. I'm just wondering how you would decide to solve this problem.

Edit: To add some additional features, the main parameters for a function that could do this would be something similar to this

def rotate(array, times=1, x=0, y=0, len=nil)
  ...
end
+3
source share
2 answers

Something like that?

def rotate a,len,ii=0,jj=0,t=1
    t.times do
        a = a.map.with_index do |line,i|
            line.map.with_index do |e,j|
                (ii...(ii+len))===i && (jj...(jj+len))===j ?
                    a[ii+jj+len-j-1][jj+i-ii] : e
            end
        end
    end
    a
end

t = (1..6).map{|i|(1..6).map{|j|j+6*i-6}}
t.each { |i| p i }

rotate(t,3,2,1).each { |i| p i }
rotate(t,6).each { |i| p i }
rotate(t,3,2,1,4).each { |i| p i }
rotate(t,6,0,0,4).each { |i| p i }
rotate(t,2,2,2,3).each { |i| p i }
+2
source

Check this question: How do you rotate a two-dimensional array?

There is a simple way:

2 dimensional array, use

transpose.map &:reverse

+3
source

Source: https://habr.com/ru/post/1761632/


All Articles