Browse Source

Doing some C learnin'.

Also, reformatted all the problems.
master
Brian Buller 4 years ago
parent
commit
986d17f104
  1. 3
      .gitignore
  2. 42
      2016/day01/day01.rs
  3. 20
      2016/day01/helpers.rs
  4. 15
      2016/day01/input2
  5. 68
      2017/day01/day01.c
  6. 74
      2017/day01/problem
  7. 6
      2017/day02/problem
  8. 4
      2017/day03/problem
  9. 4
      2017/day04/problem
  10. 4
      2017/day05/problem
  11. 91
      2017/day06/problem
  12. 4
      2017/day07/problem
  13. 4
      2017/day08/problem
  14. 4
      2017/day09/problem
  15. 4
      2017/day10/problem
  16. 57
      2017/day11/problem
  17. 4
      2017/day12/problem
  18. 4
      2017/day13/problem
  19. 4
      2017/day14/problem
  20. 476
      2017/day14gui/main.go
  21. 153
      2017/day15/problem
  22. 4
      2017/day16/problem
  23. 4
      2017/day17/problem
  24. 4
      2017/day18/problem
  25. 6
      2017/day19/problem
  26. 4
      2017/day20/problem
  27. 142
      2017/day21/problem
  28. 4
      2017/day22/problem
  29. 82
      2017/day23/problem
  30. 104
      2017/day24/problem
  31. 139
      2017/day25/problem

3
.gitignore

@ -1,3 +1,6 @@
# ---> C
a.out
# ---> Go
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o

42
2016/day01/day01.rs

@ -0,0 +1,42 @@
use std::fmt;
mod helpers;
enum Direction {
North,
East,
South,
West
}
struct Position {
x: i32,
y: i32,
dir: Direction,
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}: {})", self.x, self.y, string_dir(self.dir))
}
}
fn string_dir(d: Direction) -> String {
match d {
Direction::North => String::from("North"),
Direction::East => String::from("East"),
Direction::South => String::from("South"),
Direction::West => String::from("West"),
}
}
fn main() {
let input = helpers::read_std_in();
let split = input.split(",");
for mut s in split {
s = s.trim();
println!("{}", s);
}
let p = Position{ x: 0, y: 0, dir: Direction::North };
println!("{}", p)
}

20
2016/day01/helpers.rs

@ -0,0 +1,20 @@
use std::io;
pub fn read_std_in() -> String {
let mut input = String::new();
let mut done = false;
while !done {
match io::stdin().read_line(&mut input) {
Ok(n) => {
if n == 0 {
done = true;
}
},
Err(error) => {
println!("error: {}", error);
done = true;
},
}
}
input
}

15
2016/day01/input2

@ -0,0 +1,15 @@
R3, L5, R2, L1, L2, R5, L2, R2, L2, L2, L1, R2,
L2, R4, R4, R1, L2, L3, R3, L1, R2, L2, L4, R4,
R5, L3, R3, L3, L3, R4, R5, L3, R3, L5, L1, L2,
R2, L1, R3, R1, L1, R187, L1, R2, R47, L5, L1,
L2, R4, R3, L3, R3, R4, R1, R3, L1, L4, L1, R2,
L1, R4, R5, L1, R77, L5, L4, R3, L2, R4, R5, R5,
L2, L2, R2, R5, L2, R194, R5, L2, R4, L5, L4,
L2, R5, L3, L2, L5, R5, R2, L3, R3, R1, L4, R2,
L1, R5, L1, R5, L1, L1, R3, L1, R5, R2, R5, R5,
L4, L5, L5, L5, R3, L2, L5, L4, R3, R1, R1, R4,
L2, L4, R5, R5, R4, L2, L2, R5, R5, L5, L2, R4,
R4, L4, R1, L3, R1, L1, L1, L1, L4, R5, R4, L4,
L4, R5, R3, L2, L2, R3, R1, R4, L3, R1, L4, R3,
L3, L2, R2, R2, R2, L1, L4, R3, R2, R2, L3, R2,
L3, L2, R4, L2, R3, L4, R5, R4, R1, R5, R3

68
2017/day01/day01.c

@ -0,0 +1,68 @@
#include <stdio.h>
void part1() {
printf("Part 1\n");
int result = 0;
char first = 0, prev, ch;
ch = getchar();
while(ch) {
if(first == 0) { first = ch; }
prev = ch;
ch = getchar();
if(ch == '\n') {
break;
}
if(ch == prev) {
result += prev - '0';
}
}
if(prev == first) {
result += prev - '0';
}
printf("%d\n", result);
}
void part2() {
printf("Part 2\n");
int result = 0;
char first = 0, prev, ch;
ch = getchar();
char* input;
gets
while(ch) {
if(first == 0) { first = ch; }
prev = ch;
ch = getchar();
if(ch == '\n') {
break;
}
if(ch == prev) {
result += prev - '0';
}
}
if(prev == first) {
result += prev - '0';
}
printf("%d\n", result);
}
int main(int argc, char **argv) {
printf("Args: %d\n", argc);
int doPart = 1;
if(argc > 1) { doPart = argv[1][0] - '0'; }
if(doPart == 1) {
part1();
} else {
part2();
}
return 0;
}

74
2017/day01/problem

