> For the complete documentation index, see [llms.txt](https://heunnajo.gitbook.io/algorithms-problem-solving-skills/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heunnajo.gitbook.io/algorithms-problem-solving-skills/implementation/gearwheel.md).

# GearWheel

**회전 순서, 알고리(재귀함수 이용)**

1. 왼쪽/오른쪽 톱니바퀴 먼저 회전
2. idx번째 톱니바퀴 회전

**틀린 이유**

1. 시계방향으로 회전할 &#xB54C;**(5시간의 교훈)**\
   i번째 값은 i-1값에서 온다. 그런데 반복문을 i가 증가하는 반복문으로 해버리면 새로 갱신된 i번째값이 i+1번째 값으로 들어가게 된다. 그렇기 때문에 감소하는 반복문을 사용하여 뒤에서부터 값을 갱신시켜준다!

```java
if(dir == 1) {
			int tmp = wheels[idx][7];
			for(int i=7;i>=1;i--) {
				wheels[idx][i] = wheels[idx][i-1];
			}
			wheels[idx][0] = tmp;
		}
```

2\. idx-1,idx+1번째 톱니바퀴가 회전하는 부분 한번만 구현했다.\
\=>0번째 톱니바퀴를 회전한다고 하자. 그러면 1번째,2번째,3번째 톱니바퀴 모두 비교해봐야한다! 그렇기 때문에 1회성으로 1번 구현하는 게 아니라 **idx를 기준으**로 **왼쪽 오른쪽**, **idx-1기준**으로 **왼쪽**, **idx+1기준**으로 **오른쪽**을 확인해봐야한다!!!!!\
\=>재귀함수로 구현할 수 있다! 매개변수로는 (톱니바퀴인덱스, 방향, 왼쪽(1) or 오른쪽(2))를 넘겨준다.\
idx기준 왼쪽 톱니바퀴 : go(idx-1,-dir,1) : 왼쪽 톱니바퀴니까 왼쪽 톱니바퀴에 대해 회전 여부 확인,회전시켜준다.\
idx기준 오른쪽 톱니바퀴 : go(idx+1,-dir,2) : 오른쪽 톱니바퀴니까 오른쪽 톱니바퀴에 대해 회전 여부 확인,회전시켜준다.

```java
if(d==0) {//초기.
			//1.왼쪽톱니바퀴
			if(idx-1>=0 && wheels[idx-1][2] != wheels[idx][6]) {
				go(idx-1,-dir,1);
			}
			if(idx+1<4 && wheels[idx][2] != wheels[idx+1][6]) {
				go(idx+1,-dir,2);
			}
		}
		//왼쪽 톱니바퀴=>왼쪽 톱니바퀴의 왼쪽 톱니바퀴도 회전해야하는지 확인하고 회전해준다!
		else if(d==1) {
			if(idx-1>=0 && wheels[idx-1][2] != wheels[idx][6]) {
				go(idx-1,-dir,1);
			}
		}
		else if(d==2) {
			if(idx+1<4 && wheels[idx][2] != wheels[idx+1][6]) {
				go(idx+1,-dir,2);
			}
		}
```

배운 점

구현 문제는 복잡한 구현들을 해야하는 경우가 많으니까 동작 별로 함수를 구현하는 것도 좋고, 하나의 함수로 구현한다면 최대한 명확하게 구현하도록 하자. 깔끔한 클린 코드들을 보고 배우자.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/algorithms-problem-solving-skills/implementation/gearwheel.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
