如何从特定点得到对角线值?

0g0grzrc  于 2022-09-21  发布在  Ruby
关注(0)|答案(7)|浏览(196)

假设我有10x10矩阵,其中包含以下数据:

我的位置在[4][4]。我怎么才能列出这个位置的对角线数值呢?

例如,预期结果将是:

[56, 67, 78, 89, 100, 1, 12, 23, 34]
[54, 63, 72, 81, 9, 18, 27, 36]

我目前的解决方案

def next?(index, row, size)
    (((row + index) % size) + 1 ) % size
  end

  (1...chess_size).each do |l|
    next_el, curr_el = next?(l, row, chess_size), (row + l) % chess_size

    # this gets me the first diagnonal. Note that it prints out wrong value
    tmp[0] << chess[curr_el][curr_el]

    # this gets me the values from current row below to up
    tmp[1] << chess[(row + l) % chess_size][row]
    tmp[2] << chess[-l][l]
    tmp[3] << chess[row][(row + l) % chess_size]
  end

我们的矩阵将始终具有相同的行数和列数。

xpcnnkqh

xpcnnkqh1#

通常,要从ij获得对角线值,可以同时迭代ij,直到其中一个为零。因此,主对角线是(i-1, j-1), (i-2, j-2), ...i, j >= 0(i + 1, j + 1), (i +2, j + 2), ...i, j <= n。对角线是(i - 1, j + 1), (i - 2, j + 2), ...i >= 0j <= n(i + 1, j-1), (i + 2, j - 2), ...i <= nj >= 0

pu82cl6c

pu82cl6c2#

这是HackerRank Queen's attack问题的解决方案。

代码

def count_moves(n, obs, qrow, qcol)
  qdiff = qrow-qcol
  qsum =  qrow+qcol  
  l = u = -1
  r = d =  n
  ul = qdiff >= 0 ? qrow-qcol-1 : -1
  dr = qdiff >= 0 ? n           : qrow+n-qcol
  ur = qsum < n   ? -1          : qrow-n+qcol
  dl = qsum < n   ? qrow+qcol+1 : n
  obs.uniq.each do |i,j|
    case i <=> qrow
    when -1               # up
      case j <=> qcol
      when -1               # up-left
        ul = [ul,i].max
      when 0                # up same col
        u  = [u,i].max
      when 1                # up-right
        ur = [ur,i].max
      end
    when 0                # same row
      j < qcol ? (l = [l,j].max) : r = [r,j].min
    else                  # down
      case j <=> qcol
      when -1               # down-left
        dl = [dl,i].min
      when 0                # down same col
        d  = [d,i].min
      when 1                # down-right
        dr = [dr,i].min
      end
    end
  end
  r + dl + d + dr - l - ul -u - ur - 8
end

示例

