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

  • morrowind@lemmy.ml
    link
    fedilink
    arrow-up
    1
    ·
    11 months ago

    Crystal

    !crystal_lang@lemmy.ml

    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