Created
December 8, 2017 04:00
-
-
Save snarkbait/0cb5652ecd85dbd9c3ca08deda83de42 to your computer and use it in GitHub Desktop.
Advent of Code 2017 Day 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Advent2017; | |
import util.FileIO; | |
import java.util.*; | |
public class Day7 { | |
private static int sumOfChildren(List<Leaf> children) { | |
if (children.size() == 0) return 0; | |
int sum = 0; | |
int target = 0; | |
for (Leaf each : children){ | |
if (each.children.size() == 0) { | |
sum += each.weight; | |
if (target == 0) target = each.weight; | |
} else { | |
int subtotal = sumOfChildren(each.children); | |
each.weightOfChildren = subtotal; | |
subtotal += each.weight; | |
if (target == 0) target = subtotal; | |
sum += subtotal; | |
} | |
} | |
if (sum / children.size() != target) { | |
System.out.println("unbalanced : " + children); | |
System.out.println("Sum :" + sum + " Target :" + target); | |
System.out.println("actual:" + (sum/children.size())); | |
} | |
return sum; | |
} | |
static class Leaf { | |
String name; | |
int weight; | |
int weightOfChildren; | |
Leaf parent; | |
List<Leaf> children; | |
Leaf(String name, int weight){ | |
this.name = name; | |
this.weight = weight; | |
children = new ArrayList<>(); | |
} | |
@Override | |
public String toString() { | |
return "Leaf{" + | |
"name='" + name + '\'' + | |
", weight=" + weight + | |
", children =" + children.size() + | |
", wt of ch:" + weightOfChildren + | |
", sum :" + (weight + weightOfChildren) + | |
'}'; | |
} | |
} | |
public static void main(String[] args) { | |
List<String> input = FileIO.getAOCInputForDay(2017, 7, FileIO.SESSION_ID); | |
Leaf root = null; | |
System.out.println(input.size()); | |
Map<String, Leaf> tree = new HashMap<>(); | |
for (String each : input) { | |
String[] split = each.split(" "); | |
int weight = Integer.parseInt(split[1].replaceAll("[()]", "")); | |
Leaf node = new Leaf(split[0], weight); | |
tree.put(split[0], node); | |
} | |
for (String each : input) { | |
String[] split = each.split(" "); | |
Leaf parent = tree.get(split[0]); | |
if (split.length > 2) { | |
for (int i = 3; i < split.length; i++) { | |
String name = split[i].replaceAll(",", ""); | |
Leaf child = tree.get(name); | |
child.parent = parent; | |
parent.children.add(child); | |
} | |
} | |
} | |
for (Map.Entry each : tree.entrySet()) { | |
Leaf troot = (Leaf) each.getValue(); | |
if (troot.parent == null) { | |
System.out.println(troot.name); | |
root = troot; | |
} | |
} | |
System.out.println(sumOfChildren(root.children)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment