re: AoC Day 5: Alchemical Reduction VIEW POST

VIEW FULL DISCUSSION
 

PHP

Second part looks kind of long because I figured it would be faster to just declare the letters rather than generate the letters programmatically. I'm pretty sure there's a way to improve performance here, since this has a long-ish runtime, but I wasn't up to optimizing performance at midnight, haha. I might fiddle with this some more to see if I can do better.

Part 1:

<?php
$polymer = str_split(trim(file_get_contents($argv[1])));
do {
  $destruction = false;
  for ($i = 0; $i < count($polymer)-1; $i++) {
    $val = $polymer[$i];
    $next = $polymer[$i+1];
    if (($val == strtoupper($next) && strtoupper($next) != $next) || ($val == strtolower($next) && strtolower($next) != $next)) {
      $destruction = true;
      array_splice($polymer, $i, 2);
      break;
    }
  }
} while ($destruction);
echo count($polymer);
die(1);

Part 2:

<?php
$basepolymer = str_split(trim(file_get_contents($argv[1])));
$polymer = $basepolymer;
$shortest;
$units = array(
  array('a', 'A'),
  array('b', 'B'),
  array('c', 'C'),
  array('d', 'D'),
  array('e', 'E'),
  array('f', 'F'),
  array('g', 'G'),
  array('h', 'H'),
  array('i', 'I'),
  array('j', 'J'),
  array('k', 'K'),
  array('l', 'L'),
  array('m', 'M'),
  array('n', 'N'),
  array('o', 'O'),
  array('p', 'P'),
  array('q', 'Q'),
  array('r', 'R'),
  array('s', 'S'),
  array('t', 'T'),
  array('u', 'U'),
  array('v', 'V'),
  array('w', 'W'),
  array('x', 'X'),
  array('y', 'Y'),
  array('z', 'Z')
);
foreach ($units as $unit) {
  $polymer = array_filter($polymer, function($c) {
    global $unit;
    if (in_array($c, $unit)) {
      return false;
    }
    return true;
  });
  do {
    $destruction = false;
    for ($i = 0; $i < count($polymer)-1; $i++) {
      $val = $polymer[$i];
      $next = $polymer[$i+1];
      if (($val == strtoupper($next) && strtoupper($next) != $next) || ($val == strtolower($next) && strtolower($next) != $next)) {
        $destruction = true;
        array_splice($polymer, $i, 2);
        break;
      }
    }
  } while ($destruction);
  if (!$shortest || count($polymer) < $shortest) {
    $shortest = count($polymer);
  }
  echo $shortest;
  $polymer = $basepolymer;
}

echo $shortest;
die(1);
code of conduct - report abuse