muadgra
muadgra

Reputation: 71

How to avoid using same members in a matrix which is made by rand() function?

I'm trying to make a 5x10 matrix with full of random letters and once the letter is used, it shouldn't be used again. 25 of them have to be small letters, 25 ought to be big letters. Even numbered columns should be small letters too. I don't know how to avoid using same letters. I tried to send the letters used to another array made of one dimension, then check every letter sent by it so that same letter won't be used but my coding skills didn't let me do it. So, my code is this so far:

#include <iostream> 
#include <iomanip> 
#include <stdlib.h>
#include <ctime>                
#include <locale.h>             


using namespace std;

const int row = 5;
const int column = 10;

int main()  
{
    char matris[row][column];

    srand(time(0));

    for (int i = 0; i < row; i++)
        for (int j = 0; j < column; j++)
            if(j % 2 == 0)
                matris[i][j] = rand() % 25 + 65;
            else
                matris[i][j] = rand() % 25 + 97;
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; j++)
            cout << setw(5) << matris[i][j];
        cout << endl;
    }
    system("pause");

    return 0;
    }

So, how can I avoid using same letters? Did I approach wrongly? Is there a easier way to do what I'm trying to do? Thanks...

Upvotes: 0

Views: 66

Answers (2)

Fabio
Fabio

Reputation: 2277

A possible solution is to create a vector containing all the symbols you want to use, randomized it, then draw from that. Example

#include <iostream>
#include <algorithm>
#include <vector>
#include <random>

using namespace std;

struct CharPool
{
    size_t pos;
    vector<char> m_unused_char;

    CharPool()
        : pos(0)
    {
        // add whatever characters you like to the pool
        for (char c = 'a'; c <= 'z'; ++c)
            m_unused_char.push_back(c);
        for (char c = 'A'; c <= 'Z'; ++c)
            m_unused_char.push_back(c);

        std::random_device rd;
        std::mt19937 g(rd());

        // randomize
        shuffle(m_unused_char.begin(), m_unused_char.end(), g);
    }

    char next()
    {
        // here we should assert that the pool is not depleted
        return m_unused_char[pos++];
    }
};

int main()
{
    CharPool pool;
    for (size_t i = 0; i < 10; ++i)
        cout << pool.next() << ", ";
    cout << "\n";
}

Upvotes: 1

L.C.
L.C.

Reputation: 1145

You need to keep trace of the chars that already appeared, to do so you can use a std::set , at each random call, you check if the random result is inside the set: if it is you simply random another number and retry; if not, you insert it and put it in your matrix.

I'd use a set rather than a vector because it's faster when checking if a value already appears in it.

See this to know how to check if a set contains an element: How to check that an element is in a std::set?

Upvotes: 0

Related Questions