Task1
We are asked to see if we can return exact change while selling juice for $5 each. The inputs are only of 5,10, and 20 dollars. We check for each one and make our decision:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env perl use strict; use warnings; sub exact_change{ my ($arr) = @_; my %hash; foreach(@$arr){ if($_ == 10){ return 0 unless $hash{5}--; } elsif($_ == 20){ $hash{5} && $hash{10} ? do{--$hash{$_} foreach(5,10)} : $hash{5} > 2 ? $hash{5} -= 3 : return 0; } $hash{$_}++; } 1 } printf "%d\n",exact_change([5,5,5,10,20]); printf "%d\n",exact_change([5,5,10,10,20]); printf "%d\n",exact_change([5,5,5,20]); |
Task2
We are asked to count the loops in the array. To find a loop we start at an index and go to that index's element until we reach that first index again:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env perl use strict; use warnings; sub array_loops{ my ($count,@indices) = (0); foreach my $i(0..$#{$_[0]}){ next if $indices[$i]; $count++; while(!$indices[$i]){ $indices[$i] = 1; $i = $_[0]->[$i]; } } $count } printf "%d\n", array_loops([4,6,3,8,15,0,13,18,7,16,14,19,17,5,11,1,12,2,9,10]); printf "%d\n", array_loops([0,1,13,7,6,8,10,11,2,14,16,4,12,9,17,5,3,18,15,19]); printf "%d\n", array_loops([9,8,3,11,5,7,13,19,12,4,14,10,18,2,16,1,0,15,6,17]); |