Sherlock and Anagrams

  • + 0 comments

    Here's the approch that I implement to solve this problem with Kotlin:

    fun sherlockAndAnagrams(s: String): Int {
        var windowedSize = s.length - 1 // define possible windowed steps for that string
        var listOfWindows : List<List<Char>> = listOf()
        var anagramsCounter = 0
        
        // itterate based on possible windowed steps
        while(windowedSize > 0){
            // get all windowed sets
            listOfWindows = s.toList().windowed(size = windowedSize, step = 1) { it ->
                it.sortedBy { it }
            }
            // count all anagrams
            listOfWindows.forEachIndexed{ index, window ->
                for(j in (index + 1) .. listOfWindows.lastIndex) {
                    if(window == listOfWindows[j])  
                        anagramsCounter++
                }
            }
            windowedSize-- // reduce the windowed size
        }
        return anagramsCounter
    }