Ruby Nested Array - ruby

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"]]

Related

How to join second or third dimension array items without affecting first dimension

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"]

Produce all permutations of a number's digits

I've recently solved a problem, which takes a 3-4 digit number, such as 1234, (as well as some greater numbers) and returns a sorted array of ALL the possible permutations of the numbers [1234, 1432, 4213, 2431, 3412, 3214, etc.]
I don't like my solution, because it used .times to add the numbers to the array, and thus is still fallible, and furthermore ugly. Is there a way that the numbers could be added to the array the perfect number of times, so that as soon as all the possible shufflings of the numbers have been reached, the program will stop and return the array?
def number_shuffle(number)
array = []
number = number.to_s.split(//)
1000.times{ array << number.shuffle.join.to_i}
array.uniq.sort
end
Do as below using Array#permutation:
>> a = 1234.to_s.chars
=> ["1", "2", "3", "4"]
>> a.permutation(4).to_a
=> [["1", "2", "3", "4"],
["1", "2", "4", "3"],
["1", "3", "2", "4"],
["1", "3", "4", "2"],
["1", "4", "2", "3"],
["1", "4", "3", "2"],
["2", "1", "3", "4"],
["2", "1", "4", "3"],...]
Your modified method will be :
def number_shuffle(number,size)
number.to_s.chars.permutation(size).to_a
end
For your method it will be:
def number_shuffle(number)
a = number.to_s.chars
a.permutation(a.size).to_a.map { |b| b.join.to_i }
end
p number_shuffle 123 # => [123, 132, 213, 231, 312, 321]

How to access a hash that has a key that's an array and a value that's an integer

So I have a hash that looks like:
hash = { ["1", "2", "3"]=>"a", ["4", "5", "6"]=>"b", ["7", "8", "9"]=>"c" }
Though when I try to do something like hash[0] just a new line in my console shows up and if I try hash[0][0] it pops me an error that says [] method is undefined.
Now I'm wondering how to I access this in a way that I can do something like hash["1"] and it'll return me the "a".
I assume that since it lets me make hashes in this way I can access the content inside.
I'm not sure why you would want to create a hash with a key that's an array, but it works :)
hash = { ["1", "2", "3"]=>"a", ["4", "5", "6"]=>"b", ["7", "8", "9"]=>"c" }
hash[["1", "2", "3"]]
=> "a"
You might want to consider the opposite:
hash = { "a"=>["1", "2", "3"], "b"=>["4", "5", "6"], "c"=>["7", "8", "9"] }
hash["a"]
=> ["1", "2", "3"]
There's not a direct built-in way to access something like this, but by using select you can filter out the key/value pair that has the "1" and get the value for it:
hash.select { |key| key.include?("1") }.values.first
This assumes that each integer only exists in a single key.

How to combination/permutation in ruby?

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.

Array Semi-Flattening

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]

Resources