C
Christushka
Даны массивы А и В, с размерностью N. Определить, какой элемент массива В чаще всего встречается в А.
#include <stdio.h>
#include <stdlib.h>
int main()
{
const N=4;
int a[N],b[N],c[N];
int i,j,OfftenlyIndex=0,OfftenlyEl;
/*Читам массив*/
printf("A:\n");
for (i=0;i<N;i++) scanf("%d",&a[i]);
printf("B:\n");
for (i=0;i<N;i++) scanf("%d",&b[i]);
for (i=0;i<N;i++) c[i]=0; //Обнуляем массив c
for (i=0;i<N;i++)
for (j=0;j<N;j++) if (a[i]==b[j]) c[j]++;//Пробегаем по массиву a и считаем кол-во совпадений a[i] с b[j]
OfftenlyEl=c[0];
for (i=0;i<N;i++) if (OfftenlyEl<c[i]){ //Ищем максимальный из c
OfftenlyIndex=i;
OfftenlyEl=c[i];
}
printf("Чаще всего встречается элемент b[%d]=%d",(OfftenlyIndex+1),b[OfftenlyIndex]);
return 0;
}
#include <map>
#include <iostream>
#include <boost/spirit/home/phoenix.hpp>
namespace phx = boost::phoenix;
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
using namespace boost::adaptors;
using phx::arg_names::arg1;
/*
Даны массивы А и В, с размерностью N. Определить, какой элемент массива В чаще всего встречается в А.
*/
template <typename T, size_t N>
T find_most_frequent(const T (&A)[N], const T (&B)[N])
{
T tmp[N];
boost::copy(B, tmp);
boost::sort(tmp);
T* end = std::unique(tmp, tmp+N);
std::map<T, size_t> m;
std::for_each(tmp, end, phx::ref(m)[arg1] = phx::count(phx::cref(A), arg1));
return boost::max_element(m | map_values).base()->first;
}
int main()
{
const int A[10] = {1,2,2,3,3,4,4,7,2,9};
const int B[10] = {0,1,5,6,7,1,2,-1,2};
const int most = find_most_frequent(A, B);
// наиболее частый элемент == 2, встречается 3 раза
std::cout << most << std::endl;
return 0;
}
Взломай свой первый сервер и прокачай скилл — Начни игру на HackerLab