-1

可能重复:
ruby - 数组元素之间的排列

我正在用 ruby​​ 在 Google Sketchup 中编写一个插件,在尝试置换另一个数组中存在的数组中的不同元素时遇到了一个真正的问题,这一切都取决于用户组合。

我有一个数组,如:

[["a, "b", c"], ["lol1", "lol2", lol3"], ["so1", "so2", "so3"]]

对于这样的组合:

[1, 2, 3]

输出应该仍然相同:

[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]]

但是对于这样的组合:

[2, 1, 3]

输出应该是:

[["b", "a", "c"], ["lol2", "lol1", "lol3"], ["so2", "so1", "so3"]]

但是对于这样的组合:

[3, 2, 1]

输出应该是:

[["c", "b", a"], ["lol3", "lol2", "lol1"], ["so3", "so2", "so1"]]
4

3 回答 3

2
ar = [["a, b, c"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]
p maybe_this = ar.map{|sub_ar| sub_ar.first.split(', ')}
#[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]]
idx = [2,1,3]
#indexing of an array is zero-based
p idx.map!{|i| i-1} #[1,0,2]
p res = maybe_this.map{|sub_ar| sub_ar.values_at(*idx)}
#[["b", "a", "c"], ["lol2", "lol1", "lol3"], ["so2", "so1", "so3"]]

小故事:values_at方法接受多个参数;*idx将一个数组分解为多个参数。

于 2013-02-05T22:58:39.770 回答
1

也许你想要这个:

perm_idx = [1,2,3].permutation.to_a.index([2,3,1])
[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]].map {|x| x.permutation.to_a[perm_idx] }
于 2013-02-05T22:40:44.333 回答
0

不完全确定您想要什么,但这可能对您有用:

a = [["a, b, c"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]

def combi_with_join(ordering, arrays)
  ordering = ordering.map {|x| x - 1}
  arrays.map {|ar| [ar.first.split(/,\s*/).values_at(*ordering).join(", ")] }
end

puts combi_with_join([1, 2, 3], a).inspect
puts combi_with_join([2, 1, 3], a).inspect
puts combi_with_join([3, 2, 1], a).inspect

如果你真的想要一个数组数组......

def combi(ordering, arrays)
  ordering = ordering.map {|x| x - 1}
  arrays.map {|ar| ar.first.split(/,\s*/).values_at(*ordering) }
end

puts combi([1, 2, 3], a).inspect
puts combi([2, 1, 3], a).inspect
puts combi([3, 2, 1], a).inspect
于 2013-02-05T23:15:26.497 回答