How to resolve the algorithm Find the missing permutation step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Find the missing permutation step by step in the Racket programming language
Table of Contents
Problem Statement
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Find that missing permutation.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Find the missing permutation step by step in the Racket programming language
Source code in the racket programming language
#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]
[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 B D C]
[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 B D A]
[D B C A] [D C A B]))
;; Obvious method:
(for/first ([p (in-permutations (car almost-all))]
#:unless (member p almost-all))
p)
;; -> '(D B A C)
;; For permutations of any set
(define charmap
(for/hash ([x (in-list (car almost-all))] [i (in-naturals)])
(values x i)))
(define size (hash-count charmap))
;; Illustrating approach mentioned in the task description.
;; For each position, character with odd parity at that position.
(require data/bit-vector)
(for/list ([i (in-range size)])
(define parities (make-bit-vector size #f))
(for ([permutation (in-list almost-all)])
(define n (hash-ref charmap (list-ref permutation i)))
(bit-vector-set! parities n (not (bit-vector-ref parities n))))
(for/first ([(c i) charmap] #:when (bit-vector-ref parities i))
c))
;; -> '(D B A C)
You may also check:How to resolve the algorithm Vector products step by step in the Action! programming language
You may also check:How to resolve the algorithm Empty directory step by step in the Ruby programming language
You may also check:How to resolve the algorithm Copy stdin to stdout step by step in the Ada programming language
You may also check:How to resolve the algorithm Create a file step by step in the Scala programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the Go programming language