commit 26: c3993f71575e
parent 25: f732216b9649
branch: default
Bogosort- Scheme implementation
r0...@r00t-box
7 months ago

Changed (Δ1.1 KB):

raw changeset »

bogosort.ss (45 lines added, 0 lines removed)

Up to file-list bogosort.ss:

1
#lang scheme
2
3
;; A implementation of Bogosort(http://en.wikipedia.org/wiki/Bogosort) in Scheme (plt-scheme)
4
;; Uses the "modern" version of Fisher-Yates shuffle for shuffling..(http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm)
5
;;
6
;;
7
;;Amit Saha (http://amitksaha.wordpress.com; amitsaha.in@gmail.com)
8
;;
9
;;
10
;;
11
(define flag 0)
12
13
(define (bogosort to-sort)
14
  (if (eq? #t (sorted? to-sort))
15
    to-sort
16
     (begin
17
      (set! flag 0)
18
      (display to-sort)
19
      (display "\n")
20
      (bogosort (shuffle to-sort)))))
21
22
(define (sorted? to-sort)
23
      (for ((i (in-range (- (vector-length to-sort) 1))))
24
	   (if (> (vector-ref to-sort i) (vector-ref to-sort (+ 1 i)))
25
	     (set! flag 1)
26
	     (set! flag flag)))
27
    (if (eq? 0 flag)
28
      #t
29
      #f))
30
31
32
;; Fisher-Yates shuffle
33
(define (shuffle deck)
34
  (let loop ((n (vector-length deck)) (shuff_deck deck))
35
    (if (<= n 1)
36
      shuff_deck
37
      (begin 
38
	(set! n (- n 1))
39
	(let* ([rand (random (+ 1 n))]
40
	       [tmp (vector-ref shuff_deck rand)]
41
	       )
42
	  (vector-set! shuff_deck rand (vector-ref shuff_deck n))
43
	  (vector-set! shuff_deck n tmp))
44
	(loop n shuff_deck)))))
45