Probability of a key K present in array
Last Updated :
30 Aug, 2022
Given an array A[] and size of array is N and one another key K. The task is to find the probability that the Key K present in array.
Examples:
Input : N = 6
A[] = { 4, 7, 2, 0, 8, 7, 5 }
K = 3
Output :0
Since value of k = 3 is not present in array,
hence the probability of 0.
Input :N = 10
A[] = { 2, 3, 5, 1, 9, 8, 0, 7, 6, 5 }
K = 5
Output :0.2
The probability of can be found out using the below formula:
Probability = total number of K present /
size of array.
First, count the number of K’s and then the probability will be the number of K’s divided by N i.e. count / N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float kPresentProbability( int a[], int n, int k)
{
float count = 0;
for ( int i = 0; i < n; i++)
if (a[i] == k)
count++;
return count / n;
}
int main()
{
int A[] = { 4, 7, 2, 0, 8, 7, 5 };
int K = 3;
int N = sizeof (A) / sizeof (A[0]);
cout << kPresentProbability(A, N, K);
return 0;
}
|
Python3
def kPresentProbability(a, n, k) :
count = a.count(k)
return round (count / n , 2 )
if __name__ = = "__main__" :
A = [ 4 , 7 , 2 , 0 , 8 , 7 , 5 ]
K = 2
N = len (A)
print (kPresentProbability( A, N, K))
|
Java
class GFG
{
static float kPresentProbability( int a[],
int n,
int k)
{
float count = 0 ;
for ( int i = 0 ; i < n; i++)
if (a[i] == k)
count++;
return count/ n;
}
public static void main(String[] args)
{
int A[] = { 4 , 7 , 2 , 0 , 8 , 7 , 5 };
int K = 2 ;
int N = A.length;
double n = kPresentProbability(A, N, K);
double p = ( double )Math.round(n * 100 ) / 100 ;
System.out.println(p);
}
}
|
C#
using System;
class GFG
{
static float kPresentProbability( int [] a,
int n,
int k)
{
float count = 0;
for ( int i = 0; i < n; i++)
if (a[i] == k)
count++;
return count/ n;
}
public static void Main()
{
int [] A = { 4, 7, 2, 0, 8, 7, 5 };
int K = 2;
int N = A.Length;
double n = kPresentProbability(A, N, K);
double p = ( double )Math.Round(n * 100) / 100;
Console.Write(p);
}
}
|
PHP
<?php
function kPresentProbability(& $a , $n , $k )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
if ( $a [ $i ] == $k )
$count ++;
return $count / $n ;
}
$A = array ( 4, 7, 2, 0, 8, 7, 5 );
$K = 2;
$N = sizeof( $A );
echo round (kPresentProbability( $A , $N , $K ), 2);
?>
|
Javascript
<script>
function kPresentProbability(a,n,k)
{
let count = 0;
for (let i = 0; i < n; i++)
if (a[i] == k)
count+=1;
return count / n;
}
let A = [ 4, 7, 2, 0, 8, 7, 5 ];
let K = 3;
let N = A.length;
document.write(kPresentProbability(A, N,K));
</script>
|
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...