C++ interview questions: print out the number between 1 and 10000 as required

Title description:

Please write a program to print out the number between 1 and 10000. Requirements:
a) Random out of order
b) Cannot be repeated
c) All output, can not be omitted
d) If you want to use data containers, you can only use arrays.

Coding implementation:

#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

const int MaxNum = 1e4 + 10;
int first_array[MaxNum], second_array[MaxNum];

int main() 
{
    
    
	srand((unsigned)time(NULL));
	for(int i = 0;i < 10000; ++i)
	{
    
    
		first_array[i] = i + 1;
	}
	int index, tmp, rest = 10000;
	for(int i = 0; i < 10000; ++i) 
	{
    
    
		index = rand() % rest;
		//冒泡算法随机交换位置
		second_array[i] = first_array[index];
		tmp = first_array[index];
		first_array[index] = first_array[rest - 1];
		first_array[rest - 1] = tmp;
		rest--;
	}
	for(int i = 0; i < 10000; ++i)
	{
    
    
		cout <<  second_array[i] << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/oTianLe1234/article/details/114179531