Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
L
lab_reactive_java
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Deploy
Releases
Package Registry
Container Registry
Model registry
Operate
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
rtbdp
labs
lab_reactive_java
Commits
d8f9156a
Commit
d8f9156a
authored
8 years ago
by
Stuart Marks
Browse files
Options
Downloads
Patches
Plain Diff
add ex37_majority()
parent
269948a3
No related branches found
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
LambdaLab/test/solutions/Exercises.java
+35
-0
35 additions, 0 deletions
LambdaLab/test/solutions/Exercises.java
with
35 additions
and
0 deletions
LambdaLab/test/solutions/Exercises.java
+
35
−
0
View file @
d8f9156a
...
...
@@ -33,6 +33,7 @@ import java.util.HashSet;
import
java.util.IntSummaryStatistics
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.OptionalInt
;
import
java.util.Random
;
import
java.util.Set
;
import
java.util.TreeMap
;
...
...
@@ -1287,6 +1288,40 @@ public class Exercises {
new
ArrayList
<>(
result
));
}
/**
* Given an array of int, find the int value that occurs a majority
* of times in the array (that is, strictly more than half of the
* elements are that value), and return it in an OptionalInt. If there
* is no majority value, return an empty OptionalInt.
*/
OptionalInt
majority
(
int
[]
array
)
{
//UNCOMMENT//return null; // TODO
//BEGINREMOVE
Map
<
Integer
,
Long
>
map
=
Arrays
.
stream
(
array
)
.
boxed
()
.
collect
(
groupingBy
(
x
->
x
,
counting
()));
return
map
.
entrySet
().
stream
()
.
filter
(
e
->
e
.
getValue
()
>
array
.
length
/
2
)
.
mapToInt
(
Entry:
:
getKey
)
.
findAny
();
//ENDREMOVE
}
@Test
public
void
ex37_majority
()
{
int
[]
array1
=
{
3
,
3
,
4
,
2
,
4
,
4
,
2
,
4
,
4
};
int
[]
array2
=
{
3
,
3
,
4
,
2
,
4
,
4
,
2
,
4
};
OptionalInt
result1
=
majority
(
array1
);
OptionalInt
result2
=
majority
(
array2
);
assertTrue
(
result1
.
isPresent
()
&&
result1
.
getAsInt
()
==
4
);
assertFalse
(
result2
.
isPresent
());
}
// ========================================================
// END OF EXERCISES -- CONGRATULATIONS!
...
...
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment