Skip to content

Commit ad812d7

Browse files
author
Adrian Reimann
committed
solution for day 21 part 1
1 parent 9d3fb8a commit ad812d7

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

day_21/21-1.php

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
3+
//define constants for some fixed values
4+
const WIN_SCORE = 1000;
5+
const MAX_DIE = 100;
6+
const MAX_FIELD = 10;
7+
8+
//read input (just need number after last space of each line for the actual position)
9+
$player_pos = [];
10+
$input = fopen("input.txt", "r");
11+
while (($input_line = fgets($input)) !== false) {
12+
$line = trim($input_line);
13+
14+
$split_str = explode(' ', $line);
15+
$player_pos[] = array_pop($split_str);
16+
}
17+
fclose($input);
18+
19+
//initialise player scores
20+
$player_scores = [];
21+
foreach ($player_pos as $no => $pos) {
22+
$player_scores[$no] = 0;
23+
}
24+
25+
//count die rolls and increase the die value every roll
26+
$die_rolls = 0;
27+
$die_val = 1;
28+
while (max($player_scores) < WIN_SCORE) {
29+
foreach ($player_pos as $no => $pos) {
30+
31+
//increase move with 3 rolls, if the die reaches it max it resets to 1
32+
$move = 0;
33+
for($i = 0; $i < 3; $i++) {
34+
if($die_val > MAX_DIE) {
35+
$die_val = 1;
36+
}
37+
$move += $die_val++;
38+
}
39+
40+
//add the 3 rolls to the counter and move the player
41+
$die_rolls += 3;
42+
$new_pos = $pos + $move;
43+
44+
//decrement new position to 10 or below
45+
while($new_pos > MAX_FIELD) {
46+
$new_pos -= MAX_FIELD;
47+
}
48+
49+
//update player position & score
50+
$player_pos[$no] = $new_pos;
51+
$player_scores[$no] += $new_pos;
52+
53+
//game ends immmediately when a player wins, do not do next player's turn
54+
if($player_scores[$no] >= WIN_SCORE) {
55+
break;
56+
}
57+
}
58+
}
59+
60+
//result
61+
$losing_score = min($player_scores);
62+
$result = $losing_score * $die_rolls;
63+
64+
echo "Losing player's score times dice rolls equals $result." . PHP_EOL;
65+

day_21/input.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Player 1 starting position: 10
2+
Player 2 starting position: 1

day_21/testinput.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Player 1 starting position: 4
2+
Player 2 starting position: 8

0 commit comments

Comments
 (0)