简体   繁体   中英

iteration: select a random element from random list

I have a tree (or "matrix") containing a bunch of line position points:

tree = [[[x,y],[x,y],[x,y]],
    [[x,y],[x,y],[x,y]],
    [[x,y],[x,y],[x,y]]]

My goal is to connect even more lines from random points on each "branch" to other random points on separate branches. Once a line is created, the position points on both branches will be unusable for future line creation.

I've managed to randomize the point iteration with random.shuffle(), but I'm currently taking one branch at a time and comparing it's points with only one neighboring branch at a time. This gives me a bunch of lines connecting from one branch to the first branch it checks, but I want them all over the place, connecting to many branches.

Here's what I have so far. The functions are native to Cinema 4D. The searchable API can be found here: https://developers.maxon.net/docs/Cinema4DPythonSDK/html/index.html Function GetSplinePoint() simply returns the position of a spline (3D line) object.

rand_pts = [_ for _ in xrange(spline_resolution)]        
for p_spline in xrange(len(splines)):
    random.shuffle(rand_pts)
    for p in rand_pts:
        if p == 0 or p == spline_resolution-1 or occupied[p_spline][p] == True: continue
        mindist = 99999
        new_connection = False
        p_amt = c4d.utils.RangeMap(p, 0, spline_resolution-1, 0, 1, False)
        p_pt = spline_objs[p_spline].GetSplinePoint(p_amt)
        for n_spline in xrange(len(splines)):
            if n_spline != p_spline:
                random.shuffle(rand_pts)
                for n in rand_pts:
                    if n == 0 or n == spline_resolution-1 or occupied[n_spline][n] == True: continue
                    n_amt = c4d.utils.RangeMap(n, 0, spline_resolution-1, 0, 1, False)
                    n_pt = spline_objs[n_spline].GetSplinePoint(n_amt)
                    dist = (p_pt - n_pt).GetLength()
                    if dist < op[c4d.ID_USERDATA,5] and dist < mindist:
                        mindist = dist
                        new_connection = True
                        break

Got it working.

I made a new list:

rand_splines = [_ for _ in xrange(len(splines))]

then shuffled with random.shuffle(rand_splines) before my first and second iterations and used for spline in rand_splines: to iterate the shuffled list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM