#!/usr/bin/perl

use v5.30;
use strict;

my %st_move;
my %st_write;
my %st_next;
my $state;
my $val;
my $start_st;
my $sum_steps;
while (<>) {
	if (/Begin in state (\w+)/) {
		$start_st = $1;
	} elsif (/Perform a diagnostic checksum after (\d+) steps/) {
		$sum_steps = $1;
	} elsif (/In state (\w+):/) {
		$state = $1;
	} elsif (/If the current value is (\d):/) {
		$val = $1;
	} elsif (/Write the value (\d)./) {
		$st_write{$state,$val} = $1;
	} elsif (/Move one slot to the (\w+)/) {
		$st_move{$state,$val} = $1 eq 'right' ? 1 : -1;
	} elsif (/Continue with state (\w+)/) {
		$st_next{$state,$val} = $1;
	}
}

my %tape;
my $pos = 0;
while ($sum_steps--) {
	my $val = $tape{$pos} ? 1 : 0;
	$tape{$pos} = $st_write{$start_st,$val};
	$pos += $st_move{$start_st,$val};
	$start_st = $st_next{$start_st,$val};
}

use List::Util qw(sum);
say sum values %tape;
