Last active
August 29, 2015 14:24
-
-
Save JFFail/dcdc150d8d6c523b01b1 to your computer and use it in GitHub Desktop.
Solution to Reddit Daily Programmer #222 - Balancing Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# Solution To Reddit Daily Programmer 222 | |
# http://www.reddit.com/r/dailyprogrammer/comments/3c9a9h/20150706_challenge_222_easy_balancing_words/ | |
use warnings; | |
use strict; | |
#Function to balance the word. | |
sub balance { | |
my $input = shift; | |
my $word_len = length($input); | |
#Assign each letter a value. | |
my @letters = qw( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z); | |
#Make an array of the letters. | |
my @split_string = split("", $input); | |
#Make an array of values. | |
my @values = (); | |
foreach my $letter(@split_string) { | |
my $index = 0; | |
while ($letters[$index] ne $letter) { | |
$index++; | |
} | |
push(@values, $index + 1); | |
} | |
#Now calculate the value of each side to find where they're equal. | |
my $left_value = 0; | |
my $right_value = 0; | |
my $position = 0; | |
#Loop through the array of values and compare sides at intervals. | |
for(my $i = 1; $i < $#values; $i++) { | |
$position = $i; | |
$left_value = 0; | |
$right_value = 0; | |
#Determine the left side value. | |
for(my $k = 0; $k < $i; $k++) { | |
$left_value += $values[$k] * ($i - $k); | |
} | |
#Determine the right side value. | |
for(my $k = $i+1; $k <= $#values; $k++) { | |
$right_value += $values[$k] * ($k - $i); | |
} | |
#Break when they're equal. | |
last if ($left_value == $right_value); | |
} | |
#Print the output we need. | |
if($right_value == $left_value) { | |
for(my $i = 0; $i < $position; $i++) { | |
print $split_string[$i]; | |
} | |
print " $split_string[$position] "; | |
for(my $i = $position + 1; $i <= $#values; $i++) { | |
print $split_string[$i]; | |
} | |
print " - $right_value\n"; | |
} else { | |
print "$input DOES NOT BALANCE\n"; | |
} | |
} | |
#Main code. | |
balance("WRONGHEADED"); | |
balance("STEAD"); | |
balance("CONSUBSTANTIATION"); | |
balance("UNINTELLIGIBILITY"); | |
balance("SUPERGLUE"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment