;;; -*- lexical-binding: t -*- ;; ;; this file: ;; https://dataswamp.org/~incal/emacs-init/perm.el (require 'cl-lib) (require 'spell) ;; Christoph Conrad @ https://www.emacswiki.org/emacs/StringPermutations (defun perms (l) (if l (cl-mapcan (lambda (a) (cl-mapcan (lambda (p) (list (cons a p))) (perms (cl-remove a l :count 1)) )) l) '(()) )) (defun string-perms (str) (let*((chars (string-to-list str)) (char-perms (perms chars)) ) (mapcar (lambda (a) (concat a) ) char-perms) )) ;; (string-perms "hte") ; ("hte" "het" "the" "teh" "eht" "eth") (defun string-perms-filter (str) (let ((strs (cl-remove-duplicates (cl-remove-if-not (lambda (w) (spell-word w)) (string-perms str)) :test #'string=) )) (if (= 1 (length strs)) (car strs) strs) )) ;; eht kudtce pigelsen tagni ogod seot erontuf si ni fo hte ;; ;; (string-perms-filter "ogod") ; good ;; (string-perms-filter "erontuf") ; fortune ;; (string-perms-filter "si") ; is ;; (string-perms-filter "kudtce") ; tucked ;; (string-perms-filter "ni") ; in ;; (string-perms-filter "eth") ; the ;; (string-perms-filter "seot") ; toes ;; (string-perms-filter "fo") ; of ;; (string-perms-filter "hte") ; the ;; (string-perms-filter "pigelsen") ; ("peelings" "sleeping") ;; (string-perms-filter "tagni") ; giant ;; (string-perms-filter "emacs") (defun factorial (n) (if (> n 1) (* n (factorial (1- n))) 1)) ;; (factorial 5) ; 120 ;; (factorial 10) ; 3 628 800 ;; (factorial (* 3 3)) (defun cl-factorial (n) (cl-loop with prod = 1 for i from 2 to n do (setq prod (* i prod)) finally return prod) ) ;; (cl-factorial 5) ; 120 ;; (cl-factorial 10) ; 3 628 800 (defun product-string (str) (let*((str-list (string-to-list str)) (str-list-no-dups (cl-remove-duplicates str-list)) (prod 1) ) (dolist (e str-list-no-dups) (setq prod (* prod (cl-factorial (cl-count e str-list)))) ) prod )) ;; (product-string "ogod") ; 2 (defun perms-string-num (str) (let ((n (cl-factorial (length str))) (r (product-string str)) ) (/ n r) )) ;; (perms-string-num "ogod") ; 12 ;; (perms-string-num "kudtce") ; 720 (provide 'perm)