【问题标题】:change random postions in matrix改变矩阵中的随机位置
【发布时间】:2021-08-11 14:52:48
【问题描述】:

我用零填充矩阵

[
  [0,0,0,0,0],
  [0,0,0,0,0],
  [0,0,0,0,0],
  [0,0,0,0,0],
  [0,0,0,0,0]
]

用 -1 更改 5 个随机零的最有效方法是什么

[
  [0,-1,0,0,0],
  [0,0,-1,0,0],
  [0,0,0,0,0],
  [-1,0,-1,0,0],
  [0,0,-1,0,0]
]

我尝试了这个解决方案,但我认为有比这个更好的解决方案

funtion solution(matrix:number[][],times = 5){
   if(times === 0) return
   const i = Math.floor(Math.random() * matrix.length)
   const j = Math.floor(Math.random() * matrix[i].length)
   if(matrix[i][j] === -1) return solution(matrix,times)
   matrix[i][j] = -1
   return solution(matrix,times - 1)
}

我想要任何编程语言的解决方案 谢谢你的帮助

【问题讨论】:

    标签: algorithm matrix


    【解决方案1】:
    construct empty set S
    set size = col count * row count
    while S size < 5
       generate random in range [ 0, size-1 ]
       insert random into S
    loop r over S
       set row = r( modulus ) col_count
       set col = r- row * col_count 
       set matrix[ col, row ] = -1
    

    在一个集合中,一个元素的值也标识它(值本身就是键),并且每个值必须是唯一的。例如http://www.cplusplus.com/reference/set/set/

    该算法假定矩阵索引首先更改 col 索引。如果您的矩阵以相反的方式被索引,您将不得不更改 r 循环以匹配

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多