Home > Software design >  How to create a 2D array from 1D with the algorithm specified in the description?
How to create a 2D array from 1D with the algorithm specified in the description?

Time:12-01

Good afternoon,
I need to create a 2D array from 1D , according to the following rules:\

  • The 2d array must not contain
    [["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"]...]
  • The array should not repeat, it's same for me
    [["A1", "A2"], ["A2", "A1"], ....]\
  • For example Input array
    A ["A1", "A2", "A3", "A4"]
    Output array
    B [['A1' 'A2'] ['A1' 'A3']['A1' 'A4']['A2' 'A1']['A2' 'A3']['A2' 'A4']['A3' 'A1'] ['A3' 'A2'] ['A3' 'A4']['A4' 'A1'] ['A4' 'A2']['A4' 'A3']]

I need
[['A1' 'A2']['A1' 'A3']['A1' 'A4']['A2' 'A3']['A2' 'A4'] ['A3' 'A4']

    import numpy as np
    
    x = ("A1", "A2", "A3", "A4")
    
    arr = []
    for i in range(0, len(x)):
        for j in range(0, len(x)):
            if x[i] != x[j]:
                arr.append((x[i], x[j]))
    
    mylist = np.unique(arr, axis=0)
    print(mylist)

how to do it?

Thanks in advance.

CodePudding user response:

Python's standard library has a function that does exactly this, itertools.combinations.

from itertools import combinations

print( list(combinations(['A1', 'A2', 'A3', 'A4'], 2)) )
# [('A1', 'A2'), ('A1', 'A3'), ('A1', 'A4'), ('A2', 'A3'), ('A2', 'A4'), ('A3', 'A4')]

You can also write your own, using nested loops to iterate on the array:

def all_pairs(arr):
    for i, x in enumerate(arr):
        for y in arr[i 1:]:
            yield (x, y)

print( list(all_pairs(['A1', 'A2', 'A3', 'A4'])) )
# [('A1', 'A2'), ('A1', 'A3'), ('A1', 'A4'), ('A2', 'A3'), ('A2', 'A4'), ('A3', 'A4')]

CodePudding user response:

A simple if statement to check if the tuple already exists should be all you need:

    import numpy as np
    
    x = ("A1", "A2", "A3", "A4")
    
    arr = []
    for i in range(0, len(x)):
        for j in range(0, len(x)):
            if x[i] != x[j]:
                if not (x[j], x[i]) in arr: // If the pair already exists, it would be the
                                            //flipped version of it
                    arr.append((x[i], x[j]))
    
    mylist = np.unique(arr, axis=0)
    print(mylist)
  • Related