Homework
July 23, 2019
Today’s exercise comes from somebody’s homework assignment:
Write a program that fills a 50-element array with random numbers from 1 to 10. Print the array. Calculate and print the sum of the random numbers in the array. Calculate and print the number of times that a particular number appears in the array.
Your task is to complete the homework problem described above. 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.
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