Source: HackerRank > Data Structures > Arrays > Arrays - DS
Description
Print elements of an array in reverse order
Given an array of numeric, character, or string values, print each element in
reverse order as a single line of space-separated elements.
1
2
| [1, 4, 3, 2] ⟹ "2 3 4 1"
["a", "b", "c", "d"] ⟹ "d c b a"
|
My solution
Using reverse
1
2
3
4
| #lang racket
(define (reverse-str lst)
(string-join (map ~a (reverse lst))))
|
Without using reverse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#lang racket
(define (reverse-str lst)
"Given a list, return a string that reverses the list."
(local [
(define (all-but-last lst)
"Return all but the last element of a list."
(take lst (- (length lst) 1)))
(define (stringify elt)
"Convert an element to a string."
(if (number? elt)
(number->string elt)
elt))
(define (reverse-str lst str)
(if (= 1 (length lst))
(string-append (stringify (last lst)) str)
(string-append
(stringify (last lst))
" "
(reverse-str (all-but-last lst) str))))]
(reverse-str lst "")))
(define (print-reverse lst)
(print (reverse-str lst)))
(provide reverse-str)
|
Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
| #lang racket
(require rackunit rackunit/text-ui "print-reverse.rkt")
(define print-reverse-tests
(test-suite "print-reverse-tests"
(test-case "Should return a string with numeric list elements reversed"
(check-equal? (reverse-str '(1 4 3 2)) "2 3 4 1"))
(test-case "Should return a string with string list elements reversed"
(check-equal? (reverse-str '("a" "b" "c" "d")) "d c b a"))
))
(run-tests print-reverse-tests)
|