Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to generate 10 random numbers with a minimum spacing of 0.15 between any two of them. What I am trying is 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 pairs when that difference is less than 0.15. This detects violations of my minimum spacing, but does not produce a new list.

like image 868
user1992 Avatar asked Nov 23 '25 19:11

user1992


1 Answers

You're missing a very basic thing, you don't try to recreate the list when it violates your constraints.

I also prefer to break things apart more than this, Python makes it so easy. I've moved your constraint checking into its 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 keeps generating a new list until you obtain one where all of the elements are at least 0.15 apart. Note that this is incredibly inefficient, since checking all the elements is an n^2 algorithm and you will keep performing the test some random number of times until you happen across a sequence that passes. A better algorithm would guarantee the constraint as you're building the list in the first place.

P.S. I've also added an abs in the difference calculation, since I think that was a bug in your original code.

like image 73
Mark Ransom Avatar answered Nov 25 '25 11:11

Mark Ransom