I'm hopelessly trying to write a method to manipulate an array in ruby. I'm trying to generate all in-order permutations of an array where each item is in turn replaced by an outside item. An example...
Given input:
arr = ["a", "b", "c"]
Desired output:
newArr = [ ["a", "b", "c"], ["a", "b", "*"], ["a", "*", "c"], ["a", "*", "*"], ["*", "b", "c"], ["*", "b", "*"], ["*", "*", "c"], ["*", "*", "*"] ]
Any help would be greatly appreciated. Thank you!
I don't understand your example order, either, but ignoring that, here's a solution in one line:
(0...(2**a.size)).map {|x| (0...a.size).map {|y| x & 2**y == 0 ? a[y] : val}}
I'm not sure permutation is the right word. If you count in binary, then you are replacing the things if there is a one. Here's that in Ruby:
def mike(arr, sub)
format = sprintf("%%0%db", arr.length)
m = Array.new
0.upto(2**arr.length-1) { |i|
bits = sprintf(format, i).split('')
a = Array.new
0.upto(arr.length-1) { |j|
if bits[j] == '0' then
a << arr[j]
else
a << sub
end
}
m[i] = a
}
return m
end
arr = ["a", "b", "c"]
p mike(arr, '*')
Is that if-then-else better with a ternary operator?
a <<= bits[j] == '0' ? arr[j] : sub
There must be a cleverer (or, at least more Rubyesque) way to do this, but it seems to produce the desired output.
ETA: Oops! My second and third items don't agree with yours. I guess I don't know what order you mean.
Similar to oylenshpeegui's method:
def toggle(arr, sub)
format = "%0#{arr.length}b"
(0...2**(arr.length)).to_a.map do |i|
sprintf(format,i).split('').zip(arr).map { |x| x[0] == "0" ? x[1] : sub }
end
end
The split/zip combo matches each digit of the binary expansion of the index with the element it is selecting. The map at the end uses the digit to decide if it should return the array element or the substitution.
Related
I am trying to take input as a string.
Then I need to find all the possible combination and distinct combination but I am unable to do so.
input = "aabb"
Output I need to print all Combination =
'a','a','b','b','aa','ab','bb','aab','abb','aabb'
Now Distinct combination
'a','b','aa','ab','bb','aab','abb','aabb'
Then I need to count the letters and do a summation
'a','a','b','b','aa','ab','bb','aab','abb','aabb'
For this
result = 1+1+1+1+2+2+2+3+3+4
Similarly for the other combination I need to find summation.
You can use Array#combination.
To get all combinations:
input = "aabb"
res = []
input.size.times { |n| res << input.chars.combination(n+1).map { |a| a.join } }
res.flatten
#=> ["a", "a", "b", "b", "aa", "ab", "ab", "ab", "ab", "bb", "aab", "aab", "abb", "abb", "aabb"]
distinct combinations:
res.flatten.uniq
#=> ["a", "b", "aa", "ab", "bb", "aab", "abb", "aabb"]
to count the letters and do a summation:
res.flatten.uniq.map(&:size)
#=> [1, 1, 2, 2, 2, 3, 3, 4]
res.flatten.uniq.map(&:size).reduce(:+)
# => 18
To get all the substrings of your input (or more generally to get all subsequences of an Enumerable) you can use something like this:
def subsequences(e)
a = e.to_a
indices = (0..a.length - 1).to_a
indices.product(indices)
.reject { |i, j| i > j }
.map { |i, j| a[i..j] }
end
You would use that on your string like this: subsequences(input.chars).map(&:join). The chars and join are only necessary because Strings are not Enumerable, but the subsequences function does not really need that. You can just take out the first line and it should still work for strings (anything that has a "slicing" subscript operator, really ...).
Note also that this is not the only way to do this. The basic problem here is to iterate over all ordered pairs of indices of a sequence. You could also do that with basic loops. I just happen to find the cartesian product method very elegant. ;)
Once you have your first list in a variable, say list, the second task is as easy as list.uniq, and the third one is solved by
list.map(&:size).reduce(:+)
data = {"B"=>"bb", "C"=>"cc", "A"=>"aa", "D"=>"dd", "E"=>"", "F"=>nil}
fields_to_select = ["A", "B", "C"]
str = data.select { |elem| fields_to_select.include? elem }.values.compact.reject(&:empty?).join(', ')
This would currently return bb, cc, aa since that is the order it's in the data hash.
Is there anyway way to create the string based on the order in fields_to_select?
So that it returns aa, bb, cc
Yes...possible using Hash#values_at
data = {"B"=>"bb", "C"=>"cc", "A"=>"aa", "D"=>"dd", "E"=>"", "F"=>nil}
fields_to_select = ["A", "B", "C"]
data.values_at(*fields_to_select).join(', ')
# => "aa, bb, cc"
Granted, values_at is cool stuff, but this problem can also be solved by a garden-variety use of our very old friend map.
fields_to_select.map { |k| data[k] }.join(', ')
This question already has answers here:
Why are exclamation marks used in Ruby methods?
(12 answers)
Closed 8 years ago.
From Ruby's official documentation:
sort → new_ary sort { |a, b| block } → new_ary Returns a new array
created by sorting self.
Comparisons for the sort will be done using the <=> operator or using
an optional code block.
The block must implement a comparison between a and b, and return -1,
when a follows b, 0 when a and b are equivalent, or +1 if b follows a.
See also Enumerable#sort_by.
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
sort! → ary click to toggle source sort! { |a, b| block } → ary Sorts
self in place.
Comparisons for the sort will be done using the <=> operator or using
an optional code block.
The block must implement a comparison between a and b, and return -1,
when a follows b, 0 when a and b are equivalent, or +1 if b follows a.
See also Enumerable#sort_by.
a = [ "d", "a", "e", "c", "b" ]
a.sort! #=> ["a", "b", "c", "d", "e"]
a.sort! { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
The result seems the same, so what's the difference?
sort will not modify the original array whereas sort! will
('!' is the bang method in ruby, it will replace the existing value)
For example:
a = [4,3,2,5,1]
a.sort # => [1,2,3,4,5]
a is still [4,3,2,5,1]
where as
a = [4,3,2,5,1]
a.sort! # => [1,2,3,4,5]
a is now [1,2,3,4,5]
In rails ! used to apply changes and update its calling object means
a.sort will only return sorted array but a.sort! will return sorted array and also save new sort result in a variable.
'!' is the bang method in ruby, it will replace the existing value
ex: .sort is a normal sorting method in ruby
.sort! its a bang method in ruby its override the existing value.
Let's say I have a list of elements in an array, but there is a logical way to divide them into two groups. I want to put those elements into two smaller arrays based on that criteria. Here is some code that works and helps illustrate what I mean:
foo = ['a', 'bb', 'c', 'ddd', 'ee', 'f']
=> ["a", "bb", "c", "ddd", "ee", "f"]
a = foo.select{|element| element.length == 1}
=> ["a", "c", "f"]
b = foo.reject{|element| element.length == 1}
=> ["bb", "ddd", "ee"]
I seem to remember seeing some way by which a single method call would assign both a and b, but I don't remember what it was. It would look something like
matching, non_matching = foo.mystery_method{|element| element.length == 1}
Am I crazy, or does such a method exist in Ruby and/or Rails?
Yes! http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-partition
matching, non_matching = foo.partition {|element| element.length == 1}
One of my objects ('item') has an ID ('letter_id') in the format of "a", "b", ..., "aa", "ab", etc. To generate it I am using ruby's String#succ in an instance method like this:
def set_letter_id
last = parent.items.all(:order => "letter_id ASC").last
if last.nil?
self.letter_id = 'a'
else
self.letter_id = last.letter_id.succ
end
end
Now this works great until the 28th letter. The 27th will properly generate "aa", but then the value of last will always return the item with the letter_id of 'z' because the ordering of the returned items doesn't follow the same rules as String#succ.
I found this out from a comment over here - but now I'm struggling to find a nice solution around this issue. The problem is basically this:
"aa".succ #=> "ab" - great, that's what I want.
"z"<=>"aa" #=> 1 - not so great, "z" should actually be less than "aa"
Obviously this isn't necessarily a bug, but it makes sorting and ordering a list of letter_ids in this format quite difficult. Has anyone encountered this and found a workaround, or any suggestions that I might try? Thanks!
There was a solution in answers at link you've posted - you have to write own <=> in way to sort_by{|i|[i.length,i]}
irb> %w{a b c z aa ab zz aaa}.shuffle.sort_by { |i| [i.length,i] }
=> ["a", "b", "c", "z", "aa", "ab", "zz", "aaa"]
You can override the <=> method for your Item model to compare first by ID length, then by alphanumeric.
Something like this:
class Item < ActiveRecord::Base
# stuff
def <=>(other)
len_comp = self.letter_id.length <=> other.letter_id.length
return len_comp if len_comp != 0
self.letter_id <=> other.letter_id
end
end
That way you first compare for shorter ID length (i.e., "z" before "aa"), then lexicographically.
This sort of issue is exactly why some people discourage the use of String#succ. It clashes with Range, Object#to_a, and others.
Anyway, you probably know this, but things like this might help...
>> t
=> ["x", "y", "z", "aa", "ab", "ac", "ad", "ae", "af", "ag"]
>> t.shuffle.sort_by { |e| "%3s" % [e] }
=> ["x", "y", "z", "aa", "ab", "ac", "ad", "ae", "af", "ag"]
You could even renormalize this way and dispense with sort_by.