FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Maths/Mode.java at master · loisoft/Java · GitHub
loisoft
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Maths
/
Mode.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
59 lines (46 loc) · 1.5 KB
Breadcrumbs
Java
/
Maths
/
Mode.java
Copy path
File metadata and controls
59 lines (46 loc) · 1.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
Maths
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
Collections
;
import
java
.
util
.
HashMap
;
/*
* Find the mode of an array of numbers
*
* The mode of an array of numbers is the most frequently occurring number in the array,
* or the most frequently occurring numbers if there are multiple numbers with the same frequency
*/
public
class
Mode
{
public
static
void
main
(
String
[]
args
) {
/* Test array of integers */
assert
(
mode
(
new
int
[] {})) ==
null
;
assert
Arrays
.
equals
(
mode
(
new
int
[] {
5
}),
new
int
[] {
5
});
assert
Arrays
.
equals
(
mode
(
new
int
[] {
1
,
2
,
3
,
4
,
5
}),
new
int
[] {
1
,
2
,
3
,
4
,
5
});
assert
Arrays
.
equals
(
mode
(
new
int
[] {
7
,
9
,
9
,
4
,
5
,
6
,
7
,
7
,
8
}),
new
int
[] {
7
});
assert
Arrays
.
equals
(
mode
(
new
int
[] {
7
,
9
,
9
,
4
,
5
,
6
,
7
,
7
,
9
}),
new
int
[] {
7
,
9
});
}
/*
* Find the mode of an array of integers
*
* @param numbers array of integers
* @return mode of the array
*/
public
static
int
[]
mode
(
int
[]
numbers
) {
if
(
numbers
.
length
==
0
)
return
null
;
HashMap
<
Integer
,
Integer
>
count
=
new
HashMap
<>();
for
(
int
num
:
numbers
) {
if
(
count
.
containsKey
(
num
)) {
count
.
put
(
num
,
count
.
get
(
num
) +
1
);
}
else
{
count
.
put
(
num
,
1
);
}
}
int
max
=
Collections
.
max
(
count
.
values
());
ArrayList
<
Integer
>
modes
=
new
ArrayList
<>();
for
(
int
num
:
count
.
keySet
()) {
if
(
count
.
get
(
num
) ==
max
) {
modes
.
add
(
num
);
}
}
return
modes
.
stream
().
mapToInt
(
n
->
n
).
toArray
();
}
}
Back
|
FazBrowse Home
|
New Git URL