Как сделать рандомный массив в c
Перейти к содержимому

Как сделать рандомный массив в c

  • автор:

rand() – генератор случайных чисел в C++

генератор случайных чисел

Не всегда надо заполнять числовые одномерные и двумерные массивы порядковыми номерами или конкретными значениями. Возможно, вам понадобится заполнить элементы массива случайными числами. В С++ для этого есть специальные фyнкции rand() и srand() .

Они находятся в библиoтечном файле cstdlib , поэтому чтобы их применять в программе, необходимо подключить этот библиотечный файл: #include <cstdlib> или #include <stdlib.h> (для старых компиляторов).

Если воспользоваться только функцией rand() – будем получать одинаковые “случайные числа” от запyска к запуску. Наберите следующий код и откомпилируйте программу несколько раз. Обратите внимание, что “случайные числа” всегда будут одинаковы.

Случайное число генерируется в строке 11 и записывается в i -й элемент массива randomDigits . В следующей строке просим его показать. Запуская программу будем видеть каждый раз oдни и тe же числa:

генератор случайных чисел C++, rand c++, srand c++

Получается, что числа генерируются не совсем случайные. Чтобы добиться “настоящей” случайности чисел при повторных запуска x программы, необходимо применить функцию srand() до функции rand() . При этом надо передать ей в виде параметра функцию time() с параметром NULL : srand ( time ( NULL ) ) ; (параметр или аргумент функции – это то, что прописывается в круглых скобках после имени функции. Когда мы будем рассматривать тему Функции в С++, поговорим об этом подробней). Таким образом srand() получает в виде параметра текущее системное время, которое при каждом запускe программы будет разным. Это позволит функции rand() каждый раз генерировать именно случайные числа. Для использования time() необходимо подключить библиотечный файл ctime ( time.h для более старых компиляторов): #include <ctime> .

Пробуйте запускать. Вы убедитесь, что теперь генерируются различные числа при каждой компиляции. У меня получился такой результат:

rand c++, srand c++, генератор случайных чисел

Первая компиляция

rand c++, srand c++, генератор случайных чисел

Вторая компиляция

Все выглядит неплохо. Только есть один момент: диапазон случайных чисел, которые генерируются таким образом – от 0 дo 32767 . Возможно вам понадобится заполнить массив числами от 200 дo 300, от 0.1 дo 1, от -20 дo 20. Такую генерацию случайных чисел возможно и несложно реализовать. В примере рассмотрим несколько случаев:

В первом цикле for происходит генерация случайных чисел определённых диапазонов и их запись в соответствующие массивы. В каждом шаге цикла будут генерироваться новыe случайные числа. Возможно кому-то сложно разобраться как это происходит. Рассмотрим детально:

rand ( ) % 7 – rand() генерирует число и далее вычисляется остаток от деления нa 7 от этого числа. Понятно, что это могут быть числа только oт 0 до 6. Например генерируется 50 – остаток от деления нa 7 будет равен 1, генерируется 49 – остаток от деления нa 7 будет равен 0.

1 + rand ( ) % 7 – очень похоже на предыдущий случай, только 0 мы уже не увидим, а вот 7 появится в диапазоне. Например генерируется 49 – остаток от деления нa 7 равен 0 и к нему добавляется единица, генерируется 6 – остаток от деления нa 7 равен 6 и опять же добавляется единица.

200 + rand ( ) % 101 – даст нам число от 200 до 300. Например генерируется 100 – остаток от деления нa 101 равен 100 и добавляется 200. Получаем число 300. Генерируется 202: 200 + (202 % 101)= 200 + 0 = 200.

rand ( ) % 41 — 20 – oт – 20 дo 20. Например генерируется 1: (1 % 40) – 20 = 1 – 20 = -19; генерируется 30: 30 – 20 = 10.

0.01 * ( rand ( ) % 101 ) – oт 0.01 дo 1. Например генерируется 55: 0.01* 55 = 0.55.

rand c++, srand c++, генератор случайных чисел C++

Чтобы попрактиковаться, попробуйте решить задачу: компьютер “загадывает” число oт 1 дo 7, a пользователь должен его отгадать. Если не получится – смотрите наш вариант решения:

Best way to randomize an array with .NET

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I’d like to create a new Array with the same strings but in a random order.

Please include a C# example in your answer.

19 Answers 19

