Skip to content

Commit 53acb6e

Browse files
authored
Create 3044-most-frequent-prime.js
1 parent bfe5498 commit 53acb6e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

3044-most-frequent-prime.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @param {number[][]} mat
3+
* @return {number}
4+
*/
5+
var mostFrequentPrime = function (mat) {
6+
const DIRS = [
7+
[1, 1],
8+
[1, -1],
9+
[-1, 1],
10+
[-1, -1],
11+
[1, 0],
12+
[0, 1],
13+
[-1, 0],
14+
[0, -1],
15+
]
16+
17+
const m = mat.length
18+
const n = mat[0].length
19+
const f = new Map()
20+
21+
for (let i = 0; i < m; i++) {
22+
for (let j = 0; j < n; j++) {
23+
for (const d of DIRS) {
24+
let t = 0
25+
for (
26+
let k = i, l = j;
27+
k >= 0 && k < m && l >= 0 && l < n;
28+
k += d[0], l += d[1]
29+
) {
30+
t = t * 10 + mat[k][l]
31+
f.set(t, (f.get(t) || 0) + 1)
32+
}
33+
}
34+
}
35+
}
36+
37+
let res = -1
38+
let maxF = 0
39+
40+
for (const [val, freq] of f.entries()) {
41+
if (val <= 10) continue
42+
if (freq >= maxF && isPrime(val)) {
43+
if (freq === maxF) {
44+
res = Math.max(res, val)
45+
} else {
46+
res = val
47+
}
48+
maxF = freq
49+
}
50+
}
51+
52+
return res
53+
}
54+
function isPrime(N) {
55+
if (N < 2) return false
56+
const R = Math.sqrt(N)
57+
for (let d = 2; d <= R; ++d) {
58+
if (N % d === 0) return false
59+
}
60+
return true
61+
}

0 commit comments

Comments
 (0)