## Homework

### March 20, 2020

I suspect the instructor was thinking of something like this, with one loop:

(define (f1 n) (do ((i 1 (+ i 1))) ((= i (* 2 n))) (display (if (< n i) (- (* 2 n) i) i))) (newline))

The student probably had this in mind, with two loops:

(define (f2 n) (do ((i 1 (+ i 1))) ((= n i)) (display i)) (do ((i n (- i 1))) ((= 0 i)) (display i)) (newline))

Of course, you could use recursion with zero loops:

(define (f3 n) (define (f n s) (if (= n 1) (begin (display s) (newline)) (f (- n 1) (string-append (number->string (- n 1)) s (number->string (- n 1)))))) (f n (number->string n)))

Since the limit on *n* is so small, here is a cheeky solution that has no loops and does no computation:

(define (f4 n) (display (case n ((1) "1") ((2) "121") ((3) "12321") ((4) "1234321") ((5) "123454321") ((6) "12345654321") ((7) "1234567654321") ((8) "123456787654321") ((9) "12345678987654321"))) (newline))

You can run the program at https://ideone.com/aeCJjV.

Nifty little exercise. The single loop makes it more challenging. Here is my take on it using Julia: https://pastebin.com/mqqywQn6

Stay healthy!

Klong version

Here are three simple versions in R7RS Scheme.

Pedantic note: I realize that the solution by @programmingpraxis does

not claim conformance to any specific Scheme standard. However, if

portability or conformance to standard Scheme is desired then I

believe that the integers cannot be handed as-is (e.g., without

conversion to strings) to the display procedure. My reading of R7RS

gives implementations a free hand when displaying objects that are not

strings or chars. In my very quick testing, there is at least one

major implementation that will output a space after ‘display’-ing each

integer.

Output:

Here are a few solutions in Python.

Output:

Here’s a solution in C.

Example:

Another solution in C, with n loop iterations instead of 2n:

def updown(n):

return “”.join([f”{n-abs(n-i)}” for i in range(1, 2*n)])

Python solution:

Main sort function

def sort_ints(n):

total_nums = n*2 – 1

int_list = []

Print result

print(sort_ints(5))

======================

OUTPUT

[1, 2, 3, 4, 5, 4, 3, 2, 1]

VBA Solution: