Untitled
unknown
golang
a year ago
2.2 kB
25
Indexable
Never
package main import ( "bufio" "fmt" "math" "os" "strconv" "strings" "unicode" ) type dataMap = map[string]*[]string func main() { f, err := os.Open("./input.txt") if err != nil { panic(err) } defer f.Close() s := bufio.NewScanner(f) crates := &dataMap{} for s.Scan() { line := s.Text() splitLine := strings.Split(line, " ") if splitLine[0] == "move" { crates = parseInstruction(splitLine, crates) } else { crates = parseLayout(line, crates) } } fmt.Println(crates) final := [10]string{} for k, v := range *crates { idx, _ := strconv.Atoi(k) final[idx] = (*v)[len((*v))-1] } fmt.Println(final) } func prepend(arr *[]string, item string) (ret []string) { return append([]string{item}, *arr...) } // creates a map keyed by id with letter array values func parseLayout(line string, crates *dataMap) *dataMap { if line != "" { for i, l := range line { if unicode.IsLetter(l) { crateId := strconv.Itoa(int(math.Floor(float64(i)/4) + 1)) targetContainer := (*crates)[crateId] *targetContainer = prepend((targetContainer), string(l)) } } } return crates } func parseInstruction(line []string, crates *dataMap) *dataMap { amount, _ := strconv.Atoi(line[1]) origin := (*crates)[line[3]] destination := (*crates)[line[5]] for i := 0; i < amount; i++ { moveCrate(origin, destination) } return crates } func moveCrate(origin *[]string, destination *[]string) { lastIdx := len(*origin) - 1 last := (*origin)[lastIdx] *origin = (*origin)[:lastIdx] *destination = append(*destination, last) } // [Q] [B] [H] // [F] [W] [D] [Q] [S] // [D] [C] [N] [S] [G] [F] // [R] [D] [L] [C] [N] [Q] [R] // [V] [W] [L] [M] [P] [S] [M] [M] // [J] [B] [F] [P] [B] [B] [P] [F] [F] // [B] [V] [G] [J] [N] [D] [B] [L] [V] // [D] [P] [R] [W] [H] [R] [Z] [W] [S] // 1 2 3 4 5 6 7 8 9 // move 1 from 4 to 1 // move 2 from 4 to 8 // move 5 from 9 to 6 // move 1 from 1 to 3 // move 5 from 8 to 3 // move 1 from 1 to 5 // move 4 from 3 to 6 // move 14 from 6 to 2