본문 바로가기
Coding/Swift

Playgrounds 코딩 배우기 1 > 알고리즘 > 오른손 법칙

Swift Playgrounds 코딩 배우기 1 > 알고리즘 > 오른손 법칙

 

제시한 의사코드_

navigate around wall {
	if blocked to the right {
     move forward
    } else {
    	turn right
        move forward
    }
}

while not on closed switch {
 navigate around wall
 if on gem {
 	collect gem
    turn around
 }
}
toggle switch

 

 

내가 작성한 코드_

func navigateAroundWall() {
    if isBlockedRight {
        moveForward()
    }  else {
        turnRight()
        moveForward()
    }
}
func collectOrToggle() {
    if isOnGem {
        collectGem()
    } else if isOnClosedSwitch {
        toggleSwitch()
    }
}

while !isOnOpenSwitch {
    while !isOnGem && !isOnClosedSwitch {
        navigateAroundWall()
    }
    collectOrToggle()
    turnLeft()
    turnLeft()
}

 

프로그램에서 제시한 코드_

func navigateAroundWall() {
    if isBlockedRight {
        moveForward()
    }  else {
        turnRight()
        moveForward()
    }
}
    
while !isOnClosedSwitch {
    navigateAroundWall()
    if isOnGem {
        collectGem()
        turnLeft()
        turnLeft()
    }
}
toggleSwitch()

 

분석_

나는 쓸데없이 중첩반복문을 사용하여 실행시간을 늘렸다. 좋지 않은 판단이었다. 

의사코드와 프로그램에서 제시한 코드를 비교해보면 나는 의사코드에서 의도한대로 코드를 짜지 않았음을 알 수 있다. 

 

다음에는..._

의사코드를 좀 더 따라보자...고 생각합니다