# Generating a 4-digit number with distinct digits?

This is a discussion on Generating a 4-digit number with distinct digits? within the C++ Programming forums, part of the General Programming Boards category; I 've started programming a " Bulls and Cows " game.I got through the two player mode(which is easy). Now ...

1. ## Generating a 4-digit number with distinct digits?

I've started programming a "Bulls and Cows" game.I got through the two player mode(which is easy). Now for the single player, I know how to generate a random number but I have a problem in generating a number with distinct digits(4-digit number)?Can anyone help me out?

Example:
The number can be 1234 not 1133 or 2448.

[code]
#include <stdlib.h>
#include <iostream.h>
#include <conio.h>

void main()
{
char guess[10], word[10];
int turns, a, b, bulls, cows;
clrscr();
cout<<"Welcome to Bulls & Cows \n\nPlayer 1, enter the letters(distinct) of your word: ";
cin.getline(word,sizeof(word));
clrscr();

for(turns=1;turns<=10;turns++)
{
bulls=0;cows=0;
cout<<"\nEnter Guess : "<<turns;
cin.getline(guess,sizeof(guess));

for(a=0;a<4;a++)
{
if(guess[a]==word[a])
{
bulls++;
}
else
{
for(b=0;b<4;b++)
{
if(guess[a]==word[b])
{
cows++;
}
}
}
}

if(bulls==4)
{
cout<<"\nYou are Victorious!\n";
break;
}else
{
cout<<"\nBulls ="<<bulls<< "Cows ="<<cows;
}
}

getch();
}
[\code]

2. Another approach is to generate a random four digit number, check if any digits are repeated, and if so throw the number away and generate another one.

Sounds dumb, but is in fact a common way of generating samples of a specific distribution.

3. I'm new to c++ and this is how they teach in our school.

4. Occasionally someone does get by the code filter though. This will help you follow board etiquette in the future. Code tags are supposed to be [code] [ / code] and you can also use the # button when making a new thread, or on the advanced reply form. To get from the Quick Reply box to the advanced reply form, click the button that says Go Advanced.

In general, check your posts before you submit em. We have to see exactly what you see. People can post the nastiest junk code sometimes...

5. Originally Posted by droidbreath
I'm new to c++ and this is how they teach in our school.
This is an opportunity for you to learn yourself better C++ than the (seemingly) junk your school teaches you. It will also be of more use to you in real life.