# RabbitFarm

### 2022-04-17

#### Four is Equilibrium

The examples used here are from The Weekly Challenge problem statement and demonstrate the working solution.

## Part 1

You are given a positive number, \$n < 10. Write a script to generate english text sequence starting with the English cardinal representation of the given number, the word "is" and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue until you reach four.

### Solution

``````
use strict;
use warnings;

my %cardinals = (
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine"
);

sub four_is_magic{
my(\$n, \$s) = @_;
\$s = "" if !\$s;
return \$s .= "four is magic" if \$n == 4;
\$s .= \$cardinals{\$n} . " is " . \$cardinals{length(\$cardinals{\$n})} . ", ";
four_is_magic(length(\$cardinals{\$n}), \$s);
}

MAIN:{
print four_is_magic(5) . "\n";
print four_is_magic(7) . "\n";
print four_is_magic(6) . "\n";
}
``````

### Sample Run

``````
\$ perl perl/ch-1.pl
five is four, four is magic
seven is five, five is four, four is magic
six is three, three is five, five is four, four is magic
``````

### Notes

I was thinking of a clever way I might do this problem. I got nothing! Too much Easter candy perhaps? Anyway, I am not sure there is much tow rite about here as it's an otherwise straightforward use of hashes.

## Part 2

You are give an array of integers, @n. Write a script to find out the Equilibrium Index of the given array, if found.

### Solution

``````
use strict;
use warnings;

sub equilibrium_index{
for my \$i (0 .. @_ - 1){
return \$i if unpack("%32I*", pack("I*",  @_[0 .. \$i])) == unpack("%32I*", pack("I*",  @_[\$i .. @_ - 1]));
}
return -1;
}

MAIN:{
print equilibrium_index(1, 3, 5, 7, 9) . "\n";
print equilibrium_index(1, 2, 3, 4, 5) . "\n";
print equilibrium_index(2, 4, 2) . "\n";
}
``````

### Sample Run

``````
\$ perl perl/ch-2.pl
3
-1
1
``````

### Notes

Like Part 1 above this problem allows for a pretty cut and dry solution. Also, similarly, I can't see a more efficient and/or creative way to solve this one. Maybe I should have just gone for obfuscated then?!?!? In any event, if nothing else, I always like using pack/unpack. I always considered it one of Perl's super powers!

## References

Challenge 160

posted at: 09:59 by: Adam Russell | path: /perl | permanent link to this entry