[Exam_rang02] Union

Cadet_42·2021년 7월 22일
0

Exam_rang02

목록 보기
1/2
post-thumbnail

Ecole42에 입학한 이후에 처음으로 시험을 치게 되는데, 시험 대비를 하면서 코딩 과정을 정리해보았다. 참고로, 시험을 칠 때는 norminette을 생각하지 않아도 된다.

Union Subject 이해

  • Union은, .\a.out 을 제외한 첫번째 argument의 글자를 출력하고, 첫번째 argument 안에 반복되는 문자가 있으면 반복하지 않는다.
  • 첫번째 argument에 없는 문자가 두번째 argument에 있다면, 그 문자를 함께 출력한다.
  • 문제와 예시는 하기와 같다.
.\a.out "first_argument", "second_argument"
Assignment name  : union
Expected files   : union.c
Allowed functions: write
--------------------------------------------------------------------------------

Write a program that takes two strings and displays, without doubles, the
characters that appear in either one of the strings.

The display will be in the order characters appear in the command line, and
will be followed by a \n.

If the number of arguments is not 2, the program displays \n.

Example:

$>./union zpadinton "paqefwtdjetyiytjneytjoeyjnejeyj" | cat -e
zpadintoqefwjy$
$>./union ddf6vewg64f gtwthgdwthdwfteewhrtag6h4ffdhsd | cat -e
df6vewg4thras$
$>./union "rien" "cette phrase ne cache rien" | cat -e
rienct phas$
$>./union | cat -e
$
$>
$>./union "rien" | cat -e
$
$>

Union 코딩 단계

1. [Intro] argument들을 연결하기

  • 결국, 두 문자열을 출력해야 하는 것이기 때문에, ./a.out 을 제외한 첫번째 argument와 두번째 argument을 연결하여, 함수 구현을 통하여 어떻게 접근해야 하는지 생각해보았다.

  • 프로그램을 작성해야 하는것이기 때문에, main 함수에 직접 int ac, char *av[]를 넣어 함수를 구현 하기로 하였다.

#include <unistd.h>

int main(int ac, char*av[])
{
	int	i;

	if (ac == 3)
	{
		i = 0; //==> 첫번째 함수를 읽고 출력한다.
		while (av[1][i])
		{
			write(1, &av[1][i],1);
			i++;
		}
		i = 0; // ==> 두번째 함수를 읽고 출력하며, 라인을 줄이기 위해 다시 i=0 함으로써, 두번째 함수를 읽고 출력한다.
		while (av[2][i])
		{
			write(1, &av[2][i], 1);
			i++;
		}
	}
	write(1, "\n", 1);
	return (0);
}

2. [Process] tab을 이용하여 union 함수 구현

💡 함수 구현을 위한 기본 개념

  • static variables 은 해당 파일내에서의 함수내에서만 호출되고 쓰인다는 용도도 있으며, 항상 default 값으로 0 을 가진다.

  • Static : If your array is declared as static or is global, all the elements in the array already have default value 0.

  • static int tab[256]은 256개의 아스키 문자를 담은 tab이며, default 이므로 tab안은 0만이 존재한다.

❗️❗️❗️ 하기 두개는 완전히 다른 개념이다. ❗️❗️❗️
static int tab[256] ==> tab안에 있는 값들은 모두 0 이다.
int tab[256] ={0} ==> tab[256] 안의 첫 값은 0 으로 시작한다.

  • 💡 ascii 문자의 총 개수가 256인 이유?
    ascii is a user-written package, developed by Adrian Mande that merely returns numbers of ASCII characters in SMCL markup language. ASCII (pronunced /askee/), abbreviated from "American Standard Code for Information Interchange" which is a is a character-encoding scheme. The complete list of ascii table is printed below.

💡 함수 로직

간단히 말하면, 출력가능한 문자의 아스키 코드를 static int tab[256]( default 값: 0) 안에 담고, 조건에 해당하는 문자를 발견했으면, 0 을 1로 바꾸고, 이미 1로 바꾼 문자가 다시 나오면, 0으로 남겨두고 argument이 끝날때 까지 while loop을 통하여 반복한다.

  • static int tab[256] 이미 tab 안에는 256개의 아스키 문자가 0으로 표시 되어 있다.
  • (tab[(int)av[1][i]] == 0) : tab을 이용하여, argument의 문자를 하나하나씩 확인하는 과정이다. (on va tester le cas, quand le char n'a pas encore été vu (=switch off)) 해당 문자가 보여지지 않았을경우, if loop안에 들어간다.
  • tab[(int)av[1][i]] = 1 그리고 1 (= switch on) 을 써주고 if loop 을 나온다.
  • i++ 를 해주면서, 상기와 같은 방법으로 계속 테스트 해준다.
  • 마찬 가지로 av[2][i]에 적용 시켜 준다.
#include <unistd.h>

int	main(int ac, char*av[])
{
	int			i;
	static int	tab[256];

	if (ac == 3)
	{
		i = 0;
		while (av[1][i])
		{
			if (tab[(int)av[1][i]] == 0)
			{
				write(1, &av[1][i], 1);
				tab[(int)av[1][i]] = 1;
			}
			i++;
		}
		i = 0;
		while (av[2][i])
		{
			if (tab[(int)av[2][i]] == 0)
			{
				write(1, &av[2][i], 1);
				tab[(int)av[2][i]] = 1;
			}
			i++;
		}
	}
	write(1, "\n", 1);
	return (0);
}

3. [Final] Optimize the code

2번의 코드중에 반복되는 코드의 부분이 있어서, 반복되는 부분을 optimize 해주었다.

  • int j = 1를 2번 반복해주는 loop을 만들어주었다. Why? ./a.out을 제외한 first argument와 second argument의 문자열을 각각 확인해줘야 하므로.
#include <unistd.h>

int	main(int ac, char*av[])
{
	int			i;
	int			j;
	static int	tab[256];

	if (ac == 3)
	{
		j = 1;
		while (j <= 2)
		{
			i = 0;
			while (av[j][i])
			{
				if (tab[(int)av[j][i]] == 0)
				{
					write(1, &av[j][i], 1);
					tab[(int)av[j][i]] = 1;
				}
				i++;
			}
			j++;
		}
	}
	write(1, "\n", 1);
	return (0);
}

출처 :
1. ascii code
http://www.haghish.com/statistics/stata-blog/stata-programming/ascii_characters_mobile.php

profile
안녕하세요! 개발공부를 하고 있습니다. 감사히 배우겠습니다. ;)

0개의 댓글