How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Racket programming language
Table of Contents
Problem Statement
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Use the word list at unixdict to find and display the longest deranged anagram.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Racket programming language
Source code in the racket programming language
#lang racket
(define word-list-file "data/unixdict.txt")
(define (read-words-into-anagram-keyed-hash)
(define (anagram-key word) (sort (string->list word) char<?))
(for/fold ((hsh (hash)))
((word (in-lines)))
(hash-update hsh (anagram-key word) (curry cons word) null)))
(define anagrams-list
(sort
(for/list
((v (in-hash-values
(with-input-from-file
word-list-file
read-words-into-anagram-keyed-hash)))
#:when (> (length v) 1)) v)
> #:key (compose string-length first)))
(define (deranged-anagram-pairs l (acc null))
(define (deranged-anagram-pair? hd tl)
(define (first-underanged-char? hd tl)
(for/first
(((c h) (in-parallel hd tl))
#:when (char=? c h)) c))
(not (first-underanged-char? hd tl)))
(if (null? l) acc
(let ((hd (car l)) (tl (cdr l)))
(deranged-anagram-pairs
tl
(append acc (map (lambda (x) (list hd x))
(filter (curry deranged-anagram-pair? hd) tl)))))))
;; for*/first give the first set of deranged anagrams (as per the RC problem)
;; for*/list gives a full list of the sets of deranged anagrams (which might be interesting)
(for*/first
((anagrams (in-list anagrams-list))
(daps (in-value (deranged-anagram-pairs anagrams)))
#:unless (null? daps))
daps)
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the MANOOL programming language
You may also check:How to resolve the algorithm Flow-control structures step by step in the Tcl programming language
You may also check:How to resolve the algorithm Time a function step by step in the D programming language
You may also check:How to resolve the algorithm N-queens problem step by step in the Visual Basic programming language
You may also check:How to resolve the algorithm Retrieve and search chat history step by step in the Go programming language