๐Ÿ“šSTUDY/Etc

๊ทธ๋ ˆ์ด ์ฝ”๋“œ Gray code?

ํ•ด๋Š”์„  2020. 2. 28. 01:22

๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ž‘ ์—ฐ์†๋œ ์ˆ˜๋ฅผ ํ•œ ๋น„ํŠธ๋งŒ ๋‹ค๋ฅด๊ฒŒ ์ธ์ฝ”๋”ฉ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

์ฆ‰, ์ˆ˜๊ฐ€ ์ฆ๊ฐ€ํ•  ๋•Œ, ์–ธ์ œ๊ฐ€ 1๊ฐœ ๋น„ํŠธ๋งŒ ๋ฐ”๋€๋‹ค๊ณ  ๋ณด๋ฉด ๋œ๋‹ค. 

 

  ์ด์ง„ ๊ทธ๋ ˆ์ด
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
5 101 111
6 110 101
7 111 100

๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

์šฐ์„  1๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์“ด๋‹ค.

0

1

 

๊ทธ๋ฆฌ๊ณ  ๊ทธ ์•„๋ž˜ ์—ญ์ˆœ์œผ๋กœ ๋‹ค์‹œ 1๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์“ด๋‹ค.

 

0

1

1

0

 

์ œ์ˆœ์œผ๋กœ ์“ด ๋น„ํŠธ ์•ž์—๋Š” 0์„, ์—ญ์ˆœ์œผ๋กœ ์“ด ๋น„ํŠธ ์•ž์—๋Š” 1์„ ๋ถ™์—ฌ์ค€๋‹ค.

 

00

01

11

10

 

์ด๋ ‡๊ฒŒ n๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ n+1๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

์‰ฝ๊ฒŒ ์ •๋ฆฌํ•˜์ž๋ฉด n๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์ ๊ณ  ์•ž์— 0์„ ๋ถ™์ธ ๊ฒƒ๊ณผ, n๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ ๊ณ  ์•ž์— 1์„ ๋ถ™์ธ ๊ฒƒ์„ ์ด์œผ๋ฉด n+1๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๊ฐ€ ๋œ๋‹ค.

 

์ฝ”๋“œ๋Š” ์•„์ง ์ดํ•ด ๋ชปํ•˜๊ฒ ๋‹คใ… 

 

#include <stdio.h>
void print_gray_reverse(int code[], int n, int index);
 // ๊ทธ๋ ˆ์ด ์ฝ”๋“œ : ์—ฐ์†๋œ ์ˆ˜๋ฅผ ํ•œ ๋น„ํŠธ๋งŒ ๋‹ค๋ฅด๊ฒŒ ์ธ์ฝ”๋”ฉ ํ•˜๋Š” ๋ฐฉ๋ฒ•.
//์ฆ‰, ๋‹ค์Œ ์ˆ˜๋กœ ๋„˜์–ด๊ฐˆ ๋•Œ ์–ธ์ œ๋‚˜ 1๊ฐœ ๋น„ํŠธ๋งŒ ๋ฐ”๋€๋‹ค!!

//n์„ ์ž…๋ ฅ ๋ฐ›์•„์„œ n๋น„ํŠธ ๊ทธ๋ ˆ์ด ์ฝ”๋“œ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ.

void print_code(int code[], int len) {
	for (int i = 0; i < len; i++) {
		printf("%d", code[i]);
	}
	printf("\n");
}

void print_gray(int* code, int n, int index) {
	if (n == index) { //๋ชฉํ‘œ์น˜์— ๋„๋‹ฌํ•˜๋ฉด ์ฝ”๋“œ ์ถœ๋ ฅ
		print_code(code, n);
		return;
	}
	//0๋น„ํŠธ ์ž๋ฆฌ ์ˆ˜ ๋ถ€ํ„ฐ ์‹œ์ž‘!
	code[index] = 0;
	print_gray(code, n, index + 1);
	code[index] = 1;
	print_gray_reverse(code, n, index + 1);

}

void print_gray_reverse(int code[], int n, int index) {
	if (index == n) {
		print_code(code, n);
		return;
	}

	code[index] = 1;
	print_gray(code, n, index + 1);
	code[index] = 0;
	print_gray_reverse(code, n, index + 1);

}


int main(void) {
	int code[20], n;
	scanf("%d", &n); //n์ž๋ฆฌ์ˆ˜(๋น„ํŠธ)

	print_gray(code, n, 0);
}

 


Reference

https://johngrib.github.io/wiki/gray-code/

๋ฌธ์ œ๋กœ ํ’€์–ด๋ณด๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜(ํ™ฉ์ธ์šฑ, ๊น€์šฉํ˜)