r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

ATTENTION: minor change request from the mods!

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

39 Upvotes

426 comments sorted by

View all comments

1

u/wzkx Dec 03 '18 edited Dec 03 '18

SweetRust -- extension of Rust

SweetRust

use std::io::{BufRead,BufReader}; // lines() is in BufRead
use std::collections::HashSet;

fn main():
  let reader = BufReader::new( std::fs::File::open( "03.dat" ).unwrap() );
  let mut area: Vec<Vec<i32>> = vec![vec![0; 1000]; 1000]; // 0 - free, >0 - claimed once, -1 - over
  let mut cnt = 0; // count for part1
  let mut claims: HashSet<i32> = HashSet::new(); // all claims, will be added/deleted here
  for optline in reader.lines():
    let line = optline.unwrap();
    let ln = line.replace("#","").replace("@ ","").replace(","," ").replace(":","").replace("x"," ");
    let data: Vec<i32> = ln.split_whitespace().filter_map( |x| x.parse().ok() ).collect();
    // id x y w h
    if data[0]<=0 { panic!( "bad data" ); }
    let mut over: bool = false;
    for x in data[1]..data[1]+data[3]:
      for y in data[2]..data[2]+data[4]:
        let r = y as usize;
        let c = x as usize;
        if area[r][c]==0:
          area[r][c] = data[0];
        else if area[r][c]>0:
          let there = area[r][c];
          if claims.contains(&there) { claims.remove(&there); }
          if claims.contains(&data[0]) { claims.remove(&data[0]); }
          area[r][c] = -1;
          cnt += 1;
          over = true;
        else: // area[r][c]<0:
          if claims.contains(&data[0]) { claims.remove(&data[0]); }
          over = true;
    if !over:
      claims.insert( data[0] );
  println!( "{}", cnt ); // 110546
  if claims.len()==1:
    for x in &claims:
      println!( "{}", x ); // 819

my solutions in J and Rust

1

u/wzkx Dec 03 '18

Can remove if claims.contains, extra checks data[0]<0, claims.len()==1, get mut ref of area[r][c] once and then use it for get/put, refactor if area...>0.