Skip to content

Instantly share code, notes, and snippets.

@piisalie
Last active October 23, 2015 01:25
Show Gist options
  • Save piisalie/c913bdbfcf9211d9f927 to your computer and use it in GitHub Desktop.
Save piisalie/c913bdbfcf9211d9f927 to your computer and use it in GitHub Desktop.
def build_cars(count)
models = { "Ford" => [ "Taurus", "Explorer", "Mustang", ], "Toyota" => [ "Camry", "Highlander" ], "Chevrolet" => [ "HHR", "Camaro"]}
makes = %w[ Ford Toyota Chevrolet ]
colors = %w[ Green Black Red Silver ]
Array.new(count) { build_a_car(makes, models, colors) }
end
def build_a_car(makes, models, colors)
make = makes.sample
model = models[make].sample
color = colors.sample
{ make: make, model: model, year: rand(1990..2015), mileage: rand(1..250_000), color: color }
end
require 'rspec'
cars = [
{ make: "Toyota", model: "Camry", year: 1996, mileage: 201293, color: "Green" },
{ make: "Toyota", model: "Camry", year: 2011, mileage: 11920, color: "Black" },
{ make: "Chevrolet", model: "HHR", year: 2007, mileage: 128743, color: "Sandstone Metallic" },
{ make: "Toyota", model: "Highlander", year: 2009, mileage: 47560, color: "Silver" },
]
def sample(count, list)
makes = list.map { |i| i[:make]}.uniq
models = list.map { |i| i[:model]}.uniq
pairings = makes.product(models).cycle
samples = [ ]
count.times do
make, model = pairings.next
possibility = list.find { |car| car[:make] == make && car[:model] == model }
redo unless possibility
samples << possibility
end
samples
end
describe 'sample' do
it 'returns the correct number' do
sample = sample(3, cars)
expect(sample.count).to eq(3)
end
it 'returns a good distribution of makes' do
cars.permutation.to_a.each do |permutation|
sample = sample(3, permutation)
makes = sample.map { |vehicle| vehicle[:make] }
expect(makes.sort).to eq(["Toyota", "Toyota", "Chevrolet"].sort)
end
end
it 'returns a good distribution of models' do
cars.permutation.to_a.each do |permutation|
sample = sample(3, permutation)
models = sample.map { |vehicle| vehicle[:model] }
expect(models.sort).to eq(["Camry", "Highlander", "HHR"].sort)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment