Create a random order of (x, y) pairs, without repeating/subsequent x's

后端 未结 9 2274
陌清茗
陌清茗 2021-02-08 12:25

Say I have a list of valid X = [1, 2, 3, 4, 5] and a list of valid Y = [1, 2, 3, 4, 5].

I need to generate all combinations of every element in

9条回答
  •  不思量自难忘°
    2021-02-08 13:12

    Here is my solution. First the tuples are chosen among the ones who have a different x value from the previous selected tuple. But I ve noticed that you have to prepare the final trick for the case you have only bad value tuples to place at end.

    import random
    
    num_x = 5
    num_y = 5
    
    all_ys = range(1,num_y+1)*num_x
    all_xs = sorted(range(1,num_x+1)*num_y)
    
    output = []
    
    last_x = -1
    
    for i in range(0,num_x*num_y):
    
        #get list of possible tuple to place    
        all_ind    = range(0,len(all_xs))
        all_ind_ok = [k for k in all_ind if all_xs[k]!=last_x]
    
        ind = random.choice(all_ind_ok)
    
        last_x = all_xs[ind]
        output.append([all_xs.pop(ind),all_ys.pop(ind)])
    
    
        if(all_xs.count(last_x)==len(all_xs)):#if only last_x tuples,
            break  
    
    if len(all_xs)>0: # if there are still tuples they are randomly placed
        nb_to_place = len(all_xs)
        while(len(all_xs)>0):
            place = random.randint(0,len(output)-1)
            if output[place]==last_x:
                continue
            if place>0:
                if output[place-1]==last_x:
                    continue
            output.insert(place,[all_xs.pop(),all_ys.pop()])
    
    print output
    

提交回复
热议问题