How to resolve the algorithm Anagrams step by step in the Scheme programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Anagrams step by step in the Scheme programming language

Table of Contents

Problem Statement

When two or more words are composed of the same characters, but in a different order, they are called anagrams. Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Anagrams step by step in the Scheme programming language

Source code in the scheme programming language

(import (scheme base)
        (scheme char)
        (scheme file)
        (scheme write)
        (srfi 125)  ; hash tables
        (srfi 132)) ; sorting library

;; read in the words
(define (read-groups)
  (with-input-from-file 
    "unixdict.txt"
    (lambda () 
      (let ((groups (hash-table string=?)))
        (do ((line (read-line) (read-line)))
          ((eof-object? line) groups)
          (let* ((key (list->string (list-sort char<? (string->list line))))
                 (val (hash-table-ref/default groups key '())))
            (hash-table-set! groups key (cons line val))))))))

;; extract the longest values from given hash-table of groups
(define (largest-groups groups)
  (define (find-largest grps n sofar)
    (cond ((null? grps)
           sofar)
          ((> (length (car grps)) n)
           (find-largest (cdr grps) (length (car grps)) (list (car grps))))
          ((= (length (car grps)) n)
           (find-largest (cdr grps) n (cons (car grps) sofar)))
          (else 
            (find-largest (cdr grps) n sofar))))
  (find-largest (hash-table-values groups) 0 '()))

;; print results
(for-each 
  (lambda (group)
    (display "[ ")
    (for-each (lambda (word) (display word) (display " ")) group)
    (display "]\n"))
  (list-sort (lambda (a b) (string<? (car a) (car b)))
             (map (lambda (grp) (list-sort string<? grp))
                  (largest-groups (read-groups)))))

  

You may also check:How to resolve the algorithm Menu step by step in the Java programming language
You may also check:How to resolve the algorithm Almost prime step by step in the Draco programming language
You may also check:How to resolve the algorithm Constrained random points on a circle step by step in the Action! programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Fe programming language
You may also check:How to resolve the algorithm Solve a Hopido puzzle step by step in the AutoHotkey programming language