본문 바로가기
HackerRank Algorithm

[HackerRank] 26. forming a magic square

by KIha_Jung 2020. 4. 7.

def CreateMagicSquare():
    # 3x3 magic square 모든 경우의 수 생성
    num = set(range(1, 10))
    group = []
    magic_square = []
    
    for a in range(1, 10):
        for b in range(1, 10):
            for c in range(1, 10):
                if (a + b + c == 15) & (a != b) & (a != c) & (b != c):
                    temp = [a, b, c]
                    group.append(temp)
    
    for i in range(len(group)):
        for j in range(len(group)):
            for k in range(len(group)):
                if set(group[i] + group[j] + group[k]) == num:
                    temp_a = group[i][0] + group[j][0] + group[k][0]
                    temp_b = group[i][1] + group[j][1] + group[k][1]
                    temp_c = group[i][2] + group[j][2] + group[k][2]
                    temp_d = group[i][0] + group[j][1] + group[k][2]
                    temp_e = group[i][2] + group[j][1] + group[k][0]
                    if temp_a == 15 & temp_b == 15 & temp_c == 15 & temp_d == 15 & temp_e == 15:
                        temp = []
                        temp.append(group[i])
                        temp.append(group[j])
                        temp.append(group[k])
                        magic_square.append(temp)
    return magic_square

def formingMagicSquare(s):
    magic_square = CreateMagicSquare()
    cost_list = []
    cost = 0
    for n in range(len(magic_square)):   
        for i in range(3):
            for j in range(3):
                cost += abs(magic_square[n][i][j] - s[i][j])
        cost_list.append(cost)
        cost = 0
    return min(cost_list)
      
if __name__ == '__main__':
    s = []
    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))

    result = formingMagicSquare(s)
    print(result)

'HackerRank Algorithm' 카테고리의 다른 글

[HackerRank] 27. Picking Numbers  (0) 2020.04.07
[HackerRank] 25. Cats and Mouse  (0) 2020.04.07
[HackerRank] 24. Electronics shop  (0) 2020.04.07
[HackerRank] 23. Apple and orange  (0) 2020.04.07
[HackerRank] 22. Between Two Sets  (0) 2020.04.07

댓글