2017-11-17 6 views
3

개체 사이의 거리를 저장하는 데 사용한 목록의 목록이 있습니다.NxN 배열의 행 및 열에서 가장 낮은 값을 결정합니다.

표는 다음과 같은 :

+----------+----------+----------+----------+----------+ 
|   | Object_A | Object_B | Object_C | Object_D | 
+----------+----------+----------+----------+----------+ 
| Entity_E |  2 |  3 |  6 |  1 | 
+----------+----------+----------+----------+----------+ 
| Entity_F |  3 |  4 |  7 |  2 | 
+----------+----------+----------+----------+----------+ 
| Entity_G |  9 |  1 |  2 |  3 | 
+----------+----------+----------+----------+----------+ 

숫자는 행 & 열 머리글 사이의 거리를 나타냅니다. 다음과 같이

대략 계산 하였다
entites = [Entity_E, Entity_F, Entity_G] 
objects = [Object_A, Object_B, Object_C, Obhect_D] 
distances = [] 

for object in objects: 

    distanceEntry = [] 

    for entity in entities: 
     distance = getDistance(entity, object) 

     distanceEntry.append(distance) 
    distances.append(distanceEntry) 

대략 위의 표에있는 정보를 나에게 주었다.

기본적으로 각 엔티티에 가장 가까운 개체를 찾습니다 (또는 그 반대). 각 객체 또는 엔티티는 다른 객체 또는 엔티티와 만 일치 할 수 있으며 근접성을 기반으로해야합니다.

내가 지금까지 해본 방법은 거리의 크기로 중첩 목록을 정렬하는 것입니다 (전체 코드에서 각 객체가 각 거리와 관련되어 있는지를 결정하는 방법이 있습니다).

그래서, 나는 다음과 같은 연결을 만들 것이라고 일에 : 그것은 두 번 Object_D를 연결하기 때문에

+----------+----------+----------+ 
| Entity | Object | Distance | 
+----------+----------+----------+ 
| Entity_E | Object_D |  1 | 
+----------+----------+----------+ 
| Entity_F | Object_D |  2 | 
+----------+----------+----------+ 
| Entity_G | Object_B |  1 | 
+----------+----------+----------+ 

이 올바르지 않습니다.

협회는해야한다 :

+----------+----------+----------+ 
| Entity | Object | Distance | 
+----------+----------+----------+ 
| Entity_E | Object_D |  1 | 
+----------+----------+----------+ 
| Entity_F | Object_A |  3 | 
+----------+----------+----------+ 
| Entity_G | Object_B |  1 | 
+----------+----------+----------+ 

이것은 내가 고민하고있는 곳입니다 -이에 대한 코드 로직에 가장 좋은 방법을 알아낼 수 없습니다.

Entity_E가 Object_D에 더 가깝기 때문에 연관을 가져야합니다. 그래서, Entity_F에 대해, 나는 두 번째로 가까운 것을 취할 필요가있다.

나는 어떤 객체가 이미 할당되어 있는지를 기록하거나, 각 열의 최소값과 일치하는 것을하려고 시도하는 것에 대해 생각하고있었습니다.하지만 모든 것이 문제가되는 것 같습니다.

이 계산을 수행하는 데 사용할 수있는 행렬 연산 또는 일종의 수학 연산이 있습니까?

모든 조언을 주시면 감사하겠습니다.

편집 - 전체 코드를 추가 :

# Create an array that stores the distances between each label and symbol. Only calculate the distance for label that 
# are "in front" of the symbol. 
# Example Table: 
# +---------------+--------------+--------------+--------------+--------------+ 
# |    | Label_1 | Label_2 | Label_3 | Label_4 | 
# +---------------+--------------+--------------+--------------+--------------+ 
# | Measurement_1 |  2  |  3  | Not_in_front |  1  | 
# +---------------+--------------+--------------+--------------+--------------+ 
# | Measurement_2 |  3  |  4  |  1  | Not_in_front | 
# +---------------+--------------+--------------+--------------+--------------+ 
# | Measurement_3 | Not_in_front | Not_in_front |  2  |  1  | 
# +---------------+--------------+--------------+--------------+--------------+ 

