fork download
  1. ; pearson hashing
  2.  
  3. (define (fold-left op base xs)
  4. (if (null? xs)
  5. base
  6. (fold-left op (op base (car xs)) (cdr xs))))
  7.  
  8. (define (range . args)
  9. (case (length args)
  10. ((1) (range 0 (car args) (if (negative? (car args)) -1 1)))
  11. ((2) (range (car args) (cadr args) (if (< (car args) (cadr args)) 1 -1)))
  12. ((3) (let ((le? (if (negative? (caddr args)) >= <=)))
  13. (let loop ((x(car args)) (xs '()))
  14. (if (le? (cadr args) x)
  15. (reverse xs)
  16. (loop (+ x (caddr args)) (cons x xs))))))
  17. (else (error 'range "unrecognized arguments"))))
  18.  
  19. (define seed 20180525)
  20. (define (random) (set! seed (modulo (* 16807 seed) 2147483647)) seed)
  21. (define (randint n) (floor (* n (random) (/ 2147483647))))
  22.  
  23. (define (shuffle x)
  24. (do ((v (list->vector x)) (n (length x) (- n 1)))
  25. ((zero? n) (vector->list v))
  26. (let* ((r (randint n)) (t (vector-ref v r)))
  27. (vector-set! v r (vector-ref v (- n 1)))
  28. (vector-set! v (- n 1) t))))
  29.  
  30. (define t (list->vector (shuffle (range 256))))
  31.  
  32. (define (pearson8 str)
  33. (fold-left (lambda (n h) (vector-ref t (modulo (+ n h) 256)))
  34. 0 (map char->integer (string->list str))))
  35.  
  36. (define (pearson16 str)
  37. (let* ((cs1 (map char->integer (string->list str)))
  38. (cs2 (cons (modulo (+ (car cs1) 1) 256) (cdr cs1))))
  39. (let loop ((h1 0) (h2 0) (cs1 cs1) (cs2 cs2))
  40. (if (null? cs1) (+ (* h1 256) h2)
  41. (let ((h1 (vector-ref t (modulo (+ (car cs1) h1) 256)))
  42. (h2 (vector-ref t (modulo (+ (car cs2) h2) 256))))
  43. (loop h1 h2 (cdr cs1) (cdr cs2)))))))
  44.  
  45. (display t) (newline)
  46. (display (pearson8 "Programming Praxis")) (newline)
  47. (display (pearson16 "Programming Praxis")) (newline)
Success #stdin #stdout 0.06s 8344KB
stdin
Standard input is empty
stdout
#(228 207 49 43 25 98 39 153 233 115 89 35 50 80 111 14 121 21 148 11 137 71 190 126 91 213 113 243 206 100 250 141 176 248 145 252 177 136 109 224 142 247 75 189 164 211 78 159 93 212 223 151 92 154 45 143 196 156 9 188 22 18 59 251 165 249 157 238 215 90 28 200 117 112 96 147 101 7 242 122 32 4 77 231 106 37 203 57 99 140 110 130 199 31 108 124 65 0 40 88 201 2 174 129 118 172 185 27 120 191 123 186 235 6 81 245 131 216 54 192 135 33 138 53 76 237 70 52 166 193 205 222 146 161 214 103 84 51 204 195 63 152 220 150 218 102 74 56 17 125 30 168 180 241 23 48 66 149 79 234 3 69 175 162 61 12 128 119 171 183 116 197 226 94 16 127 19 107 15 86 236 232 134 36 41 8 10 198 230 167 217 155 47 170 173 67 182 163 26 42 144 181 73 184 169 5 210 225 68 46 58 187 55 60 132 246 38 160 254 227 1 194 179 44 133 62 72 95 255 178 85 244 219 202 209 34 105 29 104 221 239 208 82 229 20 64 87 253 97 13 83 139 114 24 158 240)
192
49404