41 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			41 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
 | 
						|
// parse tree
 | 
						|
$possible_bags = [];
 | 
						|
 | 
						|
$rules = explode("\n", file_get_contents('input.txt'));
 | 
						|
 | 
						|
foreach ($rules as $rule) {
 | 
						|
    [$current_bag, $inside_bags] = explode(' contain ', $rule);
 | 
						|
    $current_bag = substr($current_bag, 0, -5);
 | 
						|
    if ($inside_bags === 'no other bags.') {
 | 
						|
        $possible_bags[$current_bag] = [];
 | 
						|
    } else {
 | 
						|
        $inside_bags = explode(', ', $inside_bags);
 | 
						|
        $parsed_inside_bags = [];
 | 
						|
        foreach ($inside_bags as $inside_bag) {
 | 
						|
            preg_match ('/\d+ (.*) bags?\.?/uU', $inside_bag, $bag);
 | 
						|
            $parsed_inside_bags[] = $bag[1];
 | 
						|
        }
 | 
						|
        $possible_bags[$current_bag] = $parsed_inside_bags;
 | 
						|
    }
 | 
						|
}
 | 
						|
 | 
						|
function has_shiny_in($total_list, $shiny_list = ['shiny gold'])
 | 
						|
{
 | 
						|
    $at_least_one_add = false;
 | 
						|
    foreach ($total_list as $bag => $item) {
 | 
						|
        if (!in_array($bag, $shiny_list, true) && count(array_intersect($shiny_list, $item)) > 0) {
 | 
						|
            $at_least_one_add = true;
 | 
						|
            $shiny_list[] = $bag;
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
    if ($at_least_one_add) {
 | 
						|
        return has_shiny_in($total_list, $shiny_list);
 | 
						|
    }
 | 
						|
 | 
						|
    return $shiny_list;
 | 
						|
}
 | 
						|
 | 
						|
var_dump(has_shiny_in($possible_bags)); |