# # optimal way to multiply a chain of matrices # the algorithm seeks to always collapse the higher factor # by canceling it in between the multiplications. # my @items = $*IN.get.comb(/\d+/); exit say "Input must consist of at least two integers." unless @items > 1; my @matrix = 'A' X~ 1 .. @items-1; while @matrix > 1 { my $i = max { @items[$^a] > @items[$^b] }, 1 .. @items-2; @items.splice($i,1); @matrix.splice($i-1,2,'('~@matrix[$i-1]~@matrix[$i]~')'); } say @matrix[0];