@ -2,54 +2,78 @@ Advent of Code
--- Day 1: Inverse Captcha ---
The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a few minutes until midnight. "We have
a big problem," she says; "there must be almost fifty bugs in this system, but nothing else can print The List. Stand in this square, quick! There's no time to explain; if you can convince them to pay you in stars, you'll be able
to--" She pulls a lever and the world goes blurry.
When your eyes can focus again, everything seems a lot more pixelated than before. She must have sent you inside the computer! You check the system clock: 25 milliseconds until midnight. With that much time, you should be able to
collect all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day millisecond in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You're standing in a room with "digitization quarantine" written in LEDs along one wall. The only door is locked, but it includes a small interface. "Restricted Area - Strictly No Digitized Users Allowed."
It goes on to explain that you may only leave by solving a captcha to prove you're not a human. Apparently, you only get one millisecond to solve the captcha: too fast for a normal human, but it feels like hours to you.
The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.
The night before Christmas, one of Santa's Elves calls you in a panic. "The
printer's broken! We can't print the Naughty or Nice List!" By the time you
make it to sub-basement 17, there are only a few minutes until midnight. "We
have a big problem," she says; "there must be almost fifty bugs in this
system, but nothing else can print The List. Stand in this square, quick!
There's no time to explain; if you can convince them to pay you in stars,
you'll be able to--" She pulls a lever and the world goes blurry.
When your eyes can focus again, everything seems a lot more pixelated than
before. She must have sent you inside the computer! You check the system
clock: 25 milliseconds until midnight. With that much time, you should be
able to collect all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each
day millisecond in the advent calendar; the second puzzle is unlocked when
you complete the first. Each puzzle grants one star. Good luck!
You're standing in a room with "digitization quarantine" written in LEDs
along one wall. The only door is locked, but it includes a small interface.
"Restricted Area - Strictly No Digitized Users Allowed."
It goes on to explain that you may only leave by solving a captcha to prove
you're not a human. Apparently, you only get one millisecond to solve the
captcha: too fast for a normal human, but it feels like hours to you.
The captcha requires you to review a sequence of digits (your puzzle input)
and find the sum of all digits that match the next digit in the list. The
list is circular, so the digit after the last digit is the first digit in
the list.
For example:
• 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
• 1111 produces 4 because each digit (all 1) matches the next.
• 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the
second digit and the third digit (2) matches the fourth digit.
• 1111 produces 4 because each digit (all 1) matches the next.
• 1234 produces 0 because no digit matches the next.
• 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
• 91212129 produces 9 because the only digit that matches the next one is
the last digit, 9.
What is the solution to your captcha?
Your puzzle answer was ____.
Your puzzle answer was 1144.
--- Part Two ---
You notice a progress bar that jumps to 50% completion. Apparently, the door isn't yet satisfied, but it did emit a star as encouragement. The instructions change:
You notice a progress bar that jumps to 50% completion. Apparently, the door
isn't yet satisfied, but it did emit a star as encouragement. The
instructions change:
Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches
it. Fortunately, your list has an even number of elements.
Now, instead of considering the next digit, it wants you to consider the
digit halfway around the circular list. That is, if your list contains 10
items, only include a digit in your sum if the digit 10/2 = 5 steps forward
matches it. Fortunately, your list has an even number of elements.
For example:
• 1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead.
• 1212 produces 6: the list contains 4 items, and all four digits match
the digit 2 items ahead.
• 1221 produces 0, because every comparison is between a 1 and a 2.
• 123425 produces 4, because both 2s match each other, but no other digit has a match.
• 123425 produces 4, because both 2s match each other, but no other digit
has a match.
• 123123 produces 12.
• 12131415 produces 4.
What is the solution to your new captcha?
Your puzzle answer was ____.
Your puzzle answer was 1194.
Both parts of this puzzle are complete! They provide two gold stars: **
At this point, you should return to your advent calendar and try another puzzle.
At this point, you should return to your advent calendar and try another
puzzle.
If you still want to see it, you can get your puzzle input.

6
2017/day02/problem

@ -29,7 +29,7 @@ Advent of Code
What is the checksum for the spreadsheet in your puzzle input?
Your puzzle answer was ____.
Your puzzle answer was 46402.
The first half of this puzzle is complete! It provides one gold star: *
@ -66,9 +66,7 @@ Advent of Code
Although it hasn't changed, you can still get your puzzle input.
Answer: _____________________
You can also [Shareon Twitter Google+ Reddit] this puzzle.
Answer: 265
References

4
2017/day03/problem

@ -31,7 +31,7 @@ Advent of Code
How many steps are required to carry the data from the square identified in
your puzzle input all the way to the access port?
Your puzzle answer was ____.
Your puzzle answer was 430.
--- Part Two ---
@ -63,7 +63,7 @@ Advent of Code
What is the first value written that is larger than your puzzle input?
Your puzzle answer was _______.
Your puzzle answer was 312453.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day04/problem

@ -21,7 +21,7 @@ Advent of Code
The system's full passphrase list is available as your
puzzle input. How many passphrases are valid?
Your puzzle answer was ____.
Your puzzle answer was 466.
--- Part Two ---
@ -45,7 +45,7 @@ Advent of Code
Under this new system policy, how many passphrases are
valid?
Your puzzle answer was ____.
Your puzzle answer was 251.
Both parts of this puzzle are complete! They provide two
gold stars: **

4
2017/day05/problem

@ -38,7 +38,7 @@ Advent of Code
How many steps does it take to reach the exit?
Your puzzle answer was _______.
Your puzzle answer was 343364.
--- Part Two ---
@ -50,7 +50,7 @@ Advent of Code
How many steps does it now take to reach the exit?
Your puzzle answer was _________.
Your puzzle answer was 25071947.
Both parts of this puzzle are complete! They provide two gold stars: **

