Untitled
unknown
d
3 years ago
2.4 kB
8
Indexable
import std.stdio; import std.array; import std.conv; class Stack { private char[] crates; void bottomadd(char crate){ this.crates ~= crate; } void topadd(char crate){ char[] nc = [crate]; this.crates = nc ~= crates; } void topadd(char[] cs){ char[] nc = cs[]; this.crates = nc ~= crates; } char consult(){ return crates[0]; } char[] consultn(int n){ return crates[0..n]; } char pop(){ char crate = consult(); crates = crates[1..$]; return crate; } char[] popn(int n){ char[] crate = consultn(n); crates = crates[n..$]; return crate; } void print(){ foreach (c; crates){ write(c); write(" "); } writeln(); } } class Stacks{ private Stack[] stacks; this(int s){ stacks = new Stack[s]; foreach(i; 0 .. s){ stacks[i] = new Stack(); } } void parse(string line){ for(int i=0; i<9; i++){ char crate_val = line[(i*4)+1]; if(crate_val != ' ' && crate_val > '9'){ assert (crate_val >= 'A' && crate_val <= 'Z'); stacks[i].bottomadd(crate_val); } } } void execute(string command){ auto split = command.split(" "); int amount = to!(int)(split[1]); int source = to!(int)(split[3]); int destination = to!(int)(split[5]); stacks[destination-1].topadd(stacks[source-1].popn(amount)); } char[] get_top_crates(){ char[] top; foreach(stack; stacks){ top ~= stack.consult(); } return top; } void print(){ foreach(s; stacks){ s.print(); } } } void main() { File input = File("../input5", "r"); string line; bool crate_section = true; Stacks stacks = new Stacks(9); while ((line = input.readln()) !is null){ line = line.replace("\n", ""); if (line == ""){ crate_section = false; stacks.print(); continue; } if(crate_section){ stacks.parse(line); }else{ writefln(line); stacks.execute(line); stacks.print(); writeln(); } } writeln(stacks.get_top_crates()); }
Editor is loading...