this post was submitted on 11 Dec 2023
10 points (77.8% liked)

Advent Of Code

158 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 11: Cosmic Expansion

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒 Thread is locked until there's at least 100 2 star entries on the global leaderboard

🔓 Unlocked after 9 mins

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 2 points 11 months ago

Crystal

[email protected]

wording in part 2 threw me off too

I could have done this in 2 loops, but this method is way easier to do
And it's gorgeous code imo
(except for the fact that lemmy's huge tab sizes make it look weird)

code

E = ARGV[0].to_i

input = File.read("input.txt")

sky = input.lines.map &.chars

# find galaxies
galaxies = Array(Tuple(Int32, Int32)).new
sky.size.times do |y| 
	sky[0].size.times do |x|
		if sky[y][x] == '#'
			galaxies << {y, x}
end     end     end
# puts galaxies

# vertical expansion locations
expandsy = Array(Int32).new
sky.size.times do |i|
	unless galaxies.any? {|gal| gal[0] == i}
		expandsy << i
end     end

# horizontal expansion locations
expandsx = Array(Int32).new
sky[0].size.times do |i|
	unless galaxies.any? {|gal| gal[1] == i}
		expandsx << i
end     end

# calculate expansion for each galaxy
adds = Array.new(galaxies.size) { [0, 0] }
expandsy.each do |y|
	galaxies.each_with_index do |gal, i|
		if gal[0] > y
			adds[i][0] += 1
end     end     end

# calculate expansion for each galaxy
expandsx.each do |x|
	galaxies.each_with_index do |gal, i|
		if gal[1] > x
			adds[i][1] += 1
end     end     end

# expaaaaaaaand
galaxies.map_with_index! {|gal, i| {gal[0] + adds[i][0]*E, gal[1] + adds[i][1]*E} }

# distances
sum = 0_u64
galaxies.each do |gal|
	galaxies.each do |gal2|
		if gal2 != gal
			sum += (gal2[0] - gal[0]).abs + (gal2[1] - gal[1]).abs
end     end     end
puts sum/2