Home > Blockchain >  Finding total number of combinations between flavors and toppings
Finding total number of combinations between flavors and toppings

Time:12-20

I was taking a quiz in Ruby that required me to find the total number of unique combinations between flavors and toppings but I was stuck on a particular part. One of the rules was that "chocolate chip ice cream can't have chocolate chips toppings" or some wording similar to that. This wasn't the exact problem but I tried my best to create a similar problem. How would I go about solving this problem?

def combinations(flavors, toppings)
  
end


flavors = ["fudge", "vanilla", "chocolate chip", "cookie dough"] # 11
toppings = ["chocolate chips", "sprinkles", "mint"]

I first was thinking of doing a nested loop problem but that part that I was stuck on is that "chocolate chip" and "chocolate chips" isn't the same.

CodePudding user response:

Consider an analogous situation. Use #product to find all combinations and then #reject to eliminate the ones that fail to meet the criteria.

In the below example, the second string cannot contain the first one. #index will return nil is the substring is not found.

x = ["a", "b", "c"]
y = ["as", "hello", "world"]

x.product(y).reject { |a, b| b.index(a) }
# => [["a", "hello"], ["a", "world"], ["b", "as"], 
#     ["b", "hello"], ["b", "world"], ["c", "as"], 
#     ["c", "hello"], ["c", "world"]]

CodePudding user response:

I don't want to give it away completely if it is a quiz question, but as always when solving programming problems, a good start is to break it down into smaller steps. I think the following should give you a good hint on how to do it.

  1. Define what it means for two flavours to be the same. Is "chocolate chip" the same as "chocolate chips"? (note the 's' that is different) What about "chocolate" ice cream with "chocolate chips"? One way would be to say that two flavours are equal if one is a substring of the other. Another, slightly harder, way would be to say that they must be exactly the same, normalising away plural forms. Write yourself a function that can take two flavours and give you a true/false answer.

Hint: Check out the docs for the #include? method on String if you go with the first definition and remember that you might not know in advance which string is a substring of the other.

  1. Build a list of all possible pairs when taking one element from each of the two arrays.

Hint: Check out the #product method on Array as mentioned by @jvx8ss.

  1. Remove all pairs where both elements of the pair are equal according to the definition from step 1.

Hint: Check out the #reject method on Array.

All of the relevant docs can be found at https://ruby-doc.org/3.1.3/

  •  Tags:  
  • ruby
  • Related