假设棋盘有9行和列,女王的位置用字符q表示,每个障碍用字母o表示。所有其他位置由字母x表示。我们看到女王有16可能的移动(7上和下,6左右,1在上-左到下-右对角线上,2在上-右-下-左对角线上。

arr = [
  %w| x x x x x x x x x |, # 0
  %w| o x x x x x x x x |, # 1
  %w| x o x x x x x x x |, # 2
  %w| x x o x x x x x o |, # 3
  %w| x x x o x x x x x |, # 4
  %w| x x x x x x o x x |, # 5
  %w| o o x x x q x x x |, # 6
  %w| x x x x x x o x x |, # 7
  %w| x x x x x o x x x |  # 8

# 0 1 2 3 4 5 6 7 8

]

qrow = qcol = nil
obs = []
n = arr.size
arr.each_with_index do |a,i|
  a.each_with_index do |c,j|
    case c
    when 'o'
      obs << [i,j]
    when 'q'
      qrow=i
      qcol=j
    end
  end
end
qrow
  #=> 6
qcol
  #=> 5
obs
  #=> [[1, 0], [2, 1], [3, 2], [3, 8], [4, 3], [5, 6], [6, 0], [6, 1], [7, 6], [8, 5]]

count_moves(n, obs, qrow, qcol)
  #=> 16

说明

  • l是女王排中障碍物的最大列索引,小于女王的列索引;
  • r是大于女王列索引的女王障碍物的较小列索引;
  • u是女王栏中障碍物的最大行索引,小于女王行索引;
  • d是女王列中大于女王行索引的障碍物的最小行索引;
  • ul是女王左上角至右下角对角线上的障碍物的最大行索引数,小于女王的行索引数;
  • dr是女王左上角至右下角对角线上的障碍物的最小行索引,大于女王行索引;
  • ur是女王右上角至左下角对角线上的障碍物的最大行索引,小于女王行索引;以及
  • dl是女王从右上角到左下角对角线上的障碍物的最小行索引,它大于女王的行索引。

对于上例,在考虑障碍物之前,将这些变量设置为下列值。

l  =  0
r  =  9
ul =  0 
u  = -1
ur =  2
dl =  9
d  =  9
dr =  9

注意,如果女王具有行和列索引qrowqcol

  • 所有地点的i - j = qrow - qcol在女王的左上角至右下角的对角线上;以及
  • i + j = grow + gcol用于所有位置[i, j],在女王的右上角到左下角对角线上

然后,我们遍历所有(唯一的)障碍,为每个障碍确定它是在女王的行、女王的列中,还是在女王的一条对角线中,如果它比以前最接近的位置“更接近”女王,则用它的行或列索引替换适用变量的值。

例如,如果障碍物位于女王的行且其列索引j小于女王的列索引,则进行以下计算:

l = [l, j].max

同样,如果障碍物位于女王的左上角到右下角的对角线上,并且其行索引i小于女王的行索引,则计算将为:

ul = [ul, i].max

在考虑了上例中的所有障碍之后,变量具有下列值。

l  #=>  1
r  #=>  9
ul #=>  4
u  #=> -1
ur #=>  5
dl #=>  9
d  #=>  8
dr #=>  7

最后,我们计算女王可以移动到的方格总数。

qcol - l  - 1 +  # left
r - qcol  - 1 +  # right
u - qrow  - 1 +  # up
grow - d  - 1 +  # down
ul - qrow - 1 +  # up-left
ur - qrow - 1 +  # up-right
qrow - dl - 1 +  # down-left
qrow - dr - 1    # down-right

这就简化为

r + dl + d + dr - l - ul -u - ur - 8
  #=> 9 + 9 + 8 + 7 - 1 - 4 + 1 - 5 - 8 => 16
qrjkbowd

qrjkbowd3#

我应用了@OMG提供的逻辑。不确定它的效率会有多高。

def stackOverflow(matrixSize, *args)
  pos, obstacles = *args
  chess = (1..(matrixSize * matrixSize)).each_slice(matrixSize).to_a
  obstacles.each do |l| chess[l[0]][l[1]] = '_' end
  row, col = pos[:row] - 1, pos[:col] - 1
  chess[row][col] = '♙'
  directions = [[],[],[],[],[],[],[],[]]

  (1...matrixSize).each do |l|
    directions[0] << chess[row + l][col + l] if (row + l) < matrixSize && (col + l) < chess_size
    directions[1] << chess[row - l][col - l] if (row - l) >= 0 && (col - l) >= 0
    directions[2] << chess[row + l][col - l] if (row + l) < matrixSize && (col - l) >= 0
    directions[3] << chess[row - l][col + l] if (row - l) >= 0 && (col + l) < matrixSize
    directions[4] << chess[row + l][col] if row + l < matrixSize
    directions[5] << chess[row - l][col] if row - l >= 0
    directions[6] << chess[row][col + l] if col + l < matrixSize
    directions[7] << chess[row][col - l] if col - l >= 0
  end
end

stackOverflow(5, 3, {row: 4, col: 3}, [[4,4],[3,1],[1,2]] )
uqzxnwby

uqzxnwby4#

@CarySwoveland看起来@Jamy正在处理HackerRank queens-attack的另一个问题。

这个问题相当困难,因为这个想法是从一开始就永远不会创建矩阵。也就是说,测试用例变得非常大,因此空间复杂性将是一个问题。

我已经更改了我的实现,但仍然因为超时问题而失败(这是因为测试用例变得非常大)。我不确定如何才能让它具有表现力。

在我展示密码之前。让我用插图来解释我想要做的事情:

这是我们的国际象棋:

---------------------------
 |  1     2     3     4     5 |
 |  6     7     8     9    10 |
 | 11    12    13    14    15 |
 | 16    17    18    19    20 |
 | 21    22    23    24    25 |
   ---------------------------

这就是我们的女王所在的地方:queen[2][3]

---------------------------
 |  1     2     3     4     5 |
 |  6     7     8     9    10 |
 | 11    12    13     ♙    15 |
 | 16    17    18    19    20 |
 | 21    22    23    24    25 |
   ---------------------------

女王可以攻击所有8个方向。即:

horizontal(x2): 
   1. from queen position to left         : [13, 12, 11]
   2. from queen position to right        : [15]

 vertical(x2):
   1. from queen position to top          : [9, 4]
   2. from queen position to bottom       : [19, 24]

 diagonal(x2):
   1. from queen position to bottom-right : [20]
   2. from queen position to top-left     : [8, 2]

 diagonal(x2):
   1. from queen position to bottom-left  : [18, 22]
   2. from queen position to top-right    : [10]

因为在这8条路径内没有障碍,女王总共可以攻击14次攻击。

假设我们遇到了一些障碍:

---------------------------
 |  1     2     3     4     5 |
 |  6     7     x     9    10 |
 | 11     x    13     ♙    15 |
 | 16    17    18    19     x |
 | 21     x    23     x    25 |
   ---------------------------

现在女王总共可以攻击7次攻击:[13, 18, 19, 15, 10, 9, 4]

代码

MAXI = 10**5

def queens_attack(size, number_of_obstacles, queen_pos, obstacles)
  # exit the function if...

  # size is negative or more than MAXI. Note MAXI has constraint shown in hackerrank
  return if size < 0 || size > MAXI

  # the obstacles is negative or more than the MAXI
  return if number_of_obstacles < 0 || number_of_obstacles > MAXI

  # the queen's position is outside of our chess dimension
  return if queen_pos[:row] < 1 || queen_pos[:row] > size
  return if queen_pos[:col] < 1 || queen_pos[:col] > size

  # the queen's pos is the same as one of the obstacles
  return if [[queen_pos[:row], queen_pos[:col]]] - obstacles == []

  row, col = queen_pos[:row], queen_pos[:col]

  # variable to increment how many places the queen can attack
  attacks = 0

  # the queen can attack on all directions:
  # horizontals, verticals and both diagonals. So let us create pointers
  # for each direction. Once the obstacle exists in the path, make the 
  # pointer[i] set to true
  pointers = Array.new(8, false)
  (1..size).lazy.each do |i|

    # this is the diagonal from queen's pos to bottom-right
    if row + i <= size && col + i <= size && !pointers[0]
      # set it to true if there is no obstacle in the current [row + i, col + i]
      pointers[0] = true unless [[row + i, col + i]] - obstacles != []
      # now we know the queen can attack this pos
      attacks += 1 unless pointers[0]
    end

    # this is diagonal from queen's pos to top-left
    if row - i > 0 && col - i > 0 && !pointers[1]
      # set it to true if there is no obstacle in the current [row - i, col - i]
      pointers[1] = true unless [[row - i, col - i]] - obstacles != []
      # now we know the queen can attack this pos
      attacks += 1 unless pointers[1]
    end

    # this is diagonal from queen's pos to bottom-left
    if row + i <= size && col - i > 0 && !pointers[2]
      pointers[2] = true unless [[row + i, col - i]] - obstacles != []
      attacks += 1 unless pointers[2]
    end

    # this is diagonal from queen's pos to top-right
    if row - i > 0 && col + i <= size && !pointers[3]
      pointers[3] = true unless [[row - i, col + i]] - obstacles != []
      attacks += 1 unless pointers[3]
    end

    # this is verticle from queen's pos to bottom
    if row + i <=size && !pointers[4]
      pointers[4] = true unless [[row + i, col]] - obstacles != []
      attacks += 1 unless pointers[4]
    end

    # this is verticle from queen's pos to top
    if row - i > 0 && !pointers[5]
      pointers[5] = true unless [[row - i, col]] - obstacles != []
      attacks += 1 unless pointers[5]
    end

    # this is horizontal from queen's pos to right
    if col + i <= size && !pointers[6]
      pointers[6] = true unless [[row, col + i]] - obstacles != []
      attacks += 1 unless pointers[6]
    end

    # this is horizontal from queen's pos to left
    if col - i > 0 && !pointers[7]
      pointers[7] = true unless [[row, col - i]] - obstacles != []
      attacks += 1 unless pointers[7]
    end
  end
  p attacks
end

问题

现在的问题是,我不知道为什么我的代码会从HackerRank中执行超时错误。我知道这一点是因为测试用例,其中国际象棋的维度可以是10,000×10,000。但我不知道我错过了什么约束。

xj3cbfub

xj3cbfub5#

我刚刚从OP发布的一条评论中了解到,我解决了错误的问题,尽管OP的问题似乎很清楚,特别是这个例子,并且与我的解释一致。我将把这个解决方案留给以下问题:“给定一个数组arr使得Matrix(*arr)是一个NxM矩阵,以及一个矩阵位置i,j,返回一个数组[d,a],其中元素da是通过[d,a]但不包括[d,a]的对角线上的元素,并且每个元素都被旋转,使得第一个元素的行索引在i < arr.size-1时是i+1,否则是0

代码

def diagonals(arr, row_idx, col_idx) 
  ncols = arr.first.size
  sum_idx = row_idx+col_idx
  diff_idx = row_idx-col_idx
  a = Array.new(arr.size * arr.first.size) { |i| i.divmod(ncols) } -[[row_idx, col_idx]]
  [a.select { |r,c| r-c == diff_idx }, a.select { |r,c| r+c == sum_idx }].
    map do |b| b.sort_by { |r,_| [r > row_idx ? 0:1 , r] }.
      map { |r,c| arr[r][c] }
    end
end

数组arr的所有元素的大小必须相等,但不要求arr.size = arr.first.size

示例

arr = [
  [ 1,  2,  3,  4,  5,  6,  7,  8,  9,  10],
  [11, 12, 13, 14, 15, 16, 17, 18, 19,  20],
  [21, 22, 23, 24, 25, 26, 27, 28, 29,  30],
  [31, 32, 33, 34, 35, 36, 37, 38, 39,  40],
  [41, 42, 43, 44, 45, 46, 47, 48, 49,  50],
  [51, 52, 53, 54, 55, 56, 57, 58, 59,  60],
  [61, 62, 63, 64, 65, 66, 67, 68, 69,  70],
  [71, 72, 73, 74, 75, 76, 77, 78, 79,  80],
  [81, 82, 83, 84, 85, 86, 87, 88, 89,  90],
  [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
]

diagonals(arr, 4, 4)
  #=> [[56, 67, 78, 89, 100, 1, 12, 23, 34],
  #    [54, 63, 72, 81, 9, 18, 27, 36]]

说明

假设

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

row_idx = 2
col_idx = 1

具体步骤如下。

a = Array.new(arr.size) { |i| Array.new(arr.first.size) { |j| [i,j] } }
  #=> [[[0, 0], [0, 1], [0, 2], [0, 3]],
  #    [[1, 0], [1, 1], [1, 2], [1, 3]],
  #    [[2, 0], [2, 1], [2, 2], [2, 3]],
  #    [[3, 0], [3, 1], [3, 2], [3, 3]]]
ncols = arr.first.size
  #=> 4
sum_idx = row_idx+col_idx
  #=> 3
diff_idx = row_idx-col_idx
  #=> 1
a = Array.new(arr.size * arr.first.size) { |i| i.divmod(ncols) } - [[row_idx, col_idx]]
  #=> [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3],
  #    [2, 0], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]

选择通过[row_idx, col_idx]的左上角到右下角对角线上的位置[r, c]并对其进行排序。

b = a.select { |r,c| r-c == diff_idx }
  #=> [[1, 0], [3, 2]]
c = b.sort_by { |r,_| [r > row_idx ? 0:1 , r] }
  #=> [[3, 2], [1, 0]]

选择通过[row_idx, col_idx]的左下角对角线上的位置[r, c]并对其进行排序。

d = a.select { |r,c| r+c == sum_idx }
  #=> [[0, 3], [1, 2], [3, 0]]
e = d.sort_by { |r,c| [r > row_idx ? 0:1 , r] }
  #=> [[3, 0], [0, 3], [1, 2]]
[c, e].map { |f| f.map { |r,c| arr[r][c] }
  #=> [c, e].map { |f| f.map { |r,c| arr[r][c] } }
  #=> [[15, 5], [13, 4, 7]]
yvt65v4c

yvt65v4c6#

我刚刚从OP发布的一条评论中了解到,我解决了错误的问题,尽管OP的问题似乎很清楚,特别是这个例子,并且与我的解释一致。我将把这个解决方案留给以下问题:“给定一个数组arr使得Matrix(*arr)是一个NxM矩阵,以及一个矩阵位置i,j,返回一个数组[d,a],其中元素da是通过[d,a]但不包括[d,a]的对角线上的元素,并且每个元素都被旋转,使得第一个元素的行索引在i < arr.size-1时是i+1,否则是0

以下方法使用Matrix类中的方法。

代码

require 'matrix'

def diagonals(arr, row_idx, col_idx)      
  [diag(arr, row_idx, col_idx),
   diag(arr.map(&:reverse).transpose, arr.first.size-1-col_idx, row_idx)]
end

def diag(arr, row_idx, col_idx)
  nrows, ncols = arr.size, arr.first.size
  lr = [ncols-col_idx, nrows-row_idx].min - 1
  ul = [col_idx, row_idx].min
  m = Matrix[*arr]
  [*m.minor(row_idx+1,  lr, col_idx+1,  lr).each(:diagonal).to_a,
   *m.minor(row_idx-ul, ul, col_idx-ul, ul).each(:diagonal).to_a]
end

示例

arr = [
  [ 1,  2,  3,  4,  5,  6,  7,  8,  9,  10],
  [11, 12, 13, 14, 15, 16, 17, 18, 19,  20],
  [21, 22, 23, 24, 25, 26, 27, 28, 29,  30],
  [31, 32, 33, 34, 35, 36, 37, 38, 39,  40],
  [41, 42, 43, 44, 45, 46, 47, 48, 49,  50],
  [51, 52, 53, 54, 55, 56, 57, 58, 59,  60],
  [61, 62, 63, 64, 65, 66, 67, 68, 69,  70],
  [71, 72, 73, 74, 75, 76, 77, 78, 79,  80],
  [81, 82, 83, 84, 85, 86, 87, 88, 89,  90],
  [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
]

diagonals arr, 4, 4
  #=> [[56, 67, 78, 89, 100, 1, 12, 23, 34], [54, 63, 72, 81, 9, 18, 27, 36]]
diagonals arr, 4, 5
  #=> [[57, 68, 79, 90, 2, 13, 24, 35], [55, 64, 73, 82, 91, 10, 19, 28, 37]]
diagonals arr, 0, 9
  #=> [[], [19, 28, 37, 46, 55, 64, 73, 82, 91]]

说明

假设阵列和目标位置如下所示。

arr = (1..30).each_slice(6).to_a
  #=> [[ 1,  2,  3,  4,  5,  6],
  #    [ 7,  8,  9, 10, 11, 12],
  #    [13, 14, 15, 16, 17, 18],
  #    [19, 20, 21, 22, 23, 24],
  #    [25, 26, 27, 28, 29, 30]]

row_idx = 2
col_idx = 3

arr[2][3] #=> 16。我们通过计算两个矩阵的子式的对角线来得到负斜率的对角线:

[[23, 24],
 [29, 30]]

[[2, 3],
 [8, 9]]

给了我们

[*[23, 30], *[2, 9]]
  #=> [23, 30, 2, 9]

为了获得另一条对角线,我们将阵列逆时针旋转90度,调整row_idxcol_idx,并重复上述过程。

arr.map(&:reverse).transpose
  #=> [[6, 12, 18, 24, 30],
  #    [5, 11, 17, 23, 29],
  #    [4, 10, 16, 22, 28],
  #    [3,  9, 15, 21, 27],
  #    [2,  8, 14, 20, 26],
  #    [1,  7, 13, 19, 25]]

ncols = arr.first.size
  #=> 6
row_idx, col_idx = ncols-1-col_idx, row_idx
  #=> [2, 2]

现在我们从矩阵子式中提取对角线

[[21, 27],
 [20, 26]]

[[6, 12],
 [5, 11]]

要获得第二条对角线,请执行以下操作:

[21, 26, 6, 11]
lmyy7pcs

lmyy7pcs7#

def possible_moves(val):
  # val is a value between 0 and n*n-1
  for i in range(n*n):
    if i == val:
      board[i // n][i % n] = 'Q'
      continue
    #mark row and column with a dot
    if i % n == val % n or i // n == val // n: 
      board[i//n][i%n] = '.'

    # mark diagonals with a dot
    if i % (n + 1) == val % (n + 1) and abs(i % n - val % n) == abs(i // n - val // n): 
      board[i//n][i%n] = '.'
    if i % (n - 1) == val % (n - 1) and abs(i % n - val % n) == abs(i // n - val // n):
      board[i//n][i%n] = '.'

n = 10 #board size = n x n
board = [['0' for x in range(n)] for y in range(n)] #initialize board with '0' in every row and col

possible_moves(40)

在结尾处,女王所在的位置会有一个‘Q’,在Q不能移动的位置有‘0’和‘’。她可以移动的地方

相关问题