# Data Structures: 
# measurementsDictionary = {['Type', 'Handle', 'X-Coord', 'Y-Coord', 'Z-Coord', 'Rotation', 'True Strike']} 
# dipsDictionary = {['Handle', 'Text', 'Unit', 'X-Coord', 'Y-Coord', 'Z-Coord']} 

#The two functions below grab the information from a csv-like file. 
measurementsDictionary = getMeasurementsInformationFromFile() 
dipsDictionary = getDipsInformationFromFile() 


exportHeaders = [" "] 
exportArray = [] 

for measurementSymbol in measurementsDictionary: 

    measurementEntry = measurementsDictionary[measurementSymbol] 
    measurementCoord = [measurementEntry[2], measurementEntry[3]] 
    measurementDistance = [] 
    measurementDistance.append(measurementEntry[1]) 
    measurementCartesianAngle = getCartesianAngle(measurementEntry[6]) 
    measurementLineEquation = generateLineEquation(measurementCoord,measurementCartesianAngle) 

    for dip in dipsDictionary: 
     dipEntry = dipsDictionary[dip] 
     dipCoord = [dipEntry[3],dipEntry[4]] 
     isPointInFrontOfLineTest = isPointInFrontOfLine(measurementCartesianAngle, measurementLineEquation, dipCoord) 

     if isPointInFrontOfLineTest == 1: 
      measurementSymbolDistance = calculateDistance(measurementCoord, dipCoord) 
      # string = dipEntry[0] +":" + str(measurementSymbolDistance) 
      # measurementDistance.append(string) 
      measurementDistance.append(measurementSymbolDistance) 
     elif isPointInFrontOfLineTest == 0: 
      string = "" 
      measurementDistance.append(string) 
    exportArray.append(measurementDistance) 

for dip in dipsDictionary: 
    dipEntry = dipsDictionary[dip] 
    exportHeaders.append(dipEntry[0]) 

exportedArray = [exportHeaders] + exportArray 
export = np.array(exportedArray) 
np.savetxt("exportArray2.csv", export, fmt='%5s', delimiter=",") 
print(exportHeaders) 
+0

전체 코드를 추가 할 수 있습니까? – sera

+0

가능한 한 많은 코드를 편집하고 추가했습니다! – labourday

답변

1

내가 다시 PE345이 잠시 유사한 문제를 해결하기 위해 몇 가지 코드를했다. 내 자신의 배열을 사용하려고합니다 :

[[1,2,3], 
[4,5,6], 
[7,8,9]] 

원하는 것은 특정 요소를 선택하는 비용입니다. 행을 선택하는 비용, 열을 선택하는 비용을 추가 한 다음 요소 자체를 선택하는 비용을 뺀 값을 찾아서이 작업을 수행하십시오. 따라서 배열에서 [0][0] 요소를 선택하는 비용은 (1+2+3)+(1+4+7)-3*(1)입니다. 나는 행 0을 합산하고, 열 0을 합친 다음, 요소 자체를 빼 냈습니다.

이제 각 요소를 선택하는 데 드는 비용이 있습니다. 비용이 가장 많이 드는 요소를 찾습니다. 그리드에서 가장 낮은 값이됩니다.선택하고 행이나 열의 다른 값을 선택할 수 없도록하십시오. 모든 행과 열의 값이 선택 될 때까지 반복하십시오.

내 프로젝트의 소스 코드는 다음과 같습니다. 가장 낮은 값이 아닌 가장 높은 값을 찾습니다.