91
2017/day06/problem

@ -0,0 +1,91 @@
Advent of Code
--- Day 6: Memory Reallocation ---
A debugger program here is having an issue: it is trying to repair a memory
reallocation routine, but it keeps getting stuck in an infinite loop.
In this area, there are sixteen memory banks; each memory bank can hold any
number of blocks. The goal of the reallocation routine is to balance the
blocks between the memory banks.
The reallocation routine operates in cycles. In each cycle, it finds the
memory bank with the most blocks (ties won by the lowest-numbered memory
bank) and redistributes those blocks among the banks. To do this, it removes
all of the blocks from the selected bank, then moves to the next (by index)
memory bank and inserts one of the blocks. It continues doing this until it
runs out of blocks; if it reaches the last memory bank, it wraps around to
the first one.
The debugger would like to know how many redistributions can be done before
a blocks-in-banks configuration is produced that has been seen before.
For example, imagine a scenario with only four memory banks:
• The banks start with 0, 2, 7, and 0 blocks. The third bank has the most
blocks, so it is chosen for redistribution.
• Starting with the next bank (the fourth bank) and then continuing to the
first bank, the second bank, and so on, the 7 blocks are spread out over
the memory banks. The fourth, first, and second banks get two blocks each,
and the third bank gets one back. The final result looks like this: 2 4 1
2.
• Next, the second bank is chosen because it contains the most blocks
(four). Because there are four memory banks, each gets one block. The
result is: 3 1 2 3.
• Now, there is a tie between the first and fourth memory banks, both of
which have three blocks. The first bank wins the tie, and its three blocks
are distributed evenly over the other three banks, leaving it with none: 0
2 3 4.
• The fourth bank is chosen, and its four blocks are distributed such that
each of the four banks receives one: 1 3 4 1.
• The third bank is chosen, and the same thing happens: 2 4 1 2.
At this point, we've reached a state we've seen before: 2 4 1 2 was already
seen. The infinite loop is detected after the fifth block redistribution
cycle, and so the answer in this example is 5.
Given the initial block counts in your puzzle input, how many redistribution
cycles must be completed before a configuration is produced that has been
seen before?
Your puzzle answer was 12841.
--- Part Two ---
Out of curiosity, the debugger would also like to know the size of the loop:
starting from a state that has already been seen, how many block
redistribution cycles must be performed before that same state is seen
again?
In the example above, 2 4 1 2 is seen again after four cycles, and so the
answer in that example would be 4.
How many cycles are in the infinite loop that arises from the configuration
in your puzzle input?
Your puzzle answer was 8038.
Both parts of this puzzle are complete! They provide two gold stars: **
References
Visible links
. http://adventofcode.com/
. http://adventofcode.com/2017/about
. http://adventofcode.com/2017/support
. http://adventofcode.com/2017/events
. http://adventofcode.com/2017/settings
. http://adventofcode.com/2017/auth/logout
. http://adventofcode.com/2017
. http://adventofcode.com/2017
. http://adventofcode.com/2017/leaderboard
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/6/input

4
2017/day07/problem

@ -67,7 +67,7 @@ Advent of Code
Before you're ready to help them, you need to make sure your information is
correct. What is the name of the bottom program?
Your puzzle answer was ___________.
Your puzzle answer was gynfwly.
--- Part Two ---
@ -100,7 +100,7 @@ Advent of Code
Given that exactly one program is the wrong weight, what would its weight
need to be to balance the entire tower?
Your puzzle answer was ______.
Your puzzle answer was 1526.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day08/problem

@ -25,14 +25,14 @@ Advent of Code
What is the largest value in any register after completing the instructions in your puzzle input?
Your puzzle answer was ____.
Your puzzle answer was 4877.
--- Part Two ---
To be safe, the CPU also needs to know the highest value held in any register during this process so that it can decide how much memory to allocate to these operations. For example, in the above
instructions, the highest value ever held was 10 (in register c after the third instruction was evaluated).
Your puzzle answer was ____.
Your puzzle answer was 5471.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day09/problem

@ -53,7 +53,7 @@ Advent of Code
What is the total score for all groups in your input?
Your puzzle answer was ______.
Your puzzle answer was 10820.
--- Part Two ---
@ -72,7 +72,7 @@ Advent of Code
How many non-canceled characters are within the garbage in your puzzle input?
Your puzzle answer was ______.
Your puzzle answer was 5547.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day10/problem

@ -52,7 +52,7 @@ Advent of Code
However, you should instead use the standard list size of 256 (with values 0 to 255) and the sequence of lengths in your puzzle input. Once this process is
complete, what is the result of multiplying the first two numbers in the list?
Your puzzle answer was ________.
Your puzzle answer was 19591.
--- Part Two ---
@ -99,7 +99,7 @@ Advent of Code
Treating your puzzle input as a string of ASCII characters, what is the Knot Hash of your puzzle input? Ignore any leading or trailing whitespace you might
encounter.
Your puzzle answer was _______________________________________.
Your puzzle answer was 62e2204d2ca4f4924f6e7a80f1288786.
Both parts of this puzzle are complete! They provide two gold stars: **

57
2017/day11/problem

