크기가 'n'인 배열이 주어지고 배열에서 사용 가능한 경우 주어진 요소 k의 확률을 찾는 것이 작업입니다.
배열의 요소 수와 동일한 'n'까지 전체 배열을 탐색하고 주어진 요소 또는 키 'k'를 검색합니다. 요소가 배열에 있는 경우 확률을 계산하지 않으면 0을 인쇄합니다.
입력
arr[] = { 1, 2, 3, 4, 5, 6}
K = 5 출력
probability of a key 5 in an array is :0.166
입력
arr[] = { 1,2,3,4,5,6,7 }
K = 8 출력
probability of a key 5 in an array is :0
설명

위에 주어진 크기가 7인 배열과 키 2가 있으므로 배열은 키 값 2를 찾기 위해 7번 탐색됩니다. 2가 식별될 때마다 임시 변수를 1씩 증가시키고 요소가 2가 아닌 경우 다음으로 이동합니다. 카운터를 증가시키지 않고 요소. 결국 -
-
카운터가 0이면 키가 배열에 존재하지 않을 확률이 0이 됩니다.
-
카운터가 0 이외의 값이면 키 ''''의 확률을 계산하는 공식을 적용합니다.
확률(k) =총 'k' 발생 횟수 / 총 요소 수
총 'K' 발생 횟수 =4
배열의 총 요소 수 =7
키(k)의 확률 =4 / 7 =0.57
알고리즘
Start
Step 1→ declare function to calculate probability of key in an array
float probab_key(int arr[], int size, int key)
declare float count = 0
Loop For int i = 0 and i < size and i++
IF arr[i] = key
Set count++
End
End
return count / size
Step 2→ In main()
Declare int arr[] = { 1, 2, 3, 4, 5, 6}
Declare int key = 5
Declare int size = sizeof(arr) / sizeof(arr[0])
Call probab_key(arr, size, key)
Stop 예시
#include <bits/stdc++.h>
using namespace std;
// calculate the probability of a key in an array
float probab_key(int arr[], int size, int key){
float count = 0;
for (int i = 0; i < size; i++){
if (arr[i] == key)
count++;
}
return count / size;
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 6};
int key = 5;
int size = sizeof(arr) / sizeof(arr[0]);
cout <<"probability of a key "<<key<<" in an array is :"<<probab_key(arr, size, key);
return 0;
} 출력
위의 코드를 실행하면 다음 출력이 생성됩니다 -
probability of a key 5 in an array is :0.166667