Click here to Skip to main content
15,066,296 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!
I was trying to write the code to fill random numbers in an array (using srand) such that no number is repeated. During the execution i got a Time Limit Exceeded message.
How can i solve this?
Following is the code:

C++
#include<iostream>
using namespace std;
#include<cstdlib>
#include<ctime>
int main()
{
	srand(time(NULL));
	int *deck=new int[52];
	for(int i=0;i<52;i++)
		deck[i]=-1;
	int j,top=-1;
	while(top!=51)
	{
		j=rand()%52;
		if(top==-1)
		{
			top++;
			deck[top]=j;
		}
		else
		{
			int flag=0,f=0;
			while(deck[flag]!=-1||flag!=52)
			{
				if(deck[flag]==j)
					f=1;
				flag++;
			}
			if(flag==top+1&&f==0)
			{
				top++;
				deck[top]=j;
			}
		}
	}
	for(int k=0;k<52;k++)
	{
		cout<<deck[k]<<endl;
	}
	return 0;
}


What I have tried:

I tried using printf and scanf instead of cin and cout as they are faster but dint work.
Posted
Updated 25-Aug-16 5:21am
Comments
[no name] 25-Aug-16 10:50am
   
How did you get the message that the time limit was exceeded? By mail? A phone call? A mounted courier? And who or what sent it?

Nothing in the code you posted sends that kind of a message. So the simple answer is: For some unknown component the execution of your code takes too long, as the message says. Make it faster.

This while loop
C++
while(deck[flag]!=-1||flag!=52)

will be executed until flag is 52. It is similar to
C++
while(flag!=52)


To leave the loop when the first condition is met use an AND operation:
C++
while(deck[flag]!=-1 && flag!=52)
   
As far as I remember, an array an a pointer to an array do not use the same syntax. And I see the syntax to access array elements on a pointer.

C++ Pointers[^]

You should also read these books:
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]

C++ Programing Language[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900