@ -0,0 +1,57 @@
Advent of Code
--- Day 11: Hex Ed ---
Crossing the bridge, you've barely reached the other side of the stream when a program comes up to you, clearly in distress. "It's my child process," she says, "he's gotten lost in an infinite grid!"
Fortunately for her, you have plenty of experience with infinite grids.
Unfortunately for you, it's a hex grid.
The hexagons ("hexes") in this grid are aligned such that adjacent hexes can be found to the north, northeast, southeast, south, southwest, and northwest:
\ n /
nw +--+ ne
/ \
-+ +-
\ /
sw +--+ se
/ s \
You have the path the child process took. Starting where he started, you need to determine the fewest number of steps required to reach him. (A "step" means to move from the hex you are in to any adjacent hex.)
For example:
• ne,ne,ne is 3 steps away.
• ne,ne,sw,sw is 0 steps away (back where you started).
• ne,ne,s,s is 2 steps away (se,se).
• se,sw,se,sw,sw is 3 steps away (s,s,sw).
Your puzzle answer was 747.
--- Part Two ---
How many steps away is the furthest he ever got from his starting position?
Your puzzle answer was 1544.
Both parts of this puzzle are complete! They provide two gold stars: **
References
Visible links
. http://adventofcode.com/
. http://adventofcode.com/2017/about
. http://adventofcode.com/2017/support
. http://adventofcode.com/2017/events
. http://adventofcode.com/2017/settings
. http://adventofcode.com/2017/auth/logout
. http://adventofcode.com/2017
. http://adventofcode.com/2017
. http://adventofcode.com/2017/leaderboard
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. https://en.wikipedia.org/wiki/Hexagonal_tiling
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/11/input

4
2017/day12/problem

@ -42,7 +42,7 @@ Advent of Code
How many programs are in the group that contains program ID 0?
Your puzzle answer was _____.
Your puzzle answer was 378.
The first half of this puzzle is complete! It provides one gold star: *
@ -62,7 +62,7 @@ Advent of Code
Although it hasn't changed, you can still get your puzzle input.
Answer: _____________________
Answer: 204
References

4
2017/day13/problem

@ -184,7 +184,7 @@ Advent of Code
Given the details of the firewall you've recorded, if you leave immediately, what is the severity of
your whole trip?
Your puzzle answer was _______.
Your puzzle answer was 2508.
The first half of this puzzle is complete! It provides one gold star: *
@ -311,7 +311,7 @@ Advent of Code
Although it hasn't changed, you can still get your puzzle input.
Answer: _____________________ [ [Submit] ]
Answer: 3913186
References

4
2017/day14/problem

@ -37,7 +37,7 @@ Advent of Code
Given your actual key string, how many squares are used?
Your puzzle answer was ________.
Your puzzle answer was 8148.
--- Part Two ---
@ -62,7 +62,7 @@ Advent of Code
How many regions are present given your key string?
Your puzzle answer was _____.
Your puzzle answer was 1180.
Both parts of this puzzle are complete! They provide two gold stars: **

476
2017/day14gui/main.go

