This week’s question:
You’re building a pizza ordering system that enforces strict ingredient layering rules. Given an array of pizza layers (bottom to top) and a set of rules where each rule states that ingredient A must appear somewhere below ingredient B, write a function that determines whether the pizza is valid. If any rule is violated, return the pair [A, B] that was violated first (in the order the rules are given). If the pizza is valid, return true.
Examples:
layers = ["dough", "sauce", "cheese", "pepperoni", "basil"]
rules = [
["sauce", "cheese"],
["cheese", "pepperoni"],
["dough", "basil"],
];
rules2 = [
["cheese", "pepperoni"],
["cheese", "sauce"], # "it's under the sauce"
];
validate_pizza(layers, rules);
=> true
validate_pizza(layers, rules2);
=> ["cheese", "sauce"]
1 Like
Doing this one because it looked easy… (hope the solution is correct
)
Solution
require 'minitest/autorun'
def validate_pizza(layers, rules)
# We should receive "pairs"...
raise "Ratatouille!" if rules.any? { _1.length != 2 }
rules.each do |rule|
rule => [String => ingredient_below, String => ingredient_above]
below_idx = layers.index(ingredient_below)
above_idx = layers.index(ingredient_above)
raise "Invalid rule: #{rule.inspect}" if below_idx.nil? || above_idx.nil?
return rule if below_idx > above_idx
end
true
end
class TestPizza < Minitest::Test
def test_validate_pizza
layers = %w[dough sauce cheese pepperoni basil]
assert(validate_pizza(layers, [
%w[sauce cheese],
%w[cheese pepperoni],
%w[dough basil]
]))
invalid = %w[cheese sauce]
assert_equal(invalid, validate_pizza(layers, [
%w[cheese pepperoni],
%w[cheese sauce]
]))
invalid = %w[basil dough]
assert_equal(invalid, validate_pizza(layers, [
%w[basil dough]
]))
end
end
2 Likes