From c70806ca2cc711af94959df301c7c66eb687f381 Mon Sep 17 00:00:00 2001 From: "Jan \"Yenya\" Kasprzak" Date: Wed, 21 Dec 2022 08:20:00 +0100 Subject: [PATCH] Day 21: first ugly eval-based working solution --- 2022/41.pl | 31 +++++++++++++++++++++ 2022/42.pl | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100755 2022/41.pl create mode 100755 2022/42.pl diff --git a/2022/41.pl b/2022/41.pl new file mode 100755 index 0000000..0603f02 --- /dev/null +++ b/2022/41.pl @@ -0,0 +1,31 @@ +#!/usr/bin/perl -w + +use v5.36; +use strict; + +my %names; +my %vals; +while (<>) { + chomp; + my ($name, $rest) = split /:/; + $names{$name} = $rest; + $vals{$name} = 0+$rest if $rest =~ /\A\s*\d+\z/; +} + +while (!defined $vals{root}) { + for my $n (keys %names) { + next if defined $vals{$n}; + my $e = $names{$n}; + my $d = 1; + for my $v (keys %vals) { + $e =~ s/$v/$vals{$v}/g; + } + next if $e =~ /[a-z]/; + say "eval $e"; + eval "\$vals{$n} = $e"; + say "set \$vals{$n} to $vals{$n}" unless $@; + } + say " ================= "; +} + +say $vals{root}; diff --git a/2022/42.pl b/2022/42.pl new file mode 100755 index 0000000..3611405 --- /dev/null +++ b/2022/42.pl @@ -0,0 +1,81 @@ +#!/usr/bin/perl -w + +use v5.36; +use strict; + +undef $SIG{__WARN__}; +my %names; +my %vals; +while (<>) { + chomp; + my ($name, $rest) = split /:/; + $names{$name} = $rest; + $vals{$name} = 0+$rest if $rest =~ /\A\s*\d+\z/; +} + +delete $vals{humn}; +$names{humn} = 'xx'; + +while (!defined $vals{root}) { + my $added; + for my $n (keys %names) { + no warnings; + next if defined $vals{$n}; + my $e = $names{$n}; + my $d = 1; + for my $v (keys %vals) { + $e =~ s/$v/$vals{$v}/g; + $names{$n} = $e; + } + next if $e =~ /[a-z]/; + + eval "\$vals{$n} = $e"; + # say "set \$vals{$n} to $vals{$n}" unless $@; + $added = 1; + } + last if !$added; +} + +for my $n (sort keys %names) { + say "$n = ", defined $vals{$n} ? $vals{$n} : $names{$n}; +} + +my ($val) = $names{root} =~ /(\d+)/; +my ($var) = $names{root} =~ /([a-z]+)/; +while (defined $var) { + say "$var = $val, var = $names{$var}"; + my ($arg1, $op, $arg2) = $names{$var} =~ /(\w+)\s+(\S)\s+(\w+)/; + say "-> $arg1 $op $arg2"; + if ($arg2 =~ /\d/) { + $var = $arg1; + if ($op eq '/') { + $val = $val * $arg2; + } elsif ($op eq '*') { + $val = $val / $arg2; + } elsif ($op eq '+') { + $val = $val - $arg2; + } elsif ($op eq '-') { + $val = $val + $arg2; + } + say "var $var = $val"; + } elsif ($arg1 =~ /\d/) { + $var = $arg2; + if ($op eq '/') { + $val = $arg1 / $val; + } elsif ($op eq '*') { + $val = $val / $arg1; + } elsif ($op eq '+') { + $val = $val - $arg1; + } elsif ($op eq '-') { + $val = $arg1 - $val; + } + say "var $var = $val"; + if ($var eq 'humn') { + $vals{humn} = $val; + last; + } + } else { + last; + } +} +say $vals{humn}; -- 2.43.5