Homework
July 23, 2019
We’ve done this kind of thing before:
Petite Chez Scheme Version 8.4 Copyright (c) 1985-2011 Cadence Research Systems > (define (f n m t) (define (rand n) (inexact->exact (floor (+ (* (random 1.0) n) 1)))) (let ((nums (map rand (make-list n m)))) (display nums) (newline) (display (apply + nums)) (newline) (display (length (filter (lambda (x) (= x t)) nums))) (newline))) > (f 50 10 3) (5 7 3 7 1 8 1 7 1 1 3 10 7 7 2 5 9 8 9 6 9 5 3 4 7 8 7 9 8 10 2 3 9 1 10 6 3 3 1 1 1 7 6 10 4 4 8 1 5 5) 267 6
You can run the program at https://ideone.com/EAgAmB.
Perl “golfy code” originally one liner. Line 1 creates the array – generates the counts for each number and sums them; Line 2 just outputs the data!
Slightly shorter and faster!
[sourcecode lang="perl"]
($t+=$,$X[$]++)foreach@A=map{1+int rand 10}1..50;
say join”\n”,”@A”,$t,map{“$\t$X[$]”}1..10;
[/sourccode]
Slightly shorter and faster!
Klong version (62 characters)
In Python
[5, 5, 6, 5, 9, 6, 2, 11, 8, 7, 4, 9, 3, 10, 11, 2, 1, 7, 4, 7, 1, 6, 4, 7, 5, 9, 3, 3, 9, 10, 10, 5, 5, 4, 2, 4, 4, 8, 8, 9, 7, 3, 11, 5, 1, 9, 4, 1, 7, 9]
295
Counter({5: 7, 9: 7, 4: 7, 7: 6, 3: 4, 1: 4, 6: 3, 2: 3, 11: 3, 8: 3, 10: 3})
Here’s a solution in C.
Example:
Java:
int sum=0;
int [] data = new int[50];
int count [] = new int [10];
Random r =new Random();
for(int i =0;i<50;i++) { data[i] = r.nextInt(10)+1;sum+=data[i]; }
for (int i=0;i< data.length;i++) count[data[i]-1]++;
System.out.println(Arrays.toString(data)+”\nAddition : “+sum+”\n”+Arrays.toString(count));
Actually filling the array is an implementation detail. This observation leads to the optimized version (in pseudo code):
print(275, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5);
@dfijma… what’s your observation?
Klong, version 2