Mehdi Kamar
Mehdi Kamar

Reputation: 57

ruby - Permutation between elements of an array

I'm coding a plugin in Google Sketchup with ruby and I faced a real problem while trying to permute two arrays that are present in an array all this depending on a user combination.

I have an array of arrays like [["1"],["lol"], ["so"]]

When we have a combination like this <[1, 2, 3] it's fine, it should stay the same : [["1"],["lol"], ["so"]]

But when we have a combination like this [2, 3, 1], the output should be : [["lol"], ["so"], ["1"]]

For [3,1,2] => [["so"], ["1"], ["lol"]]

...etc

EDIT
Sorry guys I forgot for the array I have a bit like : [["1, 2, 3"], ["lol1, lol2, lol3"], ["so1, so2, so3"]] so for the combination [2, 3, 1] the output should be : [["2, 3, 1"], ["lol2, lol3, lol1"], ["so2, so3, so1"]]

Thanks for helping me out.

Upvotes: 0

Views: 373

Answers (4)

Paul Rubel
Paul Rubel

Reputation: 27212

You could use collect:

array   = [["1"],["lol"], ["so"]]
indexes = [2, 1, 3]
indexes.collect {|i| array[i-1]} #=> [["lol"], ["1"], ["so"]]

If you set the indexes to be 0-based you could drop the -1

split and map can be used to turn your strings into values:

"1, 2, 3".split(",").map { |i| i.to_i} # [1, 2, 3]

You can then also split your strings

"lol2, lol3, lol1".split(/, /) #=> ["lol2", "lol3", "lol1"]

You should be able to put that together with the above to get what you want.

Upvotes: 4

Raf
Raf

Reputation: 1083

a = [["1"], ["lol"], ["so"]]
index = [2, 1, 3]

index.collect {|i| a[i - 1]}

This outputs

[["lol"], ["1"], ["so"]]

Upvotes: 0

apneadiving
apneadiving

Reputation: 115511

indexes = [2, 1, 3]
array   = [["1"],["lol"], ["so"]]
result  = indexes.map{|index| array[index-1] }

Upvotes: 1

Abram
Abram

Reputation: 41844

You should also take a look at active_enum

https://github.com/adzap/active_enum

You could do something like:

class YourClassName < ActiveEnum::Base
  value [1] => ['1']
  value [2] => ['lol'] 
  value [3] => ['so']
end

Upvotes: 0

Related Questions