Skip to content

Instantly share code, notes, and snippets.

@benkasminbullock
Created January 2, 2021 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkasminbullock/79836f8a979f5f2e84d2aa1a8f7b3fea to your computer and use it in GitHub Desktop.
Save benkasminbullock/79836f8a979f5f2e84d2aa1a8f7b3fea to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
# The Weekly Challenge 092
# Task 1
# main idea: hash of arrays
use strict;
use warnings;
use Data::Dumper;
sub learn_pattern {
my %pattern;
my $word = $_[0];
my @alphabet = split //, $word;
my %hash;
my $num_of_diff_symbols = 0;
for (0..$#alphabet) {
if (exists $hash{$alphabet[$_]}) {
push @{$pattern{$hash{$alphabet[$_]}}}, $_;
} else {
$hash{$alphabet[$_]} = $num_of_diff_symbols;
$pattern{$num_of_diff_symbols} = [ $_ ] ;
$num_of_diff_symbols++;
}
}
return %pattern;
}
sub verify_pattern {
my %pattern = %{$_[0]};
my $word = $_[1];
my @alphabet = split //, $word;
my @char = (undef) x length $word;
my @symbol;
my %ehash;
my $num_of_diff_symbols = 0;
for my $alpha (@alphabet) {
if (!exists $ehash{$alpha}) {
$ehash{$alpha} = 1;
$symbol[$num_of_diff_symbols] = $alpha;
$num_of_diff_symbols++;
}
}
for my $order (sort {$a <=> $b} keys %pattern) {
my @p = @{$pattern{$order}};
for (@p) {
$char[$_] = $symbol[$order];
}
}
my $word_two = join "", @char;
return ($word eq $word_two);
}
use Unicode::UTF8 'decode_utf8';
binmode STDOUT, ":encoding(utf8)";
my $l = decode_utf8 ($ARGV[0]);
my $r = decode_utf8 ($ARGV[1]);
print "$l $r\n";
my %h = learn_pattern($l);
if (verify_pattern(\%h,$r)) {
print 1;
} else {
print 0;
}
print "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment