#!/usr/bin/perl use v5.35.0; sub fit_ops { return undef if @_ < 2; my $target = shift; my $rhs = pop; # If target and RHS are all that exist, just compare them return $target == $rhs && '=' unless @_; # Otherwise work out what the partial result of all the # remaining LHS terms would need to be in order to allow # some operator to combine that with the RHS in a way that # would fit. If a workable partial result exists, try fitting # operators to the remaining terms to construct it. # Could multiplication work? if ($rhs == 0) { # When target and RHS are both zero, multiply will # work regardless of which operators go between the # remaining LHS terms; arbitrarily make them all * return '=' . '*' x @_ if $target == 0; } elsif ($target % $rhs == 0) { # Multiply might work if RHS divides target exactly my $ops = fit_ops($target / $rhs, @_); return "$ops*" if $ops; } # Save us, addition, you're our only hope if ($target >= $rhs) { my $ops = fit_ops($target - $rhs, @_); return "$ops+" if $ops; } # No more operators to try return ''; } my $total = 0; while (<>) { my ($test_val, @terms) = split /:?\s+/; my $ops = fit_ops($test_val, @terms); $total += $test_val if $ops; } say $total;