Skip to content

Instantly share code, notes, and snippets.

@ToJans
Last active April 30, 2018 14:44
Show Gist options
  • Save ToJans/7984691 to your computer and use it in GitHub Desktop.
Save ToJans/7984691 to your computer and use it in GitHub Desktop.
Anagram in golang vs anagram in elixir-lang ; am I missing something obvious here?
using System.IO;
using System;
using System.Linq;
public class Anagram
{
// I am aware about, but have no intention on using
// `string.Equals(a, b, StringComparison.OrdinalIgnoreCase)`
// as that is longer
public static string[] Detect(string subject, string[] Candidates)
{
return Candidates
.Where(x => subject.ToLower() != x.ToLower()
&& Normalize(subject) == Normalize(x))
.ToArray();
}
static string Normalize(string input) {
var chars = input.ToLower().ToCharArray();
Array.Sort(chars);
return new string(chars);
}
}
defmodule Anagram do
def match(subject, candidates) do
candidates
|> Enum.filter(fn x -> normalize_word(subject) == normalize_word(x) end)
|> Enum.filter(fn x -> String.downcase(subject) != String.downcase(x)end)
end
defp normalize_word(word) do
word |> String.downcase |> String.codepoints |> Enum.sort
end
end
package anagram
import (
"sort"
"strings"
)
func Detect(subject string, candidates []string) []string {
result := []string{}
for _, candidate := range candidates {
if normalize(subject) == normalize(candidate) &&
strings.ToLower(subject) != strings.ToLower(candidate) {
result = append(result, strings.ToLower(candidate))
}
}
return result
}
func normalize(subject string) string {
runes := []string{}
for _, Rune := range subject {
runes = append(runes, strings.ToLower(string(Rune)))
}
sort.Strings(runes)
return strings.Join(runes, "")
}
import Data.List (sort)
import Data.Char (toUpper)
anagram :: [Char] -> [[Char]] -> [[Char]]
anagram s cs =
let upCase = map toUpper
normalize = sort . upCase
is_anagram x = normalize s == normalize x && upCase s /= upCase x
in filter is_anagram cs
Copy link

ghost commented Dec 17, 2013

Re the Haskell code, why not use String -> [String] -> [String] instead of [Char] -> [[Char]] -> [[Char]]?

@dimroc
Copy link

dimroc commented Mar 7, 2014

By chance, can we get perf numbers on these?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment