Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TOuhrouche/4abbc3dae601d4ed13da553cee40f88f to your computer and use it in GitHub Desktop.
Save TOuhrouche/4abbc3dae601d4ed13da553cee40f88f to your computer and use it in GitHub Desktop.
Bundles code review
// 1. return the number of bundle that can be assembled from a list of products
// 2. Bundle is a tree of products with multiple nested levels
// 3. return the count without knowing the number of tree levels (N Stages).
int getBundleCount(List<Product> products, Product bundle) {
Map<String, int> productsListLeaves = {};
for (Product product in products) {
if (productsListLeaves[product.name] == null) {
productsListLeaves[product.name] = 1;
} else {
productsListLeaves[product.name] = productsListLeaves[product.name]! + 1;
}
}
Map<String, int> bundleLeaves = bundle.getLeaves();
int? count;
for (String productType in bundleLeaves.keys) {
int result = productsListLeaves[productType]! ~/ bundleLeaves[productType]!;
if (count == null || result < count) {
count = result;
}
}
return count ?? 0;
}
void main() {
Product piece1 = Product('piece1', {});
Product piece2 = Product('piece2', {});
Product seat = Product('Seat', {piece1: 1, piece2: 1});
Product pedal = Product('Pedal', {});
Product wheel = Product('Wheel', {});
Product bike = Product('Bike', {seat: 1, pedal: 2, wheel: 2});
Product car = Product('Car', {seat: 2, wheel: 4});
// There should be one instance of each product
// Each product holds a quantity field that determines how many units are in stock.
// For example: instead of having multiple wheels, we should have one product named Wheel where Wheel.Quantity = 4.
List<Product> products = [
piece1,
piece2,
pedal,
pedal,
wheel,
wheel,
piece1,
piece2,
pedal,
pedal,
wheel,
wheel,
piece1,
piece2,
piece1,
piece2,
];
print('cars count: ${getBundleCount(products, car)}');
print('bikes count: ${getBundleCount(products, bike)}');
}
class Product {
String name;
Map<Product, int> children;
Product(this.name, this.children);
Map<String, int> getLeaves() {
Map<String, int> leaves = {};
children.forEach((key, value) {
if (key.children.isEmpty) {
leaves[key.name] = value;
} else {
key.getLeaves().forEach((k, v) {
leaves[k] = v * value;
});
}
});
return leaves;
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Product &&
runtimeType == other.runtimeType &&
name == other.name &&
children == other.children;
@override
int get hashCode => name.hashCode ^ children.hashCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment