-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathIterableWarmups.java
More file actions
104 lines (77 loc) · 2.13 KB
/
IterableWarmups.java
File metadata and controls
104 lines (77 loc) · 2.13 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
package Iterable.Practice;
import java.util.ArrayList;
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;
// TODO:
// Use a for-each loop to calculate the sum
for (Integer num : numbers) {
total += num;
}
return total;
}
/*
PROBLEM 2
Count how many numbers are even
*/
public static int countEven(Iterable<Integer> numbers) {
int count = 0;
// TODO:
// Loop through numbers
// Increment count if number is even
for (Integer num : numbers) {
if (num % 2 == 0) {
count++;
}
}
return count;
}
/*
PROBLEM 3
Return the maximum value
*/
public static int findMax (Iterable < Integer > numbers) {
int max = Integer.MIN_VALUE;
// TODO:
// Loop through numbers
// Update max if current number is larger
for (Integer num : numbers) {
if (num > max) {
max = num;
}
}
return max;
}
/*
PROBLEM 4 (BONUS)
Count how many times a word appears
*/
public static int countMatches (Iterable < String > words, String target){
int count = 0;
// TODO:
// Loop through words
// Compare each word to target
for (String word : words) {
if (word.equals(target)) {
count++;
}
}
return count;
}
}