+ 2

Random number generator from an array of number

I had really like to generate random number from an array of numbers or character instead of using the time(0). I don't know if that can be possible with C++? If not is it possible in Python or which other programming language

2nd Jan 2018, 8:26 PM
Mohamed Gadaphy Nkwenkwat
Mohamed Gadaphy Nkwenkwat - avatar
7 Answers
+ 1
Oh jajaja my english is not well yet. I didn't understand the "instead" word. I don't know much about c++, but in python you can have any list (array) and use choice, below is an example: from random import choice myList = [1, 5, 2, 7, "hello", True, 9] r = choice(myList) In that code, the variable r can be any element of the list, the choice is random :)
2nd Jan 2018, 9:36 PM
Sebastián Zapata
Sebastián Zapata - avatar
+ 8
Altering Sebastián's code: int a[5] = {1,2,3,4,5}; cout << a[time(0)%5];
3rd Jan 2018, 2:42 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
thanks so much this is exactly I expected
2nd Jan 2018, 9:49 PM
Mohamed Gadaphy Nkwenkwat
Mohamed Gadaphy Nkwenkwat - avatar
+ 2
@hatsy Rei that's exactly what I wanted. thanks to Sebastian and your efforts in altering the code there by vanishing it to the right result
3rd Jan 2018, 9:52 AM
Mohamed Gadaphy Nkwenkwat
Mohamed Gadaphy Nkwenkwat - avatar
+ 1
Here is an example https://code.sololearn.com/cnkwO28hu70O/?ref=app Basically with % you divide the number by the n = length of the array and the remainder can be between 0 and n, then you pass that number like the index of the array. That's the best way using time. In python you can import random and use random.choice(list) where list is... A list :D
2nd Jan 2018, 8:52 PM
Sebastián Zapata
Sebastián Zapata - avatar
+ 1
thanks Sebastian but the array has no use in the program and it doesn't work as am saying. maybe I will try that one for Python but how can I implement it in Python
2nd Jan 2018, 9:29 PM
Mohamed Gadaphy Nkwenkwat
Mohamed Gadaphy Nkwenkwat - avatar
+ 1
Jajaja you're right, sorry Thanks :)
3rd Jan 2018, 2:44 AM
Sebastián Zapata
Sebastián Zapata - avatar