본문 바로가기
IT/코딩테스트, 알고리즘, 파이썬, C, C++, C#, JAVA 등...

알고리즘 - 사다리만들기

by G0Yang 2019. 5. 1.

문제 출처 : https://kldp.org/comment/310205#comment-310205

 

[난이도 : 상] 
[문제4] n개의 엔트리를 갖는 사다리의 아랫부분 번호를 입력받아서, 윗부분의 번호가 
사다리를 타고 아랫부분의 자기 번호에 도달할 수 있도록 사다리를 구성해 
보시오. (단, n은 10이하의 자연수이고, 아랫부분의 번호는 1부터 n까지의 수의 
임의순열(random permutation)중 하나를 입력받고, 윗부분의 번호는 
좌측으로부터 1번, 2번... n번 순으로 배열되어 있다. )

예) 
Please insert the number of entries: 4 
Insert bottom entries: 3 2 4 1 <--- 아래부분의 숫자 입력 
Output: 
1 2 3 4 
|-| | | 
| |-| | 
| | |-| <--- 이 부부을 만들어 내면 된다. 
|-| | | 
3 2 4 1

import random, copy 

while True: 
    point = random.randint(3, 10) 

    destination = [] 

    while not len(destination) == point: 
        tmp = random.randint(1, point) 
        if tmp in destination: 
            continue 
        else: 
            destination.append(tmp) 


    cngPoint = [] 
    sort = sorted(destination) 
     
    if not sort == destination: 
        break 

tmp_d = copy.deepcopy(destination) 

while not tmp_d == sort: 
    for i in range(0, len(tmp_d)-1): 
        if tmp_d[i] > tmp_d[i+1]: 
            a = tmp_d[i] 
            tmp_d[i] = tmp_d[i+1] 
            tmp_d[i+1] = a 
            cngPoint.append(i) 

rev_cng = list(reversed(cngPoint)) 

for i in sort: 
    print(i, "", end="") 
print() 

for i in range(0, len(cngPoint)): 
    for j in range(0, point): 
        print("l", end="") 
        if rev_cng[0] == j: 
            print("-", end="") 
        else: 
            print(" ", end="") 
    rev_cng.pop(0) 
    print() 


for i in destination: 
    print(i, "", end="") 



댓글