@ -0,0 +1,476 @@
package main
/* OpenGL & Go Tutorial
* https://kylewbanks.com/blog/tutorial-opengl-with-golang-part-1-hello-opengl
*
* Vertex/Fragment Shader Explanation
* https://www.quora.com/What-is-a-vertex-shader-and-what-is-a-fragment-shader/answer/Harold-Serrano?srid=aVb
*/
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/go-gl/gl/v2.1/gl"
"github.com/go-gl/glfw/v3.1/glfw"
)
// gl_Position = vec4(vp, 1.0);
const (
width = 500
height = 500
vertexShaderSource = `
#version 410
in vec3 vp;
void main() {
gl_Position = vec4(vp, 1.0);
}
` + "\x00"
fragmentShaderSource = `
#version 410
out vec4 frag_colour;
void main() {
frag_colour = vec4(1.0, 1.0, 1.0, 1.0);
}
` + "\x00"
rows = 128
cols = 128
fps = 10
threshold = 0.15
)
var (
square = []float32{
-0.5, 0.5, 0,
-0.5, -0.5, 0,
0.5, -0.5, 0,
-0.5, 0.5, 0,
0.5, 0.5, 0,
0.5, -0.5, 0,
}
)
var diskGrid map[string]bool
var groups map[string]int
var inp string
func init() {
runtime.LockOSThread()
inp = "vbqugkhl" // My puzzle input
if len(os.Args) > 1 {
inp = os.Args[1]
}
}
func main() {
diskGrid = make(map[string]bool)
groups = make(map[string]int)
in := inp
window := initGlfw()
defer glfw.Terminate()
program := initOpenGL()
log.Println("Building DiskGrid...")
var grpCnt int
for i := 0; i < 128; i++ {
row := GetBinaryString(KnotHash(fmt.Sprintf("%s-%d", in, i)))
for j := range row {
diskGrid[cs(i, j)] = (row[j] == '1')
if row[j] == '1' {
groups[cs(i, j)] = grpCnt
grpCnt++
}
}
}
cells := makeCells()
for !window.ShouldClose() {
t := time.Now()
//ReduceGroups()
for x := range cells {
for _, c := range cells[x] {
c.checkState(cells)
}
}
draw(cells, window, program)
time.Sleep(time.Second/time.Duration(fps) - time.Since(t))
}
}
// initGlfw initializes glfw and returns a Window to use.
func initGlfw() *glfw.Window {
if err := glfw.Init(); err != nil {
panic(err)
}
glfw.WindowHint(glfw.Resizable, glfw.False)
glfw.WindowHint(glfw.ContextVersionMajor, 4)
glfw.WindowHint(glfw.ContextVersionMinor, 1)
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
window, err := glfw.CreateWindow(width, height, "Conway's Game of Life", nil, nil)
if err != nil {
panic(err)
}
window.MakeContextCurrent()
return window
}
// initOpenGL initializes OpenGL and returns an initialized program.
func initOpenGL() uint32 {
if err := gl.Init(); err != nil {
panic(err)
}
version := gl.GoStr(gl.GetString(gl.VERSION))
log.Println("OpenGL version", version)
vertexShader, err := compileShader(vertexShaderSource, gl.VERTEX_SHADER)
if err != nil {
panic(err)
}
fragmentShader, err := compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER)
if err != nil {
panic(err)
}
prog := gl.CreateProgram()
gl.AttachShader(prog, vertexShader)
gl.AttachShader(prog, fragmentShader)
gl.LinkProgram(prog)
return prog
}
func draw(cells [][]*cell, window *glfw.Window, program uint32) {
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.UseProgram(program)
for x := range cells {
for _, c := range cells[x] {
c.draw()
}
}
glfw.PollEvents()
window.SwapBuffers()
}
// makeVao initializes and returns a vertex array from the points provided.
func makeVao(points []float32) uint32 {
var vbo uint32
gl.GenBuffers(1, &vbo)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.BufferData(gl.ARRAY_BUFFER, 4*len(points), gl.Ptr(points), gl.STATIC_DRAW)
var vao uint32
gl.GenVertexArrays(1, &vao)
gl.BindVertexArray(vao)
gl.EnableVertexAttribArray(0)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.VertexAttribPointer(0, 3, gl.FLOAT, false, 0, nil)
return vao
}
func compileShader(source string, shaderType uint32) (uint32, error) {
shader := gl.CreateShader(shaderType)
csources, free := gl.Strs(source)
gl.ShaderSource(shader, 1, csources, nil)
free()
gl.CompileShader(shader)
var status int32
gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status)
if status == gl.FALSE {
var logLength int32
gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log))
return 0, fmt.Errorf("failed to compile %v: %v", source, log)
}
return shader, nil
}
func makeCells() [][]*cell {
rand.Seed(time.Now().UnixNano())
cells := make([][]*cell, rows, rows)
for x := 0; x < rows; x++ {
for y := 0; y < cols; y++ {
var gr int
var ok bool
c := newCell(x, y)
if gr, ok = groups[cs(x, y)]; ok {
c.group = gr
}
c.alive = rand.Float64() < threshold
c.aliveNext = c.alive
cells[x] = append(cells[x], c)
}
}
return cells
}
type cell struct {
drawable uint32
alive bool
aliveNext bool
group int
x int
y int
}
func newCell(x, y int) *cell {
points := make([]float32, len(square), len(square))
copy(points, square)
for i := 0; i < len(points); i++ {
var position float32
var size float32
switch i % 3 {
case 0:
size = 1.0 / float32(cols)
position = float32(x) * size
case 1:
size = 1.0 / float32(rows)
position = float32(y) * size
default:
continue
}
if points[i] < 0 {
points[i] = (position * 2) - 1
} else {
points[i] = ((position + size) * 2) - 1
}
}
return &cell{
drawable: makeVao(points),
x: x,
y: y,
group: 0,
}
}
func (c *cell) draw() {
if !c.alive {
return
}
gl.BindVertexArray(c.drawable)
gl.DrawArrays(gl.TRIANGLES, 0, int32(len(square)/3))
}
// checkState determines the state of the cell for the next tick of the game
func (c *cell) checkState(cells [][]*cell) {
c.alive = c.aliveNext
c.aliveNext = c.alive
liveCount := c.liveNeighbors(cells)
if c.alive {
// 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation
if liveCount < 2 {
c.alive = false
}
// 2. Any live cell with two or three live neighbors lives on to the next generation
if liveCount == 2 || liveCount == 3 {
c.aliveNext = true
}
// 3. Any live cell with more than three live neighbors dies, as if by overpopulation
if liveCount > 3 {
c.aliveNext = false
}
} else {
// 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction
if liveCount == 3 {
c.aliveNext = true
}
}
}
// liveNeighbors returns the number of live neighbors for a cell
func (c *cell) liveNeighbors(cells [][]*cell) int {
var liveCount int
add := func(x, y int) {
// If we're at an edge, check the other side of the board.
if x == len(cells) {
x = 0
} else if x == -1 {
x = len(cells) - 1
}
if y == len(cells[x]) {
y = 0
} else if y == -1 {
y = len(cells[x]) - 1
}
if cells[x][y].alive {
liveCount++
}
}
add(c.x-1, c.y) // To the left
add(c.x+1, c.y) // To the right
add(c.x, c.y+1) // Up
add(c.x, c.y-1) // Down
add(c.x-1, c.y+1) // Top-Left
add(c.x+1, c.y+1) // Top-Right
add(c.x-1, c.y-1) // Bottom-Left
add(c.x+1, c.y-1) // Bottom-Right
return liveCount
}
func ReduceGroups() bool {
var ret bool
for x := 0; x < 128; x++ {
for y := 0; y < 128; y++ {
if oV, oOk := diskGrid[cs(x, y)]; oOk && oV {
if dV, dOk := diskGrid[cs(x, y-1)]; dOk && dV && groups[cs(x, y-1)] != groups[cs(x, y)] {
CombineBlockGroups(cs(x, y), cs(x, y-1))
ret = true
}
if dV, dOk := diskGrid[cs(x-1, y)]; dOk && dV && groups[cs(x-1, y)] != groups[cs(x, y)] {
CombineBlockGroups(cs(x, y), cs(x-1, y))
ret = true
}
if dV, dOk := diskGrid[cs(x+1, y)]; dOk && dV && groups[cs(x+1, y)] != groups[cs(x, y)] {
CombineBlockGroups(cs(x+1, y), cs(x, y))
ret = true
}
if dV, dOk := diskGrid[cs(x, y+1)]; dOk && dV && groups[cs(x, y+1)] != groups[cs(x, y)] {
CombineBlockGroups(cs(x, y+1), cs(x, y))
ret = true
}
}
}
}
return ret
}
func CombineBlockGroups(b1, b2 string) {
if groups[b1] < groups[b2] {
groups[b1] = groups[b2]
} else {
groups[b2] = groups[b1]
}
}
// Get a map coordinate string for x, y
func cs(x, y int) string {
return fmt.Sprint(x, "-", y)
}
// Get the x, y coordinate from a string
func sc(c string) (int, int) {
pts := strings.Split(c, "-")
return Atoi(pts[0]), Atoi(pts[1])
}
func KnotHash(in string) string {
var idx, skip int
var list []int
for i := 0; i < 256; i++ {
list = append(list, i)
}
inpBts := []byte(in)
inpBts = append(inpBts, []byte{17, 31, 73, 47, 23}...)
for j := 0; j < 64; j++ {
for i := range inpBts {
idx, skip, list = khRound(int(inpBts[i]), idx, skip, list)
}
}
// Now calculate the dense hash
var dense []byte
for i := 0; i < len(list); i += 16 {
dense = append(dense, xorList(list[i:i+16]))
}
return fmt.Sprintf("%x", dense)
}
func khRound(i, idx, skip int, list []int) (int, int, []int) {
// if idx+i overflows, pull from the front
var revList []int
for j := idx; j < idx+i; j++ {
revList = append([]int{list[j%256]}, revList...)
}
for j := 0; j < len(revList); j++ {
list[(idx+j)%256] = revList[j]
}
idx += i + skip
skip++
return idx, skip, list
}
func xorList(in []int) byte {
var ret byte
for i := range in {
ret ^= byte(in[i])
}
return ret
}
func GetBinaryString(in string) string {
var bin string
for i := range in {
var v int
if in[i] >= '0' && in[i] <= '9' {
v = int(in[i] - '0')
} else if in[i] >= 'a' && in[i] <= 'f' {
v = int(in[i] - 'a' + 10)
}
nibble := fmt.Sprintf("%04s", strconv.FormatInt(int64(v), 2))
bin += nibble
}
return bin
}
func StdinToString() string {
var input string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input = scanner.Text()
}
return input
}
func Atoi(i string) int {
var ret int
var err error
if ret, err = strconv.Atoi(i); err != nil {
log.Fatal("Invalid Atoi")
}
return ret
}

