Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #58867

Rosetta: Anagrams/Deranged anagrams (2.)

From "Robert L." <No_spamming@noWhere_7073.org>
Newsgroups comp.lang.forth
Subject Rosetta: Anagrams/Deranged anagrams (2.)
Date 2017-05-08 23:11 +0000
Organization Aioe.org NNTP Server
Message-ID <oeqtvp$ii2$1@gioia.aioe.org> (permalink)

Show all headers | View raw


> 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.
> 
> Task
> 
> Use the word list at unixdict to find and display the longest
> deranged anagram.

(use srfi-69) ; hash-tables
(use srfi-1) ; any
(use combinatorics) ; unordered-subset-fold

(define (sort-chars s) (sort (string->list s) char<?))

(define (deranged? . words)
  (not (apply any eqv? (map string->list words))))

(define table (make-hash-table #:initial '()))

(define (update-table table str)
  (hash-table-update! table (sort-chars str)
    (lambda(lst) (cons str lst))))

(define (find-deranged word-list)
  (unordered-subset-fold
    (lambda(two accum)
      (if (apply deranged? two)
        (cons two accum)
        accum))
    '()
    word-list
    2))

(call-with-input-file "unixdict.txt"
  (lambda (port)
    (port-for-each
      (lambda(line) (update-table table line))
      (lambda() (read-line port)))))

(define (pick words1 words2)
  (cond ((null? words2) words1)
        ((null? words1) words2)
        ((> (string-length (caar words1))
            (string-length (caar words2)))
         words1)
        (else words2)))

(hash-table-fold table
  (lambda (key words result)
    (pick (find-deranged words) result))
  '())

 ===>
(("excitation" "intoxicate"))

In Forth?

-- 
Europe is not going to be the monolithic societies that they once were in the
last century....  They are now going into a multicultural mode.  Jews will be
resented because of our leading role. --- Barbara Spectre
(https://www.youtube.com/watch?v=K0hD7IffTJs)

Back to comp.lang.forth | Previous | Next | Find similar | Unroll thread


Thread

Rosetta: Anagrams/Deranged anagrams (2.) "Robert L." <No_spamming@noWhere_7073.org> - 2017-05-08 23:11 +0000

csiph-web