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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With