153
2017/day15/problem

@ -0,0 +1,153 @@
Advent of Code
--- Day 15: Dueling Generators ---
Here, you encounter a pair of dueling generators. The generators, called
generator A and generator B, are trying to agree on a sequence of numbers.
However, one of them is malfunctioning, and so the sequences don't always
match.
As they do this, a judge waits for each of them to generate its next value,
compares the lowest 16 bits of both values, and keeps track of the number of
times those parts of the values match.
The generators both work on the same principle. To create its next value, a
generator will take the previous value it produced, multiply it by a factor
(generator A uses 16807; generator B uses 48271), and then keep the
remainder of dividing that resulting product by 2147483647. That final
remainder is the value it produces next.
To calculate each generator's first value, it instead uses a specific
starting value as its "previous value" (as listed in your puzzle input).
For example, suppose that for starting values, generator A uses 65, while
generator B uses 8921. Then, the first five pairs of generated values are:
--Gen. A-- --Gen. B--
1092455 430625591
1181022009 1233683848
245556042 1431495498
1744312007 137874439
1352636452 285222916
In binary, these pairs are (with generator A's value first in each pair):
00000000000100001010101101100111
00011001101010101101001100110111
01000110011001001111011100111001
01001001100010001000010110001000
00001110101000101110001101001010
01010101010100101110001101001010
01100111111110000001011011000111
00001000001101111100110000000111
01010000100111111001100000100100
00010001000000000010100000000100
Here, you can see that the lowest (here, rightmost) 16 bits of the third
value match: 1110001101001010. Because of this one match, after processing
these five pairs, the judge would have added only 1 to its total.
To get a significant sample, the judge would like to consider 40 million
pairs. (In the example above, the judge would eventually find a total of 588
pairs that match in their lowest 16 bits.)
After 40 million pairs, what is the judge's final count?
Your puzzle answer was 626.
--- Part Two ---
In the interest of trying to align a little better, the generators get more
picky about the numbers they actually give to the judge.
They still generate values in the same way, but now they only hand a value
to the judge when it meets their criteria:
• Generator A looks for values that are multiples of 4.
• Generator B looks for values that are multiples of 8.
Each generator functions completely independently: they both go through
values entirely on their own, only occasionally handing an acceptable value
to the judge, and otherwise working through the same sequence of values as
before until they find one.
The judge still waits for each generator to provide it with a value before
comparing them (using the same comparison method as before). It keeps track
of the order it receives values; the first values from each generator are
compared, then the second values from each generator, then the third values,
and so on.
Using the example starting values given above, the generators now produce
the following first five values each:
--Gen. A-- --Gen. B--
1352636452 1233683848
1992081072 862516352
530830436 1159784568
1980017072 1616057672
740335192 412269392
These values have the following corresponding binary values:
01010000100111111001100000100100
01001001100010001000010110001000
01110110101111001011111010110000
00110011011010001111010010000000
00011111101000111101010001100100
01000101001000001110100001111000
01110110000001001010100110110000
01100000010100110001010101001000
00101100001000001001111001011000
00011000100100101011101101010000
Unfortunately, even though this change makes more bits similar on average,
none of these values' lowest 16 bits match. Now, it's not until the 1056th
pair that the judge finds the first match:
--Gen. A-- --Gen. B--
1023762912 896885216
00111101000001010110000111100000
00110101011101010110000111100000
This change makes the generators much slower, and the judge is getting
impatient; it is now only willing to consider 5 million pairs. (Using the
values from the example above, after five million pairs, the judge would
eventually find a total of 309 pairs that match in their lowest 16 bits.)
After 5 million pairs, but using this new generator logic, what is the
judge's final count?
Your puzzle answer was 306.
Both parts of this puzzle are complete! They provide two gold stars: **
At this point, all that is left is for you to admire your advent calendar.
If you still want to see it, you can get your puzzle input.
References
Visible links
. http://adventofcode.com/
. http://adventofcode.com/2017/about
. http://adventofcode.com/2017/support
. http://adventofcode.com/2017/events
. http://adventofcode.com/2017/settings
. http://adventofcode.com/2017/auth/logout
. http://adventofcode.com/2017
. http://adventofcode.com/2017
. http://adventofcode.com/2017/leaderboard
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/15/input

4
2017/day16/problem

@ -30,7 +30,7 @@ Advent of Code
You watch the dance for a while and record their dance moves (your puzzle
input). In what order are the programs standing after their dance?
Your puzzle answer was ________________.
Your puzzle answer was bkgcdefiholnpmja.
--- Part Two ---
@ -50,7 +50,7 @@ Advent of Code
In what order are the programs standing after their billion dances?
Your puzzle answer was ________________.
Your puzzle answer was knmdfoijcbpghlea.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day17/problem

@ -56,7 +56,7 @@ Advent of Code
What is the value after 2017 in your completed circular buffer?
Your puzzle answer was ________.
Your puzzle answer was 1642.
--- Part Two ---
@ -75,7 +75,7 @@ Advent of Code
What is the value after 0 the moment 50000000 is inserted?
Your puzzle answer was _____________.
Your puzzle answer was 301.
Both parts of this puzzle are complete! They provide two gold stars: **

4
2017/day18/problem

@ -44,7 +44,7 @@ Advent of Code
What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value?
Your puzzle answer was _________.
Your puzzle answer was 1187.
--- Part Two ---
@ -80,7 +80,7 @@ Advent of Code
Once both of your programs have terminated (regardless of what caused them to do so), how many times did program 1 send a value?
Your puzzle answer was _______.
Your puzzle answer was 5969.
Both parts of this puzzle are complete! They provide two gold stars: **

6
2017/day19/problem

@ -35,7 +35,7 @@ Advent of Code
would see them) if it follows the path? (The routing diagram is very wide; make sure you view it without line
wrapping.)
Your puzzle answer was __________________.
Your puzzle answer was RUEDAHWKSM.
--- Part Two ---
@ -66,7 +66,7 @@ Advent of Code
How many steps does the packet need to go?
Your puzzle answer was _________.
Your puzzle answer was 17264.
Both parts of this puzzle are complete! They provide two gold stars: **
@ -89,7 +89,5 @@ References
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. https://teespring.com/advent-of-code
. https://teespring.com/advent-of-code-eu
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/19/input

