Find the missing permutation: Difference between revisions

→‎{{header|Racket}}: Naive method (using new builtin), and better style
(Replaced the two D entries with one, updated)
(→‎{{header|Racket}}: Naive method (using new builtin), and better style)
Line 1,155:
 
=={{header|Racket}}==
<lang racket>#lang racket
#lang racket
 
(define almost-all
'([A B C D] [C A B D] [A C D B] [D A C B] [B C D A] [A C B D] [A D C B]
(map symbol->string '(ABCD CABD ACDB DACB BCDA
[C D A B] [D A B C] [B C A D] [C A D B] [C D B A] [C B A D] [A ACBDB ADCBD CDAB DABCC]
[A D B C] [B D C A] [D C B A] [B A C D] [B A D C] [B D A C] [C BCADB CADBD CDBA CBADA]
[D B C A] [D C A B]))
ABDC ADBC BDCA DCBA
BACD BADC BDAC CBDA
DBCA DCAB)))
 
#| For permutations of any set of characters. |#
(define character-enumeration
(for/hash ([(c i) (in-indexed (first almost-all))])
(values c i)))
(define size (hash-count character-enumeration))
 
;; Obvious method:
(for/first ([p (in-permutations (car almost-all))]
#:unless (member p almost-all))
p)
;; -> '(D B A C)
 
#| Illustrating approach mentioned in the task description.
For each position, character with odd parity at that position. |#
 
#|;; For permutations of any set of characters. |#
(require data/bit-vector)
(define charmap
(for/hash ([(c i)x (in-indexedlist (firstcar almost-all))] [i (in-naturals)])
(values cx i)))
(define size (hash-count character-enumerationcharmap))
 
#|;; Illustrating approach mentioned in the task description.
(list->string
;; For each position, character with odd parity at that position. |#
(for/list ([position size])
 
(define parities (make-bit-vector size false))
(require data/bit-vector)
(for ([permutation almost-all])
(define character-index (hash-ref character-enumeration
(string-ref permutation position)))
(bit-vector-set! parities character-index
(not (bit-vector-ref parities character-index))))
(for/first ([(c i) character-enumeration]
#:when (bit-vector-ref parities i))
c)))
 
(for/list ([positioni (in-range size)])
#;"DBAC"</lang>
(define parities (make-bit-vector size false#f))
(for ([permutation (in-list almost-all)])
(define n (hash-ref charmap (list-ref permutation i)))
(bit-vector-set! parities charactern (not (bit-indexvector-ref parities n))))
(for/first ([(c i) charmap] #:when (bit-vector-ref parities i))
c)))
;; -> '(D B A C)
#;"DBAC"</lang>
 
=={{header|REXX}}==