This detects violations of my minimum spacing but does not create a new list

I need to generate 10 random numbers with a minimum spacing of 0.15 between any two of them. I am trying to do this:

    r=[]
    for i in range(0,10):
     x=random.uniform(1,6)
     r.insert(i,x)
     print(r)
    for j in range(0,9):
      for k in range(0,j):
       h=m[j]-m[k]
       if h<0.15:
          print(h)
       else:
          continue

      

The above code generates 10 random numbers, then I print the difference between the pairs when that difference is less than 0.15. This detects violations of my minimum spacing, but does not create a new list.

+3


source to share


2 answers


You are missing a very simple thing, you are not trying to recreate the list when it violates your constraints.

I also prefer to be more knowledgeable about things, Python makes it that easy. I've moved the constraint check into my own function.

def meets_constraints(m):
    for j in range(0,9):
        for k in range(0,j):
            h=abs(m[j]-m[k])
            if h<0.15:
                print(h)
                return False
    return True

while True:
    r=[]
    for i in range(0,10):
        x=random.uniform(1,6)
        r.insert(i,x)
        print(r)
    if meets_constraints(r):
        break

      



This will create a new list until you get one where all the elements are at least 0.15. Note that this is incredibly inefficient, since checking all items is an n ^ 2 algorithm and you will keep running some random number of times until it happens through the passing sequence. The best algorithm will ensure the constraint when creating the list first.

PS I also added abs

in the calculation the difference, as I think it was a bug in the original code.

+2


source


something like?



min_interval=0.15
last=0
for n in range(0,10):
    num=last+random()+0.15
    print num
    last=num

      

0


source







All Articles