# Advent of Code 2016, Day 3: Squares with Three Sides

## Part A

On Day 3 we are working with triangles. In our input each line represents a triangle and contains lengths of it’s sides.

``````101 301 501
102 302 502
103 303 503
201 401 601
202 402 602
203 403 603
``````

For triangle the sum of any two sides must be larger than the third side. That’s not the case in our input file and we need to say how many triangles are actually real triangles.

``````data = File.readlines("3.txt").map(&:strip).map { |row| row.split(" ").map(&:to_i).sort }

possible = data.select { |row| row + row > row }

puts possible.size
``````

The key here is to sort the lengths for each triangle and then we can just check if the sum of two shorter side is larger than the third one.

## Part B

In second part we learn that triangles are not specified in lines, but actually vertically. So in the example input lengths are laid out like this:

• first triangle (101, 102, 103)
• second triangle (201, 202, 203)
• and so on

First, we can transpose our input and convert it into one array:

``````data = File.readlines("3.txt").map(&:strip).map { |row| row.split(" ").map(&:to_i) }

transposed = []

3.times do |column|
data.each { |row| transposed.push(row[column]) }
end
``````

Then we iterate over this array, stepping over 3 elements each time. I used simple loop for that and the rest is the same. We sort lengths for each triangle and compare first two sides with the third one.

``````index = 0
count = 0

while index < transposed.size - 2
triangle = transposed[index..(index + 2)].sort

if triangle + triangle > triangle
count += 1
end

index += 3
end

puts count
``````

And here is the full solution:

``````data = File.readlines("3.txt").map(&:strip).map { |row| row.split(" ").map(&:to_i) }

transposed = []

3.times do |column|
data.each { |row| transposed.push(row[column]) }
end

index = 0
count = 0

while index < transposed.size - 2
triangle = transposed[index..(index + 2)].sort

if triangle + triangle > triangle
count += 1
end

index += 3
end

puts count
``````