How to generate 50 distinct numbers in an array?
I have the code for generating 50 numbers but thay are not different. I get same number sometimes twice or three time.
Here is my code:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int num;
int main()
{
    int array[50];
    for(int i = 0; i<50; i++)
    {
        array[i] = rand()%99;
    }
    for(int i = 0; i<50; i++)
    {
        cout<<array[i]<<" ";
    }
      cout <<"\nEnter an integer between 0 & 99: ";
      cin >> num;
      int flag = 0;
     
           for(int k = 0; k < 50; k++)
      {
        if(array[k] == num)
        {
    cout << "Number found in array index " << k << "."
         << endl;
         flag += 1;
        }
      }
      if(flag < 1)
      {
        cout << "number not found." << endl;
      }
     return 0;
}

Dani AI

Generated

A few focused points that fill gaps in the thread and give a ready plan to solve both problems raised by and expanded on by .

Random distinct numbers

  • Don’t pick 50 times from the range at random: that naturally allows repeats. The reliable approach is to build the whole pool (0..99), shuffle it once, then take the first 50 entries. Prefer C++11+ facilities (std::shuffle with std::mt19937) over rand()/random_shuffle (deprecated) for better quality and repeatability.
  • If you must keep rand(), seed it once (srand) and use rand()%100 to get 0..99 (your code used %99, which yields 0..98).

Example (C++11+):

#include <vector>
#include <algorithm>
#include <random>
#include <numeric> // iota

std::vector<int> pool(100);
std::iota(pool.begin(), pool.end(), 0);      // 0..99
std::mt19937 rng(std::random_device{}());
std::shuffle(pool.begin(), pool.end(), rng);
std::vector<int> container(pool.begin(), pool.begin() + 50);

Move-to-top / insertion rules

  • To move a found element at index i to the front while preserving order of the elements above it, rotate the subrange [0..i] so the element at i becomes index 0. std::rotate does exactly this and keeps code simple and correct.
  • If the value is not found, pop_back the bottom element and insert the input at the front. Using std::deque makes push_front/pop_back natural and avoids reallocations; std::vector will work but does an O(n) shift on insert at front (same complexity as the problem requires).

Example operations:

auto it = std::find(container.begin(), container.end(), value);
if (it != container.end())
    std::rotate(container.begin(), it, it + 1); // moves *it to front
else {
    container.pop_back();
    container.insert(container.begin(), value); // or push_front on deque
}

Notes and references

  • Complexity: each move/insert is O(N) — unavoidable for this ordered container model. For details see std::shuffle and std::rotate documentation: and std::rotate.
  • ’s suggestion to shuffle a prepared list is the right idea; the above gives a modern, robust implementation and a clear way to implement the required container behavior.

Recommended Answers

All 3 Replies

How to generate 50 distinct numbers in an array?
I have the code for generating 50 numbers but thay are not different. I get same number sometimes twice or three time.

That's normal. :) Random numbers aren't defined to not repeat. In fact, it's possible, but not probable, that you could randomly pick the same number infinitely. That's just how random numbers are, but a lot of people want a random shuffle instead of just a list of random numbers. :)

To make sure that the numbers don't repeat, you can fill an array in order with the numbers in your range and then shuffle it using rand() to pick the index to swap with. The easy way is to use the random_shuffle() function from <algorithm> because you don't have to think, but it's pretty simple to write your own too.

#include <algorithm>
#include <cstdlib>
#include <iostream>


namespace Raye {
  void randomShuffle( int a[], size_t n )
  {
    for ( int i = 0; i < n - 1; i++ ) {
      // Don't shuffle the parts that have already been shuffled
      std::swap( a[i], a[i + rand() % ( n - i )] );
    }
  }


  void display( const char *label, int a[], size_t n )
  {
    using namespace std;

    cout << label << "\n";
    for ( int i = 0; i < n; i++ )
      cout << a[i] << ' ';
    cout << '\n';
  }
}


int main()
{
  const int N = 20;

  int a[N];
  int b[N];
  int k = 50;

  // You can pick any numbers you want!
  for ( int i = 0; i < N; i++ )
    a[i] = b[i] = k++;

  // You should prefer random_shuffle()
  std::random_shuffle( a, a + N );
  Raye::randomShuffle( b, N );

  // Make sure that it worked :)
  Raye::display( "a:", a, N );
  Raye::display( "b:", b, N );

  return 0;
}

Here is my problem:
A container that holds 50 distinct integers has two ends: top and bottom. When an input integer matches one of the integers in the container, it is then moved to the top, and all the integers above the matched integer are moved down to fill the gap in the container (keeping the same order). When none of the integers in the container matches the input value, the bottom integer is discarded, the remaining integers are moved down to fill the gap (keeping the same order), and the input integer is inserted on top.

I have to input an integer then compare it with the array of generated numbers.
Do u have any idea?
thanks for you reply

That's normal. :) Random numbers aren't defined to not repeat. In fact, it's possible, but not probable, that you could randomly pick the same number infinitely. That's just how random numbers are, but a lot of people want a random shuffle instead of just a list of random numbers. :)

To make sure that the numbers don't repeat, you can fill an array in order with the numbers in your range and then shuffle it using rand() to pick the index to swap with. The easy way is to use the random_shuffle() function from <algorithm> because you don't have to think, but it's pretty simple to write your own too.

#include <algorithm>
#include <cstdlib>
#include <iostream>


namespace Raye {
  void randomShuffle( int a[], size_t n )
  {
    for ( int i = 0; i < n - 1; i++ ) {
      // Don't shuffle the parts that have already been shuffled
      std::swap( a[i], a[i + rand() % ( n - i )] );
    }
  }


  void display( const char *label, int a[], size_t n )
  {
    using namespace std;

    cout << label << "\n";
    for ( int i = 0; i < n; i++ )
      cout << a[i] << ' ';
    cout << '\n';
  }
}


int main()
{
  const int N = 20;

  int a[N];
  int b[N];
  int k = 50;

  // You can pick any numbers you want!
  for ( int i = 0; i < N; i++ )
    a[i] = b[i] = k++;

  // You should prefer random_shuffle()
  std::random_shuffle( a, a + N );
  Raye::randomShuffle( b, N );

  // Make sure that it worked :)
  Raye::display( "a:", a, N );
  Raye::display( "b:", b, N );

  return 0;
}

Here is my problem:
A container that holds 50 distinct integers has two ends: top and bottom. When an input integer matches one of the integers in the container, it is then moved to the top, and all the integers above the matched integer are moved down to fill the gap in the container (keeping the same order). When none of the integers in the container matches the input value, the bottom integer is discarded, the remaining integers are moved down to fill the gap (keeping the same order), and the input integer is inserted on top.

That's a priority queue. :) The big operation with this one is the array shift. It's not very efficient, but you need to copy all of the cells from 0 to n - 2 into the cells 1 to n - 1. That overwrites the last cell and leaves a hole in the first cell for whatever value needs to go there. A function to do that is really simple once you know how it works. :)

int shiftRight( int a[], int n )
{
  // Save the cell we're going to lose
  int last = a[n - 1];

  // Copy over the right cell using the left
  // from right to left in the array
  for ( int i = n - 1; i > 0; i-- )
    a[i] = a[i - 1];

  return last;
}

But that only works for the last cell. I don't want to take the eductional aspect away by doing your work for you, but it's not too hard to turn shiftRight() into a function that returns a and only shifts from 0 to i. I'll leave that as an exercise for you. After you get shiftRight() working the way you want, the rest of the program is a breeze. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.