code_junkie

Do you know how to write this Scheme function?

Nov 12th, 2011
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. inline unsigned int step(unsigned int i)
  2. {
  3. return (i&0x1)*(i*3+1)+((i+1)&0x1)*(i>>1);
  4. }
  5.  
  6. unsigned int collatz(unsigned int i)
  7. {
  8. unsigned int cur = i;
  9. unsigned steps = 0;
  10. while((cur=step(cur))!=1) steps++;
  11. return steps;
  12. }
  13.  
  14. (define (listfrom a b)
  15. (if (= a b)
  16. (cons a empty)
  17. (cons a (listfrom (+ 1 a) b))))
  18.  
  19. (define (max-collatz a b)
  20. (foldl max 0 (map collatz-loop (listfrom a b))))
  21.  
  22. (define (max-collatz-num a b)
  23. (foldl (lambda (c r)
  24. (if (> (collatz-loop c) (collatz-loop r)) c r))
  25. a
  26. (listfrom a b)))
  27.  
  28. (define (collatz x)
  29. (if (even? x)
  30. (/ x 2)
  31. (+ (* x 3) 1)))
  32.  
  33. (define (collatz-loop x)
  34. (if (= x 1) 1
  35. (+ (collatz-loop (collatz x)) 1)))
  36.  
  37. (define (collatz-loop x)
  38. (define (internal x counter)
  39. (if (= x 1) counter
  40. (internal (collatz x) (+ counter 1))))
  41. (internal x 1))
  42.  
  43. (define (collatz-range a b)
  44. (if (= a b)
  45. (cons a (collatz-loop a))
  46. (let ((this (collatz-loop a))
  47. (rest (collatz-range (+ a 1) b)))
  48. (if (< this (cdr rest)) rest
  49. (cons a this)))))
  50.  
  51. (collatz-range 1 20) ; returns (18 . 21), which means that (collatz-loop 18) returns 21
  52.  
  53. (define (collatz-range a b)
  54. (define (internal a best)
  55. (if (< b a) best
  56. (internal (+ a 1)
  57. (let ((x (collatz-loop a)))
  58. (if (< x (cdr best))
  59. best
  60. (cons a x))))))
  61. (internal a (cons -1 -1)))
Add Comment
Please, Sign In to add comment