Browse Source

Finit le 4eme jour

main
Clément 11 months ago
parent
commit
22e1882391
  1. 13
      day_4/part_1.php
  2. 13
      day_4/part_2.php
  3. 108
      day_4/passport.php

13
day_4/part_1.php

@ -0,0 +1,13 @@
<?php
include 'passport.php';
$passports = explode("\n\n", file_get_contents('input.txt'));
$number_of_valid_passports = 0;
foreach ($passports as $passport) {
$passport_o = Passport::fromInput($passport);
$number_of_valid_passports += ($passport_o->isValid()) ? 1 : 0;
}
var_dump($number_of_valid_passports);

13
day_4/part_2.php

@ -0,0 +1,13 @@
<?php
include 'passport.php';
$passports = explode("\n\n", file_get_contents('input.txt'));
$number_of_valid_passports = 0;
foreach ($passports as $passport) {
$passport_o = Passport::fromInput($passport);
$number_of_valid_passports += ($passport_o->isReallyValid()) ? 1 : 0;
}
var_dump($number_of_valid_passports);

108
day_4/passport.php

@ -0,0 +1,108 @@
<?php
class Passport
{
public $byr; // (Birth Year)
public $iyr; // (Issue Year)
public $eyr; // (Expiration Year)
public $hgt; // (Height)
public $hcl; // (Hair Color)
public $ecl; // (Eye Color)
public $pid; // (Passport ID)
public $cid; // (Country ID)
public static function fromInput($input)
{
$fields = preg_split('/\s+/', $input);
$new_passport = new self();
foreach ($fields as $field_data) {
[$field, $data] = explode(':', $field_data);
$new_passport->{$field} = $data;
}
return $new_passport;
}
public function validateByr()
{
return !empty($this->byr) &&
is_numeric($this->byr) &&
$this->byr >= 1920 && $this->byr <= 2002;
}
public function validateIyr()
{
return !empty($this->iyr) &&
is_numeric($this->iyr) &&
$this->iyr >= 2010 && $this->iyr <= 2020;
}
public function validateEyr()
{
return !empty($this->eyr) &&
is_numeric($this->eyr) &&
$this->eyr >= 2020 && $this->eyr <= 2030;
}
public function validateHgt()
{
$value = substr($this->hgt, 0, -2);
$unit = substr($this->hgt, -2);
return !empty($this->hgt) &&
in_array($unit, ['in','cm']) &&
($unit === 'cm' ? $value >= 150 && $value <= 193 : $value >= 59 && $value <= 76)
;
}
public function validateHcl()
{
return 1 === preg_match('/^#[0-9a-f]{6}$/', $this->hcl);
}
public function validateEcl()
{
return in_array($this->ecl, ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'], true);
}
public function validatePid()
{
return 1 === preg_match('/^\d{9}$/', $this->pid);
}
public function validateCid()
{
return true;
}
public function isReallyValid()
{
if (!$this->isValid()) {
// echo sprintf("invalide basiquement\n");
return false;
}
$vars = get_object_vars($this);
foreach ($vars as $var_name => $var_value) {
$method = sprintf('validate%s', ucfirst($var_name));
if (!$this->{$method}()) {
return false;
}
}
return true;
}
public function isValid()
{
return
!empty($this->byr) &&
!empty($this->iyr) &&
!empty($this->eyr) &&
!empty($this->hgt) &&
!empty($this->hcl) &&
!empty($this->ecl) &&
!empty($this->pid);
}
}
Loading…
Cancel
Save