S
S
sidor_tank2017-10-19 00:00:04
C++ / C#
sidor_tank, 2017-10-19 00:00:04

How to find the number of distinct elements in a random array (C++)?

In general, I made a program, but it does not work a little correctly, if the same numbers are in a row, then it does not display them. Tell me what's the matter? Here is the full condition: There are many matching elements in the array M(k). Find the number of distinct elements in it. Here I did it a little differently: an array of various elements is displayed on the screen, but the meaning remains the same. The challenge is to do this using array loops and conditions.

#include <locale>
#include <iostream>
#include <conio.h>
void main()
{
  setlocale(LC_ALL, "rus");
  using namespace std;
  int n, i, r=0, c=1;
  int *a = new int[99999];
  int	*b = new int[99999];
  int t, k=0;
  cout << "Введите размер массива" << endl;
  cin >> n;
  cout << "Введите размерность" << endl;
  cin >> t;
  cout << endl;
  srand((unsigned)time(NULL));
  cout << "Цикл" << endl;
  for (i = 0; i < n; i++)   // Создаём рандомный массив
  {
    a[i] = rand() % t;
    cout << a[i] << endl;
  }
  cout << endl;
  for (i = 0; i < n; i++)
  {
    for (int h=0; h < n+1; h++) {


      if (a[i] != a[h] && i!=h) {
        k++;
        if (k==i+1) {
          cout << a[i] << endl;
          break;
        }
      }
      if (a[i] == a[h] && i != h) {

        break;
      }
      

    }
    k = 0;
  }
  _getch();
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2017-10-19
@sidor_tank

The array M(k) has many matching elements. Find the number of distinct elements in it.

Please specify how many different elements are in the array 1, 1, 2 - 1 or 2?
I tried to understand your code, but I couldn't.
for (int h=0; h < n+1; h++) {
if (a[i] != a[h] && i!=h)

Crawled out of the array a.

O
ololo pishpish, 2017-10-19
@ololopishpishrealne

I did not read the code, I immediately answer.
Get a separate array and add an element to it only if it is not in it, for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question