The following implementation uses the Fisher-Yates algorithm AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the ‘sort by random’ technique, although it is more lines of code. See here for some comparative performance measurements. I have used System.Random, which is fine for non-cryptographic purposes.*

* For longer arrays, in order to make the (extremely large) number of permutations equally probable it would be necessary to run a pseudo-random number generator (PRNG) through many iterations for each swap to produce enough entropy. For a 500-element array only a very small fraction of the possible 500! permutations will be possible to obtain using a PRNG. Nevertheless, the Fisher-Yates algorithm is unbiased and therefore the shuffle will be as good as the RNG you use.

If you’re on .NET 3.5, you can use the following IEnumerable coolness:

Edit: and here’s the corresponding VB.NET code:

Second edit, in response to remarks that System.Random "isn’t threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you’re allowing the routine in which you randomize the array to be re-entered, in which case you’ll need something like lock (MyRandomArray) anyway in order not to corrupt your data, which will protect rnd as well.

Also, it should be well-understood that System.Random as a source of entropy isn’t very strong. As noted in the MSDN documentation, you should use something derived from System.Security.Cryptography.RandomNumberGenerator if you’re doing anything security-related. For example:

You’re looking for a shuffling algorithm, right?

Okay, there are two ways to do this: the clever-but-people-always-seem-to-misunderstand-it-and-get-it-wrong-so-maybe-its-not-that-clever-after-all way, and the dumb-as-rocks-but-who-cares-because-it-works way.

Dumb way

  • Create a duplicate of your first array, but tag each string should with a random number.
  • Sort the duplicate array with respect to the random number.

This algorithm works well, but make sure that your random number generator is unlikely to tag two strings with the same number. Because of the so-called Birthday Paradox, this happens more often than you might expect. Its time complexity is O(n log n).

Clever way

I’ll describe this as a recursive algorithm:

  • do nothing
  • (recursive step) shuffle the first n-1 elements of the array
  • choose a random index, x, in the range [0..n-1]
  • swap the element at index n-1 with the element at index x

The iterative equivalent is to walk an iterator through the array, swapping with random elements as you go along, but notice that you cannot swap with an element after the one that the iterator points to. This is a very common mistake, and leads to a biased shuffle.

Time complexity is O(n).

This algorithm is simple but not efficient, O(N 2 ). All the «order by» algorithms are typically O(N log N). It probably doesn’t make a difference below hundreds of thousands of elements but it would for large lists.

The reason why it’s O(N 2 ) is subtle: List.RemoveAt() is a O(N) operation unless you remove in order from the end.

You can also make an extention method out of Matt Howells. Example.

Then you can just use it like:

Just thinking off the top of my head, you could do this:

Randomizing the array is intensive as you have to shift around a bunch of strings. Why not just randomly read from the array? In the worst case you could even create a wrapper class with a getNextString(). If you really do need to create a random array then you could do something like

The *5 is arbitrary.

Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target array.

This yields a truly independent sort.

Nick's user avatar

Ok, this is clearly a bump from my side (apologizes. ), but I often use a quite general and cryptographically strong method.

Shuffle() is an extension on any IEnumerable so getting, say, numbers from 0 to 1000 in random order in a list can be done with

This method also wont give any surprises when it comes to sorting, since the sort value is generated and remembered exactly once per element in the sequence.

Jacco, your solution ising a custom IComparer isn’t safe. The Sort routines require the comparer to conform to several requirements in order to function properly. First among them is consistency. If the comparer is called on the same pair of objects, it must always return the same result. (the comparison must also be transitive).

Failure to meet these requirements can cause any number of problems in the sorting routine including the possibility of an infinite loop.

Regarding the solutions that associate a random numeric value with each entry and then sort by that value, these are lead to an inherent bias in the output because any time two entries are assigned the same numeric value, the randomness of the output will be compromised. (In a «stable» sort routine, whichever is first in the input will be first in the output. Array.Sort doesn’t happen to be stable, but there is still a bias based on the partitioning done by the Quicksort algorithm).

You need to do some thinking about what level of randomness you require. If you are running a poker site where you need cryptographic levels of randomness to protect against a determined attacker you have very different requirements from someone who just wants to randomize a song playlist.

Generate a random array in C or C++

Today, in this tutorial, we will get to know how to generate a random array with random values in C and C++. So you will learn how to generate a random number and store the corresponding number in an array. Below you can see source codes of generating random numbers in C and C++.

