수학 & 코딩

코딩 문제 - 2302161617

WEBJU 2023. 2. 16. 16:31
728x90

Q : 2차원 평면에서 임의 점들을 모두 연결하여 점을 꼭지점으로 하는 폐곡면인 다각형을 구하는 파이썬 코드는 ?

 

A : 위와 같은 문제로 챗GPT에게 3일간 질문하였으나 돌아오는 대답의 코드는 모든 점들을 포함하는 코드만을 제시하였다. 그래서 직접 파이썬으로 아래와 같이 코딩하여 테스트해 보았다.

 

결과는 임의 점 8개까지는 최적의 폐곡면 1개 이상은 구하였다. 그 이상을 구하는 것은 테스트 시간이 오려 걸려 계속 테스트하는 중이다. 이에, 아래의 코드를 참조하기 바랍니다. 

 

이 코드의 특징은 어떠한 관계 함수를 사용한 것이 아니라 random.shuffl를 적용하여 그 점들의 조합으로 연결하고 그 연결된 선들의 길이, 아래의 그림에서는 "녹색"의 픽셀점들이 적은 쪽으로 내려가도록 한 결과를 보이도록 프로그램하였다.

 

따라서, 그 함수와 관계식은 없으며 무작위 학습과 같은 원리를 이용하였다. 이 처럼 만들어진 폐곡면 경계 선에 대한 관계는 향후 인공지능의 분류하는 범위를 자동적으로 만들도록 하는데 도움을 줄 것으로 생각됩니다.

 

코딩 결과에 따른 그래프는 아래와 같다.

이에 대한 파이썬 코드는 아래와 같다. 이 그래 결과는 pygame screen에서 구현하였다.

import pygame, sys
from pygame.locals import *
import time
import random
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import Delaunay


def points_draw(x, y):
    global dis_sum
    points = list(range(0, len(x)))
    pp = []
    pp.append(points)
    done = True
   
    while done:
        random.shuffle(points)
        if np.sum(pp == points) < 1:
            xx = []
            yy = []
            screen.fill('#000000')
            for i in range(len(points)):
                if i < len(x)-1:
                    pygame.draw.line(screen, '#00FF00', [x[points[i]], y[points[i]]], [x[points[i+1]], y[points[i+1]]], 1)
                elif i == len(x)-1:
                    pygame.draw.line(screen, '#00FF00', [x[points[i]], y[points[i]]], [x[points[0]], y[points[0]]], 1)
                xx.append(x[points[i]])
                yy.append(y[points[i]])
           
            green_pp = 0
            for i in range(1, 599):
                for j in range(1, 599):
                    r0, g0, b0, c0 = pygame.Surface.get_at(screen, (i, j))
                    if g0 > 0:
                        green_pp += 1
           
            if dis_sum > green_pp:
                dis_sum = green_pp
                print(dis_sum)
                done = False
                break
        pp.append(points)
    return xx, yy

pygame.init()

dis_width = 600
dis_height = 600
N = 8

screen = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption(str(N)+' points Simulation')
font = pygame.font.Font("C:\Windows\Fonts\HYSANB.ttf", 20)

FPS = 10
clock = pygame.time.Clock()

global dis_sum
dis_sum = 1000000

g_pp = 1000000
x = []
y = []
for i in range(N):
    x.append(random.randint(5, 595))
    y.append(random.randint(5, 595))

while True: # the main game loop
    screen.fill('#000000')
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
   
    x, y = points_draw(x, y)
   
    for i in range(len(x)):
        pygame.draw.circle(screen, '#FF0000', [x[i], y[i]], 3)
 
    pygame.display.update()    
    #clock.tick(FPS)
    #time.sleep(3)

pygame.quit()
728x90