Exercise 7
June 1, 2018
This must be somebody’s homework:
You are given an input file containing lines with three pipe-separated fields; the first field is a student number (a positive integer), the second field is a class name (a string), and the third field is the grade the student received for the class (a non-negative integer, no greater than 100):
22|Data Structures|45 23|English|52 22|English|51 26|Data Structures|72 23|Data Structures|61 21|English|81You are to output a list of class names along with the grade earned by the lowest-numbers student in each class. For instance, given the above data, the output for Data Structures is 45 corresponding to student 22 (with student number lower than 23 or 26, who also took Data Structures) and the output for English is 81 corresponding to student 21 (with student number lower than 22 or 23, who also took English).
Your task is to write a program to produce the requested output. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here is a hashing-based solution in standard R7RS Scheme and a few
popular SRFIs.
Here’s a solution using Unix utilities.
Output:
Here’s a solution in Python.
Output:
Bash (no Awk) solution.
output:
Data Structures 45
English 81
Clojure.
Output:
Data Structures 45
English 81
Kotlin.
https://pastebin.com/p57zd2qu
A Haskell solution.
Here’s a solution in C.
Example Usage:
Solution in Ruby.
Test Code
Output
target: [["Data Structures", "45"], ["English", "81"]]
output: [["Data Structures", "45"], ["English", "81"]]
pass: ✅
A solution in Racket.
(define (x7 class-records)
(let recurse ((records class-records) (results null))
(if (null? records)
(reverse
(map
(lambda (x) (string-append (cadr x) "|" (number->string (caddr x))))
results))
(let* ((items (string-split (car records) "|"))
(id (string->number (car items)))
(class (cadr items))
(grade (string->number (caddr items)))
(new-result (list id class grade)))
(recurse
(cdr records)
(if (equal? #f (member class (map (lambda (x) (cadr x)) results)))
(cons new-result results)
(map
(lambda (x)
(if
(and (equal? class (cadr x)) (< id (car x)))
new-result
x))
results)))))))
A solution in Mumps