Method to Generate random array in C or C++

Follow the steps::

  • Get the size of an array and declare it
  • Generate random number by inbuilt function rand()
  • Store randomly generated value in an array
  • Print the array

Rand() function::

Random value can be generated with the help of rand() function. This function does not take any parameters and use of this function is same in C and C++. Syntax to get random one digit number::

C++ program to generate a random array

Now, we will see a C++ program to generate a random array. Here we generate values between 0 and 99 by using inbuilt function rand() and assign it to a particular position in an array. Here we take the size of an array and then declares an array of particular size. Random numbers are generated by using rand() function and that number is divided by 100 and the remainder is stored in an array at a particular location. After initializing, the array is printed.

C program to generate a random array

Now, we will see a C program to generate a random array. Here we generate values between 0 and 99 by using the inbuilt function rand() and assign it to a particular position in an array. Here we take the size of an array and then declares an array of a particular size. Random numbers are generated by using rand() function and that number is divided by 100 and the remainder is stored in an array at a particular location. After initializing, the array is printed.

How to effectively deal with bots on your site? The best protection against click fraud.

Язык программирования C++ включает встроенный генератор псевдослучайных чисел, а также два метода генерации случайных чисел: rand() и srand(). Давайте подробно рассмотрим методы rand() и srand().

Чтобы получить случайное число, мы используем метод rand(). При вызове функция rand() в C++ генерирует псевдослучайное число от 0 до RAND MAX. Всякий раз, когда этот метод используется, он использует алгоритм, который дает последовательность случайных чисел. Мы не можем считать созданные числа действительно случайными, потому что они создаются с использованием алгоритма, использующего начальное значение; вместо этого мы называем такие числа псевдослучайными числами.

Сранд()

Метод srand() часто используется в сочетании с методом rand(). Если метод srand() не используется, начальное значение rand() генерируется так, как если бы srand (1) использовался ранее в настройке программы. Любое другое начальное значение заставляет генератор начинаться с нового места.

Обратите внимание, что если вы используете rand() для создания случайных чисел без предварительного выполнения srand(), ваш код будет генерировать последовательность одних и тех же целых чисел при каждом запуске.

Пример 1

Мы используем метод rand() для генерации случайных чисел в массиве целых чисел. Во-первых, мы объявили переменную «MyNumber» с типом данных integer. Переменная MyNumber принимает от пользователя целочисленное значение. Затем у нас есть целочисленный массив «Rand», а в следующей строке у нас есть цикл цикла for, который генерирует случайное число на каждой итерации с использованием метода rand().

Мы берем размер массива, а затем определяем массив этого размера. Метод rand() генерирует случайные числа, делит их на 10 и сохраняет остаток в массиве в определенной позиции. Массив будет напечатан после инициализации.

используя пространство имен std ;

cout << «Введите число размера массива::» ;

инт Рэнд [ Мой номер ] ;

за ( инт р = 0 ; р < Мой номер ; р ++ )

Рэнд [ р ] = ранд ( ) % 10 ;

cout << » \n Элементы массива::» << конец ;

за ( инт р = 0 ; р < Мой номер ; р ++ )

cout << «Количество элементов» << р + 1 << «::» << Рэнд [ р ] << конец ;

Результат случайных чисел в целочисленном массиве показан на следующем изображении.

Пример 2

Как уже говорилось, srand() устанавливает начальное значение для метода rand(). Мы создали метод для заполнения массива случайными значениями с помощью метода srand() в C++. Прежде всего, мы импортировали встроенную библиотеку c++ time.h, которая возвращает текущую временную метку в момент вызова функции. В результате мы можем гарантировать, что при каждом выполнении программы методу srand() присваивается отдельное значение в качестве параметра.

Затем у нас есть еще одна встроенная библиотека, «stdlib.h», через которую мы можем получить доступ как к методам rand, так и к методам srand. У нас есть основная функция, в которой код приводится в действие. Мы создали массив как «Массив» произвольного размера. Размер массива будет указан пользователем. Затем мы использовали метод srand и передали в него начальное значение «NULL». Каждый раз, когда мы запускаем программу, вместо повторяющихся значений генерируется случайный и уникальный набор значений.

В блоке цикла for у нас есть метод rand(), который будет генерировать случайное число в каждом цикле цикла. Команда cout напечатает случайное число заданного размера массива.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *