Skip to content

Instantly share code, notes, and snippets.

@adibfara
Last active October 19, 2023 09:30
Show Gist options
  • Save adibfara/d6272f976f0188d4c83ffd1f1f5a6330 to your computer and use it in GitHub Desktop.
Save adibfara/d6272f976f0188d4c83ffd1f1f5a6330 to your computer and use it in GitHub Desktop.
public interface Item {
void printStructure();
int weight();
}
public record Box(int weight) implements Item {
@Override
public int weight() {
return weight;
}
@Override
public void printStructure() {
System.out.print("*Box");
}
}
public record Container(Item[] items) implements Item {
@Override
public int weight() {
var itemsWeight = Arrays.stream(items).mapToInt(Item::weight).sum();
return 2 + itemsWeight;
}
@Override
public void printStructure() {
System.out.print(" Container[");
for (Item item : items) {
item.printStructure();
}
System.out.print("]");
}
}
public static void main(String[] args) {
var ensemble = new Container(
new Item[]{
new Box(2),
new Container(new Item[]{
new Box(3),
new Box(4)}
)});
ensemble.printStructure();
System.out.println();
System.out.println("Total weight is: " + ensemble.weight());
}
// Container[*Box Container[*Box*Box]]
//Total weight is: 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment