+ 5
How to find the frequency of numbers of in an array?
A code to output the number each element of the array occurs. {5,8,9,2,5,9} 2:1 5:2 8:1 9:2
6 Answers
+ 14
// a simple approach
firstlt sort the array , so that if there were duplicate elements then they will be adjacent to each other , now run a loop from n=0 , arr.length-2
a variable p inside that loop ,
put a if else statement inside it , if arr [n]==arr [n+1] , then increase p , else print previois no. & value of p & then initialize p with 0 again 👍
+ 4
In Java I would use HashMap. See example in my code here: https://code.sololearn.com/cPWZUgEEkD0t/#java
+ 2
In which language?
My approach would be to create an empty array. Then iterate through the number array. Then for every new number, insert a new object to the new array. The new object should have the current number and a counter for the frequency.
+ 1
Python:
arr = [5, 8, 9, 2, 5, 9]
freq_map = {}
for v in arr:
if v in freq_map:
freq_map[v] += 1
else:
freq_map[v] = 1
print(freq_map)
- 2
<html>
<head>
<title>စကားဝွက္ေမ့ေနၿပီ | ေလာ့ဂ္အင္၀င္လို့မရပါ | Facebook</title>
<meta name="viewport" content="user-scalable=no,initial-scale=1,maximum-scale=1">
<link href="https://static.xx.fbcdn.net/rsrc.php/v3/ya/r/O2aKM2iSbOw.png" rel="shortcut icon" sizes="196x196">
<meta name="referrer" content="default" id="meta_referrer">
<link rel="stylesheet" type="text/css" data-bootloader-hash="IIecJ" href="https://<html>
<head>
<t/rsrc.php/v3/yM/l/0,cross/zxJzF38_RUR.css">
<link rel="stylesheet