нужна помощь с генерацией чисел С++
Генерация трехзначных чисел:
char symb [] = { '1','2','3' };
for (int i = 0; true; i++)
{
for (int j = 0; j < 3 ; j++)
{
cout << symb[rand() % 3];
}
cout << endl;
}
Как сделать так что бы эти числа не повторялись? Что бы каждый раз выводилось новое число, пока не закончатся все возможные комбинации.
Ответы (3 шт):
Автор решения: Qwertiy
→ Ссылка
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char chs[] = "123";
constexpr unsigned n = sizeof chs - 1;
bool used[n][n][n] = {};
constexpr unsigned nnn = sizeof used;
printf("%u %u\n", n, nnn);
for (int q = 0, i; q < nnn; ++q)
{
while (used[0][0][i = rand() % nnn]);
used[0][0][i] = true;
printf("%c%c%c\n", chs[i/n/n%n], chs[i/n%n], chs[i%n]);
}
return 0;
}
Автор решения: Qwertiy
→ Ссылка
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
constexpr const char chs[] = "123";
constexpr unsigned n = sizeof chs - 1;
struct s3 { char s[3]; } all[n*n*n];
constexpr void build_all()
{
for (unsigned q=0, i=0; q<n; ++q)
for (unsigned w=0; w<n; ++w)
for (unsigned e=0; e<n; ++e, ++i)
{
all[i].s[0] = chs[q];
all[i].s[1] = chs[w];
all[i].s[2] = chs[e];
}
}
int main()
{
build_all();
random_shuffle(begin(all), end(all));
for (auto &x : all) printf("%.3s\n", x.s);
return 0;
}
Автор решения: Qwertiy
→ Ссылка
решил увеличить с 3 до 10
Если нужны не все числа, то: https://ideone.com/tFz6d4 (возможны лидирующие нули)
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <set>
using namespace std;
int main()
{
set <unsigned long long> used;
for (unsigned q=0; q<100; ++q)
{
unsigned long long x;
while (!used.insert(x = (((unsigned long long)rand() << 16 | rand()) << 16 | rand()) % 10000000000).second);
cout << setfill('0') << setw(10) << x << endl;
}
return 0;
}