For this program I'm making i need to join together some arrays in a multidimensional array:
What the array is:
[["2", "2"]["0", "9"]["2", "2"]["2", "7"]["1", "7"]["0", "8"]["0", "1"]
["0", "9"]]
And I want it to become like this:
["22", "09", "22", "27", "17", "08", "01", "09"]
Sorry if this is a really dumb question but if someone can help me I would be very happy, and if it is impossible to do this, then please tell me.
Thanks.
Try this:
multi_dimensional_array = [["2", "2"], ["0", "9"], ["2", "2"], ["2", "7"], ["1", "7"], ["0", "8"], ["0", "1"], ["0", "9"]]
multi_dimensional_array.map(&:join)
map iterates over the entries in your array and returns a copy of the array with modified entries.
&:join sends join to every member of the iteration by converting the symbol to a block using Symbol#to_proc: You can read it as if it expands to:
->(entry){ entry.send(:join) }
Generally the pattern is:
list = [["2", "2"],["0", "9"],["2", "2"],["2", "7"],["1", "7"],["0", "8"],["0", "1"],["0", "9"]]
# For each item in the list, transform it...
list.collect do |entry|
# ...by joining the bits together into a single string.
entry.join
end
Related
I am trying to create an array that shows every digit permutation of a given number input. With a given input "123", the array should look like this:
["123", "132", "213", "231", "312", "321"]
I can get an array containing arrays of the separate digits:
a = []
"123".split('').each {|n| a.push(n) }
arraycombinations = a.permutation(a.length).to_a
# => [["1", "2", "3"], ["1", "3", "2"], ["2", "1", "3"], ["2", "3", "1"], ["3", "1", "2"], ["3", "2", "1"]]
but I cannot figure out how to join the second or third dimensions of arraycombinations while preserving the first dimension.
Each of these attempts failed:
arraycombinations.map {|x| print arraycombinations.join("") }
arraycombinations.map {|ar| ar.split(",") }
arraycombinations.each {|index| arraycombinations(index).join("") }
How can I isolate the join function to apply to only the second dimension within a multidimensional array?
Assuming you already have an array of arrays such as
a = [["1","2","3"],["1","3","2"],["2","1","3"],["2","3","1"], ["3","1","2"],["3","2","1"]]
a.map { |i| i.join}
#=>["123", "132", "213", "231", "312", "321"]
It's simple really
"123".split("").permutation.to_a.map { |x| x.join }
Let me explain a bit:
"123".split("") gives you an array ["1","2","3"]
permutation.to_a gives you array of arrays [["1","2","3"], ["2","1","3"] ... ]
then you must join each of those arrays inside with map { |x| x.join }
and you get the required end result.
Like this:
arraycombinations.map(&:join)
# => ["123", "132", "213", "231", "312", "321"]
I have a nested array that looks like this:
#nested = [
['1','2','3'],
['1','5','9'],
['1','4','7'],
['3','5','7'],
['3','6','9'],
['7','8','9'],
['4','5','6'],
['2','5','8']
]
I'd like to take a user input of any integer (that 1..9) and find every array that has that input integer.
Not sure how to do it.
Use select:
num_to_search = "9"
#nested.select do |array|
array.include? num_to_search
end
#=> [["1", "5", "9"], ["3", "6", "9"], ["7", "8", "9"]]
I've this familiar question that looks like permutation/combination of the Math world.
How can I achieve the following via ruby?
badges = "1-2-3"
badge_cascade = []
badges.split("-").each do |b|
badge_cascade << b
end
Gives: => ["1", "2", "3"]
But I want it to be is:
=> ["1", "2", "3",
"1-2", "2-3", "3-1", "2-1", "3-2", "1-3",
"1-2-3", "2-3-1", "3-1-2"]
Functional approach:
bs = "1-2-3".split("-")
strings = 1.upto(bs.size).flat_map do |n|
bs.permutation(n).map { |vs| vs.join("-") }
end
#=> ["1", "2", "3", "1-2", "1-3", "2-1", "2-3", "3-1", "3-2", "1-2-3", "1-3-2", "2-1-3", "2-3-1", "3-1-2", "3-2-1"]
You ned to use Array#permutation method in order to get all permutations:
arr = "1-2-3".split '-' # => ["1", "2", "3"]
res = (1..arr.length).reduce([]) { |res, length|
res += arr.permutation(length).to_a
}.map {|arr| arr.join('-')}
puts res.inspect
# => ["1", "2", "3", "1-2", "1-3", "2-1", "2-3", "3-1", "3-2", "1-2-3", "1-3-2", "2-1-3", "2-3-1", "3-1-2", "3-2-1"]
Let me explain the code:
You split string into array passing separator '-' to String#split method
You need all permutations of length 1, 2, 3. Range 1..arr.length represents all these lengths.
You collect an array of all permutations using Enumerable#reduce.
You will get array of arrays here:
[["1"], ["2"], ["3"], ["1", "2"], ["1", "3"], ["2", "1"], ["2", "3"], ["3", "1"], ["3", "2"], ["1", "2", "3"], ["1", "3", "2"], ["2", "1", "3"], ["2", "3", "1"], ["3", "1", "2"], ["3", "2", "1"]]
You transform all subarrays of this array into strings using Array#join with your '-' separator inside of Enumerable#map
Array#permutation(n) will give you all the permutations of length n as an Array of Arrays so you can call this with each length between 1 and the number of digits in badges. The final step is to map these all back into strings delimited with -.
badges = "1-2-3"
badges_split = badges.split('-')
permutations = []
(1..badges_split.size).each do |n|
permutations += badges_split.permutation(n).to_a
end
result = permutations.map { |permutation| permutation.join('-') }
Update: I think Alex's use of reduce is a more elegant approach but I'll leave this answer here for now in case it is useful.
Want to convert this:
[["1", "2", "3"], ["4", "5", "6"]]
to this:
["1", "2", "3"], ["4", "5", "6"]
to be passed into Array.product(), and the first array can contain an unknown number of other arrays. for example, the array given may also be
[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]
And ultimately, I need to pass the argument as:
otherArray.product(["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"])
Thanks ahead of time!
otherArray.product(*[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]);
* is used in argument list to unpack array contents to arguments (like
here) or to pack arguments into an array,like in "def mymethod(*args)"
Reference: http://www.justskins.com/forums/apply-method-to-array-17387.html
I think what would work for you is using Ruby's Array expansion:
a=[[1,2,3],[4,5,6]]
b=[1,2,3].product([1,2,3],[4,5,6])
c=[1,2,3].product(*a)
b == c #This should be true
Basically putting the asterisk (*) in front of the variable will expand all elements in the array into a list of arguments, which is what you want.
The last line of code aside, the rest of it seems to be solved by using the 0 index:
arr[0]
How can you change this array:
[["1","one"], ["2","two"], ["3","three"]]
to this?
["1","one"], ["2","two"], ["3","three"]
Clarification
My apologies for giving an invalid second version. This is what I'm really going for:
I want to add ["0","zero"] to the beginning of [["1","one"], ["2","two"], ["3","three"]], to get:
[["0","zero"], ["1","one"], ["2","two"], ["3","three"]]
I have tried:
["0","zero"] << [["1","one"], ["2","two"], ["3","three"]]
The above approach produces this, which contains a nesting I don't want:
[["0","zero"], [["1","one"], ["2","two"], ["3","three"]]]
unshift ought to do it for you:
a = [["1","one"], ["2","two"], ["3","three"]]
a.unshift(["0", "zero"])
=> [["0", "zero"], ["1", "one"], ["2", "two"], ["3", "three"]]
You are probably looking for flatten:
Returns a new array that is a one-dimensional flattening of this array (recursively). That
is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten.
[["1","one"], ["2","two"], ["3","three"]].flatten
Which gives you:
=> ["1", "one", "2", "two", "3", "three"]
[["1","one"], ["2","two"], ["3","three"]].flatten
You need to make your questions clearer, but is the following what you meant?
# Right answer
original = [["1","one"], ["2","two"]]
items_to_add = [["3","three"], ["4","four"]]
items_to_add.each do |item|
original << item
end
original # => [["1", "one"], ["2", "two"], ["3", "three"], ["4", "four"]]
# Wrong answer
original = [["1","one"], ["2","two"]]
items_to_add = [["3","three"], ["4","four"]]
original << items_to_add # => [["1", "one"], ["2", "two"], [["3", "three"], ["4", "four"]]]