-1

I am new into coding and got interested in Dr. Racket and I am facing my first problem now. I created this code:

(define (collatz n)
  (cond ((= n 1) 1)
        ((> n 1) (collatz_helper n))))

(define (collatz_helper n)
  (if (even? n)
      (collatz (/ n 2))
        (collatz (+ (* 3 n) 1))))


(collatz 100)    ;; >1

Is it possible to store all the intermidiate results in a list or something and then print them out. I mean by intermidiate results n/2 or 3n+1 until we get 1.

For example n=100 (100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1)

Can someone give me a clue or show me how to implement something like this?

nobody
  • 19,814
  • 17
  • 56
  • 77
herbrand
  • 13
  • 3
  • Are you interested in debugging the output? Or do you want to to use the intermediate results for something? – Davin Tryon Oct 09 '17 at 13:52
  • I want to use the intermediate results for something. But first I would like to learn how you store them and then "print" them. What I mean by that: I would like to know what steps exactly the programm took to get to 1. For example for n=100 the output should be (100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1) as a list or something. – herbrand Oct 09 '17 at 14:03
  • for debugging purposes, you can use `display`. In order to keep the results, you need to build a list as you go. – Davin Tryon Oct 09 '17 at 14:20
  • That's my main problem. I want wo creat such a list, but I don't know exactly how. – herbrand Oct 09 '17 at 17:56

1 Answers1

1

First, you can merge your two functions into one, using cond to check all three cases:

(define (collatz n)
  (cond
    ((= n 1) 1)
    ((even? n)
     (collatz (/ n 2)))
    (else
     (collatz (+ (* 3 n) 1)))))

Then, to build the list of intermediate values, you can cons n with each recursive step, creating a list whose first element is the original n and last element is 1 (assuming it terminates):

(define (collatz n)
  (cond
    ((= n 1) '(1))
    ((even? n)
     (cons n (collatz (/ n 2))))
    (else
     (cons n (collatz (+ (* 3 n) 1))))))

For example,

(collatz 100)
=> '(100 50 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1)
assefamaru
  • 2,751
  • 2
  • 10
  • 14