I'm currently working on an uncrafting tool for minecraft and got a neat output working that shows all the materials needed in a tree. I wonder if the code used to print that tree could be improved somehow. I only have the recursion depth as a measurement and the ArrayList
gets filled in the same order as seen in the input example below. The output format should also stay the same, I'm quite happy with that. The input format is a bit sketchy though, any ideas on that are appreciated as well.
The Algorithm
private static void treeprint(ArrayList<Object[]> tree) { ArrayList<String> stem = new ArrayList<>(); for (int i = 0; i < tree.size() - 1; i++) { System.out.print(String.join("", stem)); Object[] o = tree.get(i); int cdepth = (int) o[0]; String cname = (String) o[1]; int camt = (int) o[2]; int ndepth = (int) tree.get(i + 1)[0]; if (ndepth > cdepth) { if (isLastOfDepth(tree, cdepth, i + 1)) { System.out.print("\\---"); stem.add(" "); } else { System.out.print("+---"); stem.add("| "); } } if (ndepth == cdepth) { if (isLastOfDepth(tree, cdepth, i + 1)) { System.out.print("\\---"); } else { System.out.print("+---"); } } if (ndepth < cdepth) { System.out.print("\\---"); for (int j = 0; j < cdepth - ndepth; j++) { stem.remove(stem.size() - 1); } } System.out.println(cname + " x " + camt); } System.out.println(String.join("", stem) + "\\---" + (String) tree.get(tree.size() - 1)[1] + " x " + (int) tree.get(tree.size() - 1)[2]); } private static boolean isLastOfDepth(ArrayList<Object[]> tree, int depth, int start) { for (int i = start; i < tree.size(); i++) { int cdepth = (int) tree.get(i)[0]; if (cdepth < depth) { return true; } if (cdepth == depth) { return false; } } return true; }
Test Input
Format is recuresion depth / item name / item amount
1 component heat vent 1 2 iron bars 4 3 iron 6 2 heat vent 1 3 electric motor 1 4 coil 2 5 copper cable 8 5 iron 1 4 iron 1 4 tin item casing 2 3 iron bars 4 4 iron 6 3 iron plate 4 2 tin plate 4