从另一个数组生成有限组合的数组
Generate array of limited combinations from another array
我需要根据一组给定的字符串在 rails 中生成 2D
数组。例如:
days =[ "Monday",
"Tuesday",
"Wednesday",
]
现在我想创建一个 2D
数组,这个数组中的数据将使用 days
字符串随机填充。
示例:
[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...
等等取决于给定的维度
怎么做?
编辑
我试过了
# global variable
@@test_array = %w(:sunday :monday :tuesday)
def get_data(row, col)
@data_field = @@test_array.permutation.to_a(col)
return @data_field.slice!(row)
如果我传递 row:1
和 col:1
它正在工作,但是如果我在 rows
和 column
中传递一个像 20 这样的大数字,它会将 null 存储在数据库中。
Edit-2
days = ["monday, "tuesday"]
rows = 3
col = 3
应该return(随机生成可能的解决方案之一)
[[monday, tuesday, monday],[tuesday, monday, tuesday], [monday, monday, tuesday]]
如果你不想在子数组中重复,你可以使用Array#permutation
。
col
1 ∈ [1; 3]
row
2 ∈ [0; 3]
days.permutation(col).to_a.slice(0, row)
如果你想在子数组中重复,你可以使用Array#repeated_permutation
。
col
∈ [1; 3]
row
∈ [0; 33(= 27)]:
days.repeated_permutation(col).to_a.slice(0, row)
如果你想在子数组中重复,并将你的列号扩展到自定义,独立于原始数组号的长度,你可以使用 Array#repeated_combination
。
col
∈ [1; ∞3 )
row
∈ [0; col
col
]:
days.repeated_combination(col).to_a.slice(0, row)
1 col
是每个子数组的元素个数。
2 row
是所需二维数组中子数组的个数。
3 上限指定为∞表示这个值不是以原始数组的长度为界。
我需要根据一组给定的字符串在 rails 中生成 2D
数组。例如:
days =[ "Monday",
"Tuesday",
"Wednesday",
]
现在我想创建一个 2D
数组,这个数组中的数据将使用 days
字符串随机填充。
示例:
[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...
等等取决于给定的维度
怎么做?
编辑
我试过了
# global variable
@@test_array = %w(:sunday :monday :tuesday)
def get_data(row, col)
@data_field = @@test_array.permutation.to_a(col)
return @data_field.slice!(row)
如果我传递 row:1
和 col:1
它正在工作,但是如果我在 rows
和 column
中传递一个像 20 这样的大数字,它会将 null 存储在数据库中。
Edit-2
days = ["monday, "tuesday"]
rows = 3
col = 3
应该return(随机生成可能的解决方案之一)
[[monday, tuesday, monday],[tuesday, monday, tuesday], [monday, monday, tuesday]]
如果你不想在子数组中重复,你可以使用Array#permutation
。
col
1 ∈ [1; 3]row
2 ∈ [0; 3]
days.permutation(col).to_a.slice(0, row)
如果你想在子数组中重复,你可以使用Array#repeated_permutation
。
col
∈ [1; 3]row
∈ [0; 33(= 27)]:
days.repeated_permutation(col).to_a.slice(0, row)
如果你想在子数组中重复,并将你的列号扩展到自定义,独立于原始数组号的长度,你可以使用 Array#repeated_combination
。
col
∈ [1; ∞3 )row
∈ [0;col
col
]:
days.repeated_combination(col).to_a.slice(0, row)
1 col
是每个子数组的元素个数。
2 row
是所需二维数组中子数组的个数。
3 上限指定为∞表示这个值不是以原始数组的长度为界。