Search code examples
libreoffice-calcanagramlibreoffice-basic

Anagram check in Libreoffice Calc


How can I check in LibreOffice Calc whether two words have the same letters, i. e. are anagrams? Is this doable with the built-in functions?

Edit: My idea is: convert the letters in both words to lower case, sort the letters alphabetically and compare the results. With Python this is easy:

a1 = "Anagram"
b1 = "nagaram"

print("a1 & b1 are anagrams: ", "".join(sorted(a1.lower())) == "".join(sorted(b1.lower())))

But how can I do this with LibreOffice Calc? The function SORT() needs a range or an array. But how can I split a cell value into an array?

At first this seemed to be such a simple task...


Solution

  • So it seems you can't do it with the built-in functions, but as described here, you can create user-defined functions. So I created two functions:

    REM  *****  BASIC  *****
    
    Function SortLetters(a AS String, Optional toLowerCase As Boolean) As String
        GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
        Dim svc : svc = CreateScriptService("Array")
        
        if IsMissing(toLowerCase) then
            toLowerCase = true
        end if
        
        if toLowerCase then
            a = LCase(a)
        end if
        
        Dim letters(Len(a))
        for counter=0 to Len(a)
            letters(counter) = Mid(a, counter+1, 1)
        next
        SortLetters = Join(svc.Sort(letters), "")
        
        svc.Dispose()
    End Function
    
    Function CheckAnagram(a as String, b as String) as Boolean
        CheckAnagram = SortLetters(a, true) = SortLetters(b, true)
    End Function
    

    You can use these functions in a cell with =SortLetters(A1)=SortLetters(B1) or =CheckAnagram(A1;B1). Now it would be really nice if you could create a help for the usage. But an addin would really be too much effort for this little experiment.