-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathIterableWarmups.java
More file actions
115 lines (88 loc) · 2.52 KB
/
IterableWarmups.java
File metadata and controls
115 lines (88 loc) · 2.52 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package Iterable.Practice;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableWarmups {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(7);
numbers.add(10);
numbers.add(4);
numbers.add(8);
System.out.println("Sum: " + sum(numbers));
System.out.println("Even count: " + countEven(numbers));
System.out.println("Max value: " + findMax(numbers));
}
/*
PROBLEM 1
Return the sum of all numbers in the iterable
*/
public static int sum(Iterable<Integer> numbers) {
int total = 0;
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
total += iterator.next();
}
// TODO:
// Use a for-each loop to calculate the sum
return total;
}
/*
PROBLEM 2
Count how many numbers are even
*/
public static int countEven(Iterable<Integer> numbers) {
int count = 0;
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number % 2 == 0) {
count++;
}
}
// TODO:
// Loop through numbers
// Increment count if number is even
return count;
}
/*
PROBLEM 3
Return the maximum value
*/
public static int findMax(Iterable<Integer> numbers) {
int max = Integer.MIN_VALUE;
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number > max) {
max = number;
}
}
// TODO:
// Loop through numbers
// Update max if current number is larger
return max;
}
/*
PROBLEM 4 (BONUS)
Count how many times a word appears
*/
public static int countMatches(Iterable<String> words, String target) {
int count = 0;
if (target == null) {
return 0;
}
Iterator<String> iterator = words.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
if (target.equals(word)) {
count++;
}
}
// TODO:
// Loop through words
// Compare each word to target
return count;
}
}