user12473575
user12473575

Reputation: 83

How can I transform this code into Racket/ Scheme

This is the code I want translated into Racket:

public static ArrayList<Integer> convert(int k, int n) {
        ArrayList<Integer> lst = new ArrayList<>();
        while (k / n != 0) {
            lst.add(k % n); 
            k = k/n;
        }
        lst.add(k % n);
        return lst; 
    }   

e.g. in Racket the (convert 23 2) should return the binary of the decimal 23, which is (list 1 0 1 1 1).

This is what I got so far:

(define (convert k n)
  (cond 
    [(> (/ k n) 0) (list(modulo k n))]
    [else  0] 
))

It works for the first element of the list.

Thanks for any help!

Upvotes: 1

Views: 838

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Be aware that the / operator in Java performs integer division, so in Racket you'd have to use quotient to obtain the same effect.

This is a good opportunity to use a named let to implement the loop, as the result list needs to be accumulated in reverse. Other than that, the solution is pretty straightforward:

(define (convert k n)
  (let loop ((k k) (acc '()))
    (if (zero? (quotient k n))
        (cons (modulo k n) acc)
        (loop (quotient k n) (cons (modulo k n) acc)))))

For example:

(convert 23 2)
=> '(1 0 1 1 1)

Upvotes: 1

Related Questions