C++

난수 발생 중복되지 않도록 구현(Visual Studio 2008)

Geuny 2011. 5. 24. 12:41

소스코드

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

int _tmain(int argc, _TCHAR* argv[])
{
	srand((unsigned)time(NULL));
 
	int array[10];
 	int a = 0;
 	int tmp = 0;
 	int count = 0;

 	while (a < 10)
 	{
 		if (a == 0)
		{
			array[0] = rand() % 10;
			a++;
		}
		else
		{
			tmp = rand() % 10;
			count = 0;
            
			for (int i = 0; i < 10 ; i++)
			{
				if (array[i] == tmp)
				{
					count++;
				}
			}

			if (count == 0)
			{
				array[a] = tmp;
				a++;
			}
		}
	}
 
	for (int i = 0; i < 10; i++)
	{
		cout << array[i] << endl;
	}

	return 0;
}

 


출력결과