Advent of code Day 3

Goal: List possible triangles in an array of numbers

Ref: http://adventofcode.com/2016/day/3


In [1]:
data <- read.table("data.txt") #Using dataframe to align data
str(data)


'data.frame':	1911 obs. of  3 variables:
 $ V1: int  541 827 660 39 229 237 898 101 813 603 ...
 $ V2: int  588 272 514 703 871 956 566 79 541 135 ...
 $ V3: int  421 126 367 839 3 841 112 112 146 565 ...

In [2]:
data$possible <- apply(data, 1, function(x) {t <- sort(x); (t[1]+t[2]) > t[3]}) #Creating new column with the possible value

For Q2 we recreate a new dataframe to work with rows like in Q1. To do so we use to original colum to create a new matrix


In [3]:
data2 <- data.frame(do.call(rbind, lapply(data[,1:3], matrix, ncol = 3, byrow=T)))
str(data2)


'data.frame':	1911 obs. of  3 variables:
 $ X1: int  541 39 898 603 545 370 656 504 197 604 ...
 $ X2: int  827 229 101 335 657 101 634 760 357 90 ...
 $ X3: int  660 237 813 382 823 295 819 733 544 609 ...

In [4]:
data2$possible <- apply(data2, 1, function(x) {t <- sort(x); (t[1]+t[2]) > t[3]})

In [5]:
cat("Q1 - The number of possible triangles by row is: ", sum(data$possible), '\n')
cat("Q2 - The number of possible triangles by column is: ", sum(data2$possible), '\n')


Q1 - The number of possible triangles by row is:  993 
Q2 - The number of possible triangles by column is:  1849