Guest User

Untitled

a guest
Apr 23rd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. use v6;
  2.  
  3. my %dictionary;
  4. slurp("big.txt").comb(/<alpha>+/).map({%dictionary{$_.lc}++});
  5.  
  6. sub edits($word) {
  7. my @s = (^$word.chars).map({$word.substr(0, $_), $word.substr($_)});
  8. my @deletes = @s.map(-> $a, $b { $a ~ $b.substr(1); });
  9. my @transposes = @s.map(-> $a, $b { $a ~ $b.substr(0, 2).flip ~ $b.substr(2) if $b.chars > 1 });
  10. my @replaces = @s.map(-> $a, $b {$a ~ ':' ~ $b.substr(1)});
  11. my @inserts = (@s,$word,"").map(-> $a, $b {$a ~ ':' ~ $b});
  12. return (@deletes, @transposes, @replaces, @inserts);
  13. }
  14.  
  15. sub edit_list_to_regex(@el) {
  16. any(@el.uniq>>.subst(':', '<alpha>', :g).map({ rx/ ^ $_ $ / }));
  17. }
  18.  
  19. sub correct($word) {
  20. return $word if (%dictionary{$word});
  21. my $regex = edit_list_to_regex(edits($word));
  22. my @candidates = %dictionary.keys.grep($regex);
  23. if @candidates.elems == 0 {
  24. $regex = edit_list_to_regex(edits($word).map({edits($_)}));
  25. @candidates = %dictionary.keys.grep($regex);
  26. }
  27. return @candidates.max({%dictionary{$_} // 0});
  28. }
  29.  
  30. correct("lary").say;
Add Comment
Please, Sign In to add comment