fork download
  1. (use-modules (ice-9 streams))
  2.  
  3. ; Narayana algorithm, yoba.
  4. (define (permutations first-perm)
  5. (define (next-permutation perm)
  6. (define (split-descending-part items)
  7. (if (or (null? items) (null? (cdr items)))
  8. #f
  9. (let ((parts (split-descending-part (cdr items))))
  10. (cond (parts (cons (cons (car items) (car parts))
  11. (cdr parts)))
  12. ((< (car items) (cadr items))
  13. (list (list (car items))
  14. (car items)
  15. (cdr items)))
  16. (else #f)))))
  17. (define (inject-and-reverse pivot items)
  18. (define (iter new-pivot items tail)
  19. (let ((current-value (car items)))
  20. (if (and (not new-pivot)
  21. (or (null? (cdr items))
  22. (< (cadr items) pivot)))
  23. (begin
  24. (set! new-pivot (car items))
  25. (set! current-value pivot)))
  26. (let ((new-tail (cons current-value tail)))
  27. (if (null? (cdr items))
  28. (cons new-pivot new-tail)
  29. (iter new-pivot (cdr items) new-tail)))))
  30. (iter #f items '()))
  31. (define (combine prefix new-pivot tail)
  32. (if (null? (cdr prefix))
  33. (cons new-pivot tail)
  34. (cons (car prefix)
  35. (combine (cdr prefix) new-pivot tail))))
  36. (let ((parts (split-descending-part perm)))
  37. (if (not parts)
  38. (reverse perm)
  39. (let* ((prefix (car parts))
  40. (pivot (cadr parts))
  41. (tail (caddr parts))
  42. (injection (inject-and-reverse pivot tail))
  43. (new-pivot (car injection))
  44. (new-tail (cdr injection)))
  45. (combine prefix new-pivot new-tail)))))
  46. (make-stream
  47. (lambda (perm)
  48. (cons perm (next-permutation perm)))
  49. first-perm))
  50.  
  51. (define (range begin end)
  52. (if (< begin end)
  53. (cons begin (range (+ begin 1) end))
  54. '()))
  55.  
  56. (define (method-ringing size length player1 player2)
  57. (define (print-permutations count perms)
  58. (if (not (zero? count))
  59. (let ((perm (stream-car perms)))
  60. (for-each
  61. (lambda (x)
  62. (display
  63. (cond ((= x player1) "*")
  64. ((= x player2) "#")
  65. (else " "))))
  66. perm)
  67. (newline)
  68. (print-permutations (- count 1) (stream-cdr perms)))))
  69. (print-permutations length (permutations (range 1 (+ size 1)))))
  70.  
  71. (let* ((size (read))
  72. (length (read)))
  73. (method-ringing size length 2 size))
Success #stdin #stdout 0.03s 4132KB
stdin
5 100
stdout
 *  #
 * # 
 *  #
 * # 
 *#  
 *#  
  * #
  *# 
   *#
   #*
  #* 
  # *
  * #
  *# 
   *#
   #*
  #* 
  # *
 #*  
 #*  
 # * 
 #  *
 # * 
 #  *
*   #
*  # 
*   #
*  # 
* #  
* #  
*   #
*  # 
*   #
*  # 
* #  
* #  
*   #
*  # 
*   #
*  # 
* #  
* #  
*#   
*#   
*#   
*#   
*#   
*#   
  * #
  *# 
   *#
   #*
  #* 
  # *
 *  #
 * # 
 *  #
 * # 
 *#  
 *#  
   *#
   #*
  * #
  *# 
  # *
  #* 
 # * 
 #  *
 #*  
 #*  
 #  *
 # * 
  * #
  *# 
   *#
   #*
  #* 
  # *
 *  #
 * # 
 *  #
 * # 
 *#  
 *#  
   *#
   #*
  * #
  *# 
  # *
  #* 
 # * 
 #  *
 #*  
 #*  
 #  *
 # * 
# *  
# *  
#  * 
#   *