4
2017/day20/problem

@ -54,7 +54,7 @@ Advent of Code
Which particle will stay closest to position <0,0,0> in the
long term?
Your puzzle answer was _______.
Your puzzle answer was 119.
The first half of this puzzle is complete! It provides one
gold star: *
@ -99,7 +99,7 @@ Advent of Code
Although it hasn't changed, you can still get your puzzle
input.
Answer: _____________________
Answer: 471
References

142
2017/day21/problem

@ -0,0 +1,142 @@
Advent of Code
--- Day 21: Fractal Art ---
You find a program trying to generate some art. It uses a strange process
that involves repeatedly enhancing the detail of an image through a set of
rules.
The image consists of a two-dimensional square grid of pixels that are
either on (#) or off (.). The program always begins with this pattern:
.#.
..#
###
Because the pattern is both 3 pixels wide and 3 pixels tall, it is said to
have a size of 3.
Then, the program repeats the following process:
• If the size is evenly divisible by 2, break the pixels up into 2x2
squares, and convert each 2x2 square into a 3x3 square by following the
corresponding enhancement rule.
• Otherwise, the size is evenly divisible by 3; break the pixels up into
3x3 squares, and convert each 3x3 square into a 4x4 square by following
the corresponding enhancement rule.
Because each square of pixels is replaced by a larger one, the image gains
pixels and so its size increases.
The artist's book of enhancement rules is nearby (your puzzle input);
however, it seems to be missing rules. The artist explains that sometimes,
one must rotate or flip the input pattern to find a match. (Never rotate or
flip the output pattern, though.) Each pattern is written concisely: rows
are listed as single units, ordered top-down, and separated by slashes. For
example, the following rules correspond to the adjacent patterns:
../.# = ..
.#
.#.
.#./..#/### = ..#
###
#..#
#..#/..../#..#/.##. = ....
#..#
.##.
When searching for a rule to use, rotate and flip the pattern as necessary.
For example, all of the following patterns match the same rule:
.#. .#. #.. ###
..# #.. #.# ..#
### ### ##. .#.
Suppose the book contained the following two rules:
../.# => ##./#../...
.#./..#/### => #..#/..../..../#..#
As before, the program begins with this pattern:
.#.
..#
###
The size of the grid (3) is not divisible by 2, but it is divisible by 3. It
divides evenly into a single square; the square matches the second rule,
which produces:
#..#
....
....
#..#
The size of this enhanced grid (4) is evenly divisible by 2, so that rule is
used. It divides evenly into four squares:
#.|.#
..|..
--+--
..|..
#.|.#
Each of these squares matches the same rule (../.# => ##./#../...), three of
which require some flipping and rotation to line up with the rule. The
output for the rule is the same in all four cases:
##.|##.
#..|#..
...|...
---+---
##.|##.
#..|#..
...|...
Finally, the squares are joined into a new grid:
##.##.
#..#..
......
##.##.
#..#..
......
Thus, after 2 iterations, the grid contains 12 pixels that are on.
How many pixels stay on after 5 iterations?
Your puzzle answer was 164.
--- Part Two ---
How many pixels stay on after 18 iterations?
Your puzzle answer was 2355110.
Both parts of this puzzle are complete! They provide two gold stars: **
At this point, all that is left is for you to admire your advent calendar.
If you still want to see it, you can get your puzzle input.
References
Visible links
. http://adventofcode.com/
. http://adventofcode.com/2017/about
. http://adventofcode.com/2017/support
. http://adventofcode.com/2017/events
. http://adventofcode.com/2017/settings
. http://adventofcode.com/2017/auth/logout
. http://adventofcode.com/2017
. http://adventofcode.com/2017
. http://adventofcode.com/2017/leaderboard
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/21/input

4
2017/day22/problem

@ -122,7 +122,7 @@ Advent of Code
Given your actual map, after 10000 bursts of activity, how many bursts cause
a node to become infected? (Do not count nodes that begin infected.)
Your puzzle answer was _______.
Your puzzle answer was 5348.
The first half of this puzzle is complete! It provides one gold star: *
@ -241,7 +241,7 @@ Advent of Code
Although it hasn't changed, you can still get your puzzle input.
Answer: _____________________ [ [Submit] ]
Answer: 2512225
References

82
2017/day23/problem

@ -0,0 +1,82 @@
Advent of Code
--- Day 23: Coprocessor Conflagration ---
You decide to head directly to the CPU and fix the printer from there. As
you get close, you find an experimental coprocessor doing so much work that
the local programs are afraid it will halt and catch fire. This would cause
serious issues for the rest of the computer, so you head in and see what you
can do.
The code it's running seems to be a variant of the kind you saw recently on
that tablet. The general functionality seems very similar, but some of the
instructions are different:
• set X Y sets register X to the value of Y.
• sub X Y decreases register X by the value of Y.
• mul X Y sets register X to the result of multiplying the value contained
in register X by the value of Y.
• jnz X Y jumps with an offset of the value of Y, but only if the value of
X is not zero. (An offset of 2 skips the next instruction, an offset of -1
jumps to the previous instruction, and so on.)
Only the instructions listed above are used. The eight registers here,
named a through h, all start at 0.
The coprocessor is currently set to some kind of debug mode, which allows
for testing, but prevents it from doing any meaningful work.
If you run the program (your puzzle input), how many times is the mul
instruction invoked?
Your puzzle answer was 9409.
--- Part Two ---
Now, it's time to fix the problem.
The debug mode switch is wired directly to register a. You flip the switch,
which makes register a now start at 1 when the program is executed.
Immediately, the coprocessor begins to overheat. Whoever wrote this program
obviously didn't choose a very efficient implementation. You'll need to
optimize the program if it has any hope of completing before Santa needs
that printer working.
The coprocessor's ultimate goal is to determine the final value left in
register h once the program completes. Technically, if it had that... it
wouldn't even need to run the program.
After setting register a to 1, if the program were to run to completion,
what value would be left in register h?
Your puzzle answer was 913.
Both parts of this puzzle are complete! They provide two gold stars: **
At this point, all that is left is for you to admire your advent calendar.
If you still want to see it, you can get your puzzle input.
References
Visible links
. http://adventofcode.com/
. http://adventofcode.com/2017/about
. http://adventofcode.com/2017/support
. http://adventofcode.com/2017/events
. http://adventofcode.com/2017/settings
. http://adventofcode.com/2017/auth/logout
. http://adventofcode.com/2017
. http://adventofcode.com/2017
. http://adventofcode.com/2017/leaderboard
. http://adventofcode.com/2017/stats
. http://adventofcode.com/2017/sponsors
. http://adventofcode.com/2017/sponsors
. https://en.wikipedia.org/wiki/Halt_and_Catch_Fire
. http://adventofcode.com/2017/day/18
. http://adventofcode.com/2017
. http://adventofcode.com/2017/day/23/input

104
2017/day24/problem

@ -0,0 +1,104 @@
Advent of Code
--- Day 24: Electromagnetic Moat ---
The CPU itself is a large, black building surrounded by a bottomless pit.
Enormous metal tubes extend outward from the side of the building at regular
intervals and descend down into the void. There's no way to cross, but you
need to get inside.
No way, of course, other than building a bridge out of the magnetic
components strewn about nearby.
Each component has two ports, one on each end. The ports come in all
different types, and only matching types can be connected. You take an