re: AoC Day 3: No Matter How You Slice It VIEW POST

VIEW FULL DISCUSSION
 

PHP

One of those days when there's a big hint in the name, seems like. The slice/splice functions did the heavy lifting on this one.

Part 1:

<?php
$input = file_get_contents($argv[1]);
$claims = explode("\n", trim($input));
$fabric = array_fill(0, 1000, array_fill(0, 1000, 0));
foreach($claims as $claim) {
  preg_match('/\#[0-9]+ \@ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)/', $claim, $data);
  $x = intval($data[1]);
  $y = intval($data[2]);
  $w = intval($data[3]);
  $h = intval($data[4]);

  for ($i = $y; $i < $y+$h; $i++) {
    $slice = array_slice($fabric[$i], $x, $w);
    $slice = array_map(function($x) {
      return $x+1;
    }, $slice);
    array_splice($fabric[$i], $x, $w, $slice);
  }
}

$twoplus = 0;

foreach ($fabric as $row) {
  $claimcounts = array_count_values($row);
  foreach ($claimcounts as $val=>$count) {
    if ($val >= 2) {
      $twoplus += $count;
    }
  }
}
echo $twoplus;
die(1);

Part 2:

<?php
$input = file_get_contents($argv[1]);
$claims = explode("\n", trim($input));
$fabric = array_fill(0, 1000, array_fill(0, 1000, 0));
foreach($claims as $j=>$claim) {
  preg_match('/\#([0-9]+) \@ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)/', $claim, $data);
  $claims[$j] = $data;
  $c = $data[1];
  $x = intval($data[2]);
  $y = intval($data[3]);
  $w = intval($data[4]);
  $h = intval($data[5]);

  for ($i = $y; $i < $y+$h; $i++) {
    $slice = array_slice($fabric[$i], $x, $w);
    $slice = array_map(function($x) {
      return $x+1;
    }, $slice);
    array_splice($fabric[$i], $x, $w, $slice);
  }
}

foreach ($claims as $claim) {
  $c = $claim[1];
  $x = $claim[2];
  $y = $claim[3];
  $w = $claim[4];
  $h = $claim[5];

  $arr = array();

  for ($i = $y; $i < $y+$h; $i++) {
    $slice = array_slice($fabric[$i], $x, $w);
    array_push($arr, array_product($slice));
  }

  if (array_product($arr) == 1) {
    echo $c;
    break;
  }
}
die(1);
code of conduct - report abuse