0

For instance, let's say I have a random array [5,2,1,3,6,4] and I want to access it at least 6 times (i.e. 6 == len(array)) (the acess order doesn't matter, nor does it matter that I've accessed them all). How can I randomly access the whole array without popping any of the values ?

In other words, I am trying to write a function find_new_index which takes an index i such that:

arr = [5,2,1,3,6,4]
i=0
x = 0
while i < 6:
    access = arr[i]
    x+=1
    i = i + find_new_index(i)
assert(x >= 6)

The idea is that this function works for any random array of size N which has random values from 1 to N.

PS : The easy way to write find_indexis to generate a random number within it. However, I want to know if it's possible to write this function without loops or any function calls.

This differs from other questions, since I don't want to use the Random Module.

Kris
  • 61
  • 5
  • Are you trying to get the 6 elements in a random order, or can one element be returned multiple times? – Prune Nov 15 '20 at 17:50
  • one element can be returned multiple times. What I access really doesn't matter. What matters is how many times I access the array and the fact that I want to access it randomly – Kris Nov 15 '20 at 18:03
  • You say you want a random element, but you don't want to use the `random` module. This is much like saying that you want to add integers, but without using the `+` operator. If you don't use the provided facility, then you have to write your own. In that case, research how to write a RNG (random number generator). There is plenty of documentation on line; we expect you to do that research before posting here. – Prune Nov 15 '20 at 18:07
  • I can't write my own random generator, because as I said, I can't use any loops or function calls. This is simply an exercise that a friend of mine gave as a challenge. – Kris Nov 15 '20 at 18:11
  • Now I'm *really* confused; how does a RNG inherently require a loop or a function call? – Prune Nov 15 '20 at 18:28

2 Answers2

1

You can use the random.choice(my_list) function.

import random
arr = [5,2,1,3,6,4]

i = 0
while i < 6:
    access = random.choice(arr)
    #do whatever you want
    i += 1

For example, print the access adding a print(access) instead of the comment can output something like:

2
2
6
6
4
1
lorenzozane
  • 1,214
  • 1
  • 5
  • 15
0

you probably want to use the random module:

import random
arr=[5,2,1,3,6,4]
access =[]
for i in range(len(arr)):
    access.append(arr[random.randint(0,len(arr))])
print(access)

>>> [1,2,1,4,4,6]

UPDATE

This differs from other questions, since I don't want to use the Random Module.

the one way i think you can make it is with the time module....

from datetime import datetime
def get_random(mini,maxi):
    timestamp = datetime.now().timestamp() * 1000
    return timestamp % maxi + mini

# rest of the code ...    
for i in range(len(arr)):
    access.append(arr[get_random(0,len(arr))])
adir abargil
  • 5,495
  • 3
  • 19
  • 29