re: AoC Day 2: Inventory Management System VIEW POST

VIEW FULL DISCUSSION
 

PHP

Ended up learning about a bunch of useful array functions like array_values, array_count_values and array_diff_assoc for this one!

Part 1:

$list = file_get_contents($argv[1]);
$boxes = explode("\n", trim($list));
$twos = 0;
$threes = 0;
foreach ($boxes as $box) {
    $letters = str_split($box);
    $values = array_values(array_count_values($letters));
    if (in_array(2, $values)) {
        $twos++;
    }
    if (in_array(3, $values)) {
        $threes++;
    }
}
echo $twos*$threes;
die(1);

Part 2:

<?php
$list = file_get_contents($argv[1]);
$boxes = explode("\n", rtrim($list));
foreach ($boxes as $i=>$box) {
    if ($i != count($boxes)-1) {
        for ($j = $i+1; $j < count($boxes); $j++) {
            $one = str_split($box);
            $two = str_split($boxes[$j]);
            if (count(array_diff_assoc($one, $two)) == 1) {
                echo join("", array_intersect_assoc($one, $two));
                die(1);
            }
        }
    }
}
code of conduct - report abuse