forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHistogram.java
More file actions
79 lines (69 loc) · 2.17 KB
/
Histogram.java
File metadata and controls
79 lines (69 loc) · 2.17 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.Random;
/**
* Example code related to histograms.
*/
public class Histogram {
/**
* Returns an array of random integers.
*/
public static int[] randomArray(int size) {
Random random = new Random();
int[] a = new int[size];
for (int i = 0; i < a.length; i++) {
a[i] = random.nextInt(100);
}
return a;
}
/**
* Computes the number of array elements in [low, high).
*/
public static int inRange(int[] a, int low, int high) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] >= low && a[i] < high) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int numValues = 8;
int[] array = randomArray(numValues);
ArrayExamples.printArray(array);
int[] scores = randomArray(30);
int a = inRange(scores, 90, 100);
int b = inRange(scores, 80, 90);
int c = inRange(scores, 70, 80);
int d = inRange(scores, 60, 70);
int f = inRange(scores, 0, 60);
// making a histogram
int[] counts = new int[100];
for(int i = 0; i < counts.length; i++) {
count[i] = inRange(scores, i, i+1);
}
//more efficient loop that only traverses array once
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}
//foreach
//basic for loop
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
//written as for each
for(int value : values) {
System.out.println(value);
}
// histogram with enhanced for loop
counts = new int[100];
for (int score : scores) {
counts[score]++;
}
/* For the foreach loop above, write a method called histogram that
* takes an int array of scores from 0 to (but not including) 100, and
* returns a histogram of 100 counters. Generalize it to take the number
* counters as an argument.
*/
}
}