from random import randint 
from itertools import permutations 
def make_a_grid(radius=5,min_val=0,max_val=999): 
    """Return a radius x radius grid of numbers ranging from min_val to max_val. 
    Syntax: make_a_grid(radius=5,min_val=0,max_val=999 
    """ 
    return [[randint(min_val,max_val) for i in xrange(radius)] for j in xrange(radius)] 
def print_grid(grid,rjustify = 4): 
    """Print a n x m grid of numbers, justified to a column. 
    Syntax: print_grid(grid,rjustify = 4) 
    """ 
    for i in grid: 
    outstr = '' 
    for j in i: 
     outstr += str(j).rjust(rjustify) 
    print outstr 
def brute_search(grid): 
    """Brute force a grid to find the maximum sum in the grid.""" 
    mx_sum = 0 
    for r in permutations('',5): 
    mx_sum = max(sum([grid[i][int(r[i])] for i in xrange(5)]),mx_sum) 
    return mx_sum 
def choose(initial_grid,row,col): 
    """Return a grid with a given row and column zeroed except where they intersect.""" 
    grid = [sub[:] for sub in initial_grid] #We don't actually want to alter initial_grid 
    Special_value = grid[row][col] #This is where they intersect. 
    grid[row] = [0]*len(grid[row]) #zeroes the row. 
    for i in xrange(len(grid)): 
    grid[i][col] = 0 
    grid[row][col] = Special_value 
    print_grid(grid) 
    return grid 
def smart_solve(grid): 
    """Solve the grid intelligently. 
    """ 
    rowsum = [sum(row) for row in grid] #This is the cost for any element in a given row. 
    print rowsum 
    colsum = [sum(row) for row in [[grid[i][j] for i in xrange(len(grid))] for j in xrange(len(grid[0]))]] #Cost for any element in a given column 
    print colsum,"\n" 
    total_cost = [map(lambda x: x+i,rowsum) for i in colsum] #This adds rowsum and colsum together, yielding the cost at a given index. 
    print_grid(total_cost,5) 
    print "\n" 
    #Total_cost has a flaw: It counts the value of the cell twice. It needs to count it -1 times, subtracting its value from the cost. 
    for i in xrange(len(grid)): #For each row 
    for j in xrange(len(grid[0])): #For each column 
     total_cost[i][j] -= 3*(grid[i][j]) #Remove the double addition and subtract once. 
    ###Can I turn ^^that into a list comprehension? Maybe use zip or something?### 
    print_grid(total_cost,5) 
    return total_cost 
def min_value(grid): 
    """return the minimum value (And it's index) such that value>0. 
    Output is: (value,col,row)""" 
    min_value,row,col = grid[0][0],0,0 
    for row_index,check_row in enumerate(grid): 
    for col_index,check_val in enumerate(check_row): 
     #print "Min_value: %d\n Check_Val: %d\n Location: (%d,%d)"%(min_value,check_val,row_index,col_index) 
     if min_value>check_val>0: 
     min_value = check_val 
     row = row_index 
     col = col_index 
    return (min_value,row,col) 
+0

대단히 고마워요! 이것은 많은 의미가 있습니다. 그러나, 나는 두 가지 후속 질문을 가지고있다. 1. 왜 당신은 3 * (1)을 뺐습니까? 1은 [0] [0]에있는 배열의 값이라고 가정합니다. 2. '요소 선택 비용'에 대한 아이디어를 어떻게 생각해 냈습니까? 더 익숙해지기 위해 연구 할 수있는 자료가 있습니까? 다시 한 번 감사드립니다! – labourday

+0

나는 경제학 교과서 이외의 다른 출처를 정말로 인용 할 수 없다. 기회 비용의 한 사례입니다. 저는 두 가지 이유로 세 번 빼고 있습니다 : 하나는 행과 열을 가져 왔을 때 값을 두 번 더했습니다. 둘째, 무언가를하는 비용을 원할 때, 이익은 비용을 상쇄하므로 가치를 빼는 것입니다. –