1. 이름이 없는 동물의 아이디

SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NULL

2. 이름이 있는 동물의 아이디

SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NOT NULL

3. NULL 처리하기

SELECT ANIMAL_TYPE, IFNULL(NAME, "No name") AS NAME, SEX_UPON_INTAKE FROM ANIMAL_INS

 

 

1. 고양이와 개는 몇 마리 있을까

SELECT ANIMAL_TYPE, count(ANIMAL_ID) as count from ANIMAL_INS group by ANIMAL_TYPE order by ANIMAL_TYPE;

2. 동명 동물 수 찾기

SELECT NAME, count(NAME) as COUNT FROM ANIMAL_INS group by NAME
having NAME is not null and count(NAME) >=2 order by NAME;

3. 입양 시각 구하기(1)

SELECT HOUR(DATETIME) AS HOUR, COUNT(HOUR(DATETIME)) AS COUNT
FROM ANIMAL_OUTS
GROUP BY HOUR
HAVING HOUR BETWEEN 9 AND 19
-- HAVING HOUR >= 9 AND HOUR <= 19 
ORDER BY HOUR

4. 입양 시각 구하기(2)

WITH RECURSIVE NUM AS (
    SELECT 0 AS HOUR
    UNION ALL
    SELECT HOUR+1 FROM NUM WHERE HOUR<23
)

SELECT A.HOUR, IFNULL(B.COUNT, 0) AS COUNT
FROM NUM A
LEFT JOIN (
    SELECT HOUR(DATETIME) AS HOUR, COUNT(ANIMAL_ID) AS COUNT
    FROM ANIMAL_OUTS
    GROUP BY 1
) AS B ON A.HOUR=B.HOUR

1. 최댓값 구하기

SELECT DATETIME AS'시간' FROM ANIMAL_INS ORDER BY DATETIME DESC LIMIT 1;

2. 최솟값 구하기

SELECT DATETIME FROM ANIMAL_INS ORDER BY DATETIME LIMIT 1

3. 동물 수 구하기

/* COUNT사용시 괄호 주의 */
SELECT COUNT (ANIMAL_ID) AS count FROM ANIMAL_INS

4. 중복 제거하기

-- DISTINCT 중복제거
SELECT COUNT(DISTINCT NAME) FROM ANIMAL_INS WHERE NAME IS NOT NULL

1. 모든 레코드 조회하기

SELECT * from ANIMAL_INS order by ANIMAL_ID;

2. 역순 정렬하기

SELECT NAME, DATETIME FROM ANIMAL_INS ORDER BY ANIMAL_ID DESC;

3. 아픈 동물 찾기

SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION='Sick';

4. 어린 동물 찾기

SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION != 'Aged' ORDER BY ANIMAL_ID;

5. 동물의 아이디와 이름

SELECT ANIMAL_ID, NAME FROM ANIMAL_INS ORDER BY ANIMAL_ID;

6. 여러 기준으로 정렬하기

SELECT ANIMAL_ID, NAME, DATETIME FROM ANIMAL_INS ORDER BY NAME, DATETIME DESC;

7. 상위 n개의 레코드

SELECT NAME FROM ANIMAL_INS ORDER BY DATETIME LIMIT 1;

- DB는 3계층 구조로 이루어진다.

  • 인스턴스 = DB서버
  • 스키마 = Database
  • 테이블

- CRUD : Create + Read + Update + Delete

 : 데이터를 다루는 software의 기본적인 인터페이스

  • C : insert into 테이블 values();
  • R : select 필드 (as 필드명 변경) from 테이블 where 레코드조건
  • U : update 테이블 set 필드=값 where 레코드조건
  • D : delete from 테이블 where 레코드조건 
update minco.honey set age=15 where num=4;
delete from minco.honey where num=1;
insert into minco.honey values(50, "촉촉", 100);
select * from minco.honey

insert into minco.honey values(8, "순신", 20)
update minco.honey set age=320 where num=7;
update minco.honey set name='정현' where num=6;
delete from minco.honey where num =7;
delete from minco.honey where num =8;

select * from minco.honey
select * from minco.honey where num=3 or num=5;
SELECT name, age FROM minco.honey where num>=2 and num <=5 ;
select * from minco.honey where age>=20 and age <30;
select name from minco.honey where num%2=0 and age%2=1 ;
select name as '이름' from minco.honey;
select * from minco.honey order by age desc;
select num as '번호', name as '성함', age as '나이' from minco.honey order by age; 
select name,name,name,name,name from minco.honey where age<20;
honeyselect age, name from minco.honey order by name

 

- 웹에서의 CRUD

  • 로그인 : select
  • 회원가입 : select , insert, update
  • 회원탈퇴 : delete
  • 게시판 : insert, select, update, delete (CRUD 전체사용)

- UPDATE Error 

 -> Safe update mode

    : 다수의 레코드들이 한꺼번에 update되는사고를 방지하기위함 (설정에서 off가능)

 

- CMD에서 사용하기 -> 모든 명령어 ; 필수

  • mysql -u root -p (패스워드입력 uveba40d50!)
  • show database;
  • use minco(user name)
  • show tables;
  • desc honey;
  • CRUD사용 -> workbench에서 동일한 테이블 확인가능

- git에서 test_db가져오기

https://github.com/datacharmer/test_db

 

GitHub - datacharmer/test_db: A sample MySQL database with an integrated test suite, used to test your applications and database

A sample MySQL database with an integrated test suite, used to test your applications and database servers - GitHub - datacharmer/test_db: A sample MySQL database with an integrated test suite, use...

github.com

 

GitHub - datacharmer/test_db: A sample MySQL database with an integrated test suite, used to test your applications and database

A sample MySQL database with an integrated test suite, used to test your applications and database servers - GitHub - datacharmer/test_db: A sample MySQL database with an integrated test suite, use...

github.com

  • cd test_db
  • mysql -u root -p < employees.sql (패스워드입력 uveba40d50!)

- test_db활용 검색하기 -> between, in, like

SELECT * FROM employees.employees  where emp_no between 10002 and 10004; 
SELECT * FROM employees.employees  where first_name in ('Parto', 'Bezalel');
SELECT * FROM employees.employees  where first_name like ('G__'); -- 'G%'

- group by -> 조건절 having

  • SUM() / AVG()
  • MIN() / MAX()
  • COUNT
select ID, sum(Population) as 합계 from city group by CountryCode;
select CountryCode, count(Population) as from city group by CountryCode;

select CountryCode, count(Population) as '도시수' from city 
group by CountryCode
having count(Population) > 200;

- limit -> 특정개수만 보여줌으로써 빠른 쿼리 성능구현

- 날짜, 시간 검색하기

select DATE("2025-12-25 11:42:59");
select TIME("2025-12-25 11:42:59");
select YEAR("2025-12-25 11:42:59");
select MONTH("2025-12-25 11:42:59");
select DAY("2025-12-25 11:42:59");
select hour("2025-12-25 11:42:59");
select minute("2025-12-25 11:42:59");
select second("2025-12-25 11:42:59");

- 날짜 샘하기

SELECT year(from_date) as '시작년도', year(to_date) as '종료년도' FROM employees.dept_emp limit 3 ;
select date_format("2020-12-31","%Y년 %m월 %d일이었지")
select date_format("2020-12-31 11:37:40","%Y년 %m월 %d일 %h시 %i분 %s초 였을거야")
select str_to_date("1997년 12월 25일","%Y년 %m월 %d일이었지")

select date_format(from_date,"%Y년 부터 시작이었지..") as '때는' from employees.dept_emp;

select timestampdiff(year, '2011-06-12', '2021-08-15'); -- 날짜간격구하기
select date_add(now(), interval 1 day); --날짜 덧셈
select date_sub(now(), interval 1 month); --날짜 뺄셈

select timestampdiff(year, '1996-08-23', now()) +1 ; -- 내나이 구하기
select timestampdiff(month, '1996-08-23', now()); -- 내가 살아온 달 구하기
select timestampdiff(day, now(), '2096-08-23'); -- 내가 100살까지 산다면 남은 날 구하기

- null값 유무 확인후 다른문자 대체하기

SELECT * FROM employees.departments where dept_name is not null;
select dept_no, ifnull(dept_name,'#') from employees.departments;

- 문자열함수

select concat('안녕', '하', '시오');
select concat(emp_no, '-', dept_no, '-', from_date) from employees.dept_emp;

select length('abcde'); -- 문자열 길이 반환

-- INSERT(문자열, 시작위치, 길이, 새로운문자열) 문자열의 시작위치부터 길이만큼의 문자열을 제거하고 새로운 문자열 삽입
select insert('abcde' , 2, 2, 'bbb'); -- abbbde

-- replace(문자열, 기존문자열, 새로운 문자열)
select replace('aacaa','a','b'); -- bbcbb

-- instr(문자열1, 문자열2) 문자열 1에서, 문자열2를 찾아서 위치 반환
select instr('abcdefg', 'cde'); -- 3

-- left(문자열, 개수) 문자열의 좌측부터 개수만큼 가져옴
select left('abcdefg', 3) -- abc

-- right(문자열, 개수) 우측부터 가져옴
select right('abcdefg', 3) -- efg

-- mid(문자열, 시작위치, 개수) 문자열 시작위치에서 개수만큼 가져온다
select mid('abcdefg', 3, 3) -- cde

-- substring(문자열, 시작위치, 개수) 문자열의 시작위치에서 개수만큼 가져옴
select substring('abcdefg',3,3) -- cde

-- trim (공백제거) ltrim rtrim

select concat('[','         abc    ',']')
select concat('[',trim('         abc    '),']')
select concat('[',ltrim('         abc    '),']')

select lcase("abcDEF");
-- lcase, lower 

select upper("abcDEF");
-- ucase, upper

select reverse("abcdef");

 

- 집합

1. 합집합 - Union

  • select칼럼 from 테이블 union select 칼럼테이블
  • union - 자동 중복 제거
  • union all - 중복 제거 하지않고 바로 나타냄
  • 교칩한 차집합에 비해 중요도가 떨어짐

2. 교집합 - join

  • 첫번째 테이블 이름 INNER JOIN 두번째 테이블 이름 ON 조건
  • select * from 테이블1, 테이블2 where 테이블1.name=테이블2.name

3. 차집합 - subquery

  • select id from 테이블 1 where id NOT IN(select id from 테이블2)
  • select 테이블1.id from 테이블1 left join 테이블2 ON 테이블1.id = b.id where b.id IS NULL
  • 서브쿼리를 활용한다
select a.emp_no, frist_name from employees as a, dept_emp as b where a.emp_no = b.emp_no and b.dept_no = 'd001';

-- 현재 받는 급여의 평균보다 많이 받는 사원들의 사원번호, 급여액을 가져온다

-- 조건문을 만들어야되는데, 값을 직접 지정하지 못할때(평균연봉) 쿼리문을 통해서 가져와야되는경우 서브쿼리를 통해서 값을 구해 조건문으로 완성한다.
select avg(salary) from salaries;
select emp_no, salary from salaries where salary > (select avg(salary) from salaries where to_date = '9999-01-01') and to_date = '9999-01-01';

-- d001 부서에 근무하고 있는 사원들의 사원 번호와 first_name을 가져온다

-- join
select a.emp_no, first_name from employees a, dept_emp b where a.emp_no = b.emp_no and b.dept_no = 'd001'; 
-- sub
select emp_no, dept_no from dept_emp where dept_no = 'd001';
select * from employees;
select emp_no, first_name from employees  where emp_no in(select emp_no from dept_emp where dept_no = 'd001');


-- 1960 년 이후에 태어난 사원들이 근무하고 사원들의 사원번호, 근무 부서번호를 가져온다

-- join 
select a.emp_no, dept_no  from employees a, dept_emp b where a.emp_no = b.emp_no and birth_date >= '1960-01-01';
-- sub
select emp_no from employees where birth_date >= '1960-01-01';
select emp_no, dept_no from dept_emp where emp_no in (select emp_no from employees where birth_date >= '1960-01-01');

- 브라우저의 동작원리

https://d2.naver.com/helloworld/59361

1) 렌더링 엔진

렌더링 엔진은 HTML 문서를 파싱하고 "콘텐츠 트리" 내부에서 태그를 DOM 노드로 변환한다. 그 다음 외부 CSS 파일과 함께 포함된 스타일 요소도 파싱한다. 스타일 정보와 HTML 표시 규칙은 "렌더 트리"라고 부르는 또 다른 트리를 생성한다.

 

렌더트리를 통해 우리가 보는 화면이 된다.

 

기본적으로 코드는 동기적, 순차적 (좌 -> 우, 위 -> 아래)

자바스크립트 해석기보다 렌더링 엔진이 먼저있기 때문에 스크립트 만나면 렌더링 엔진 중단한다

 -> 바디태그의 하단 또는 헤더에 넣을경우 'defer' 속성 넣어주기 

 

2) 자바스크립트 엔진(해석기)

- 싱글스레드 기반의 non-blocking

- 비동기 프로그래밍 : 다른 업무를 기다리지않고 진행한다.

- Callback함수의 두가지 의미

  -> 이벤트 발생시 호출되는 예약함수 

     : 클릭 이벤트시 호출될 함수를 등록한다. (=콜백함수 등록)

      그리고, 클릭 이벤트 방생시 등록된 호출함수가 호출된다.

  -> 일반 함수의 Parameter로 등록되는 함수

     : test(1, run) 자바스크립트의 함수는 'object 값' (원시값 x)

Sync 동기 Async(Asynchronous 비동기
특정 동작이 끝난 이후, 다른 동작을 수행하기 시작함 1. Callback 함수 등록 처리( 호출하지 않음)
2. 다른 동작을 수행
 -> 내부적으로 다른 동작을 수행하면서도,
     지속적으로 Event가 발생했는지 감시
3. 특정 이벤트 발생시, Callback함수 수행됨

- Promise (비동기 작업을 좀더 편하게 할수 있도록 도입)

 -> new Promise((reslove,reject) => {});

pending 상태 - 대기 fulfilled 상태 - 이행 rejected 상태 - 실패
resolve나 rejected가 실행되기 전 resolve호출 시 reject호출 시

- async await 

 -> promise를 잘 쓰기위해 사용

 -> async는 함수 앞에 위치/ await는 함수 내부에 위치

 -> promise를 반환

 

비동기의 역사
setTimeout(callback hall)
-> promise (then..then...)
-> async/ await -> ~~ -> ~~

비동기 "통신의 역사"
XMLHttprequest
-> fetch
-> axios

 

- axios

 -> 가장 널리 쓰이는 http 통신 라이브러리

 - Vue/React에서도 권고 라이브러리로 axios가 지정됨

 - Promise형태 리턴

 - 사용에 편리

'WEB > Javascript' 카테고리의 다른 글

[21.08.10] 비동기 프로그래밍1  (0) 2021.08.10
[21.07.22]Google페이지 만들기  (0) 2021.07.22
[21.07.21] Javascript 실습 - 영화 정보 수집  (0) 2021.07.21
[21.07.20] Javascript기본  (0) 2021.07.21

- Arrow Function '=>'  : 값 전달, 리턴 가능(함수이름 따로 정의하지 않음)

const a= function(){ //함수표현식
    console.log("hello world")
}

a();

const b=() =>{ 
    alert("good morning")
}

b();

const c = () => console.log("good evening")

c()

//함수선언식 function f() { ~~

 

- forEach

: Array.forEach(Callback함수)

//각 요소에서 양수와 음수 구분해서 넣기
const array = [-5,3,4,2,-7,-2,7];
const mminus = [];
const pplus = new Array();

array.forEach(element => {
    if(element>0) pplus.push(element);
    else mminus.push(element);
})

console.log(pplus);
console.log(mminus);

- find

 : 배열을 순회하면서 조건에 해당되는 "첫번째 값"을 찾는다

- find index

 : 배열을 순회하면서 조건에 해당되는 "첫번째 인덱스"을 찾는다

const chicken = [
    { name: "머리", quantity: 1 },
    { name: "날개", quantity: 2},
    { name: "닭다리", quantity: 2},
    { name: "닭가슴살", quantity: 1},
    { name: "닭발", quantity: 2},
]

console.log(chicken.find(element => element.name==="닭다리"));
console.log(chicken.findIndex(element => element.name==="닭발"))

//배열의 정의 = "같은 자료형들의 연속된"
//객체의 정의 = "키:값으로 이루어진 다양한 자료형들의 집합" (일반 자료형, 객체형)
//->배열안의 객체

- map((요소, index))

 : 배열의 요소를 하나씩 탐색하며 Callback함수의 return값을 Array로 새롭게 만든다

  -> forEach는 값반환, map은 배열반환

const array = [1,2,3,4,5];
const result =array.map(e => e*e);

console.log(result);

const array2 = ['a','bcd','ef','g'];
const length = array2.map(e => e.length);

console.log(length);

- filter((요소, index))

 : 배열에서 특정 조건을 만족하는 값들만 따로 추출(map이랑 동시사용 가능)

const bucketlist=[
    { id:1, text: "여행", done: false},
    { id:2, text: "치킨먹기", done: true},
    { id:3, text: "알고리즘", done: true},
    { id:4, text: "운동하기", done: false}
];

const Array=bucketlist.filter( element => element.done==true);
const Array2=bucketlist.filter( element => !element.done);

console.log(Array);
console.log(Array2);

- reduce

 : 첫번째 인자는 결과값/ 두번째 인자는 현재값

 

 

 

js에서 "함수 호출 방식"에 따라 this 바인딩이 결정된다

화살표함수와 일반함수의 this바인딩은 다르다

 

1. (일반)함수 호출 -> 전역객체(브라우저 = widow node => global에 바인딩 )

2. 메서드 호출 -> 메서드를 소유한 객체

 

forEach/ map 구분점
- 단순 작업만 할경우 forEach
- 작업에 이어서 배열을 원하면 map

map filter / reduce

'WEB > Javascript' 카테고리의 다른 글

[21.08.11] 비동기 프로그래밍2  (0) 2021.08.11
[21.07.22]Google페이지 만들기  (0) 2021.07.22
[21.07.21] Javascript 실습 - 영화 정보 수집  (0) 2021.07.21
[21.07.20] Javascript기본  (0) 2021.07.21

- 민코딩 (구현의탑_흑돌백돌)

#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

char arr[8][8];

void check(int y, int x, char stone) {    //돌 놓은좌표, 내 돌의 색상

char bande = '@';
if (stone == '@')  bande = 'O';

vector<pair<int, int>> vect;

int direction[8][2] = { -1,-1,1,1,-1,1,1,-1,1, 0, -1, 0, 0, 1, 0, -1 };

for (int t = 0; t < 8; t++) {
    int dy = y + direction[t][0];
    int dx = x + direction[t][1];
    int flag = 0;
    vect.clear();
    // 배열범위
    if (dy < 0 || dy >= 8 || dx < 0 || dx >= 8) continue;

    // 내돌 옆에 반대다
    if (arr[dy][dx] == bande) { 
        while (1) {  // 계속 옆을 보자
            if (arr[dy][dx] == bande) {  
                vect.push_back({ dy, dx });
                dy = dy + direction[t][0];
                dx = dx + direction[t][1];
                
                // 범위 밖이거나 돌이 없는 경우에는 break
                if (dy < 0 || dy >= 8 || dx < 0 || dx >= 8 || arr[dy][dx] == '_') {
                    flag = 0;
                    break;
                }
            }
            // 상대 돌이 나오다가 내 돌이 나온다면 true
            else if (arr[dy][dx] == stone) {
                flag = 1;
                break;
            }
        }
    }
    if (flag==1) {
        for (int y = 0; y < vect.size(); y++) {
            arr[vect[y].first][vect[y].second] = stone;
        }
    }
}
}

int main() {

int n;
cin >> n;
int y, x;

for (int y = 0; y < 8; y++) {
    for (int x = 0; x < 8; x++) {
        arr[y][x] = '_';
    }
}


for (int t = 0; t < n; t++) {

    cin >> x >> y; // 3,4
    char stone;
    if (t % 2 == 0) stone = '@';
    else stone = 'O';
    arr[7 - y][x] = stone;  // 4,3  돌 놓고 체크
    check(7 - y, x, stone); 
}


for (int y = 0; y < 8; y++) {
    for (int x = 0; x < 8; x++) {
        cout << arr[y][x];
    }
    cout << endl;
}

return 0;
}

- 백준_봄버맨(https://www.acmicpc.net/problem/16918)

#include <vector>

#include <string>

#include <queue>

#include <iostream>
using namespace std;

int r, c, n;
char map[200][200];
int direct[4][2] = {
    0,1,
    0,-1,
    1,0,
    -1,0
};

int main() {
    cin >> r >> c >> n;

for (int y = 0; y < r; y++) {  // 입력
    for (int x = 0; x < c; x++) {
        cin >> map[y][x];
    }
}


if (n % 2 == 0) {    // N이 2의 배수라면 항상 모든 판에 폭탄으로 채워진 상태임
    for (int y = 0; y < r; y++) {
        for (int x = 0; x < c; x++) {
            cout << 'O';
        }
        cout << '\n';
    }
    return 0;
}


int time = 1;

while (time != n) {

    /*
    struct node {
        int a, b;
    };
    */

    queue<pair<int, int>> q;     // 구조체로 사용하셔도 좋습니다. pair는 두개의 변수를 하나 로 묶어서 사용한다는 것으로 차후 라이브때 볼께요~
    //queue<node>q;

    for (int y = 0; y < r; y++) {         // 'O'으로 모두 채우고 queue에 폭탄좌표 저장
        for (int x = 0; x < c; x++) {
            if (map[y][x] == 'O') q.push({ x, y });
            else map[y][x] = 'O';
        }
    }


    while (!q.empty()) {         // 터트리기
        int x = q.front().first;  // pair 자료형의 앞부분을 first  구조체라면 x=q.front().a;
        int y = q.front().second; // pair 자료형의 뒷부분을 second 로 놓았습니다.  구조체라면 x=q.front().b;
        q.pop();

        map[y][x] = '.';
        for (int t = 0; t < 4; t++) {
            int dy = x + direct[t][1];
            int dx = y + direct[t][0];

            if (dy >= 0 && dy < c && dx >= 0 && dx < r) {
                map[dx][dy] = '.';  // 터트리기
            }
        }
    }
    time += 2;
}


for (int y = 0; y < r; y++) {  // 출력
    for (int x = 0; x < c; x++) {
        cout << map[y][x];
    }
    cout << '\n';
}
}

- 배열덧셈(자릿수 올림)

#include<iostream>
using namespace std;

void input(char arr[6])
{
    for (int x = 0; x < 6; x++)
        cin >> arr[x];
}

int main()
{
    char arr1[6], arr2[6], sum[6] = {0};
    input(arr1);
    input(arr2);

int flag;
for (int x = 5; x >= 0; x--)
{
    flag = 0;
    if ((arr1[x] - '0') + (arr2[x] - '0') >= 10)    // 합이 10이 넘을때
    {
        sum[x] += (arr1[x] - '0') + (arr2[x] - '0') - 10;
        flag = 1;
    }
    else {   // 합이 10이 안넘을떄
        sum[x] += (arr1[x] - '0') + (arr2[x] - '0');
    }

    if (flag == 1) sum[x - 1]++; // 10이 넘으면 앞자리 ++
}

for (int x = 0; x < 6; x++)
    cout << sum[x] << ' ';

return 0;
}

- BFS + cycle방지(used)

#include <iostream>
#include <queue>
using namespace std;

int map[7][7] = {
0,1,1,0,0,0,0,
0,0,1,0,0,0,0,
0,0,0,1,1,1,0,
0,1,0,0,0,0,0,
1,0,0,0,0,1,1,
0,0,0,1,0,0,0,
0,0,0,0,0,0,0,
};

char name[8] = "AGKRHTV";
int used[10];

queue<int> q;

int main()
{
    used[2] = 1;
    q.push(2);

    while (!q.empty()) {

        int now = q.front();
        q.pop();

        cout << name[now] << " ";

        for (int i = 0; i < 7; i++) {
            if (map[now][i] == 0) continue;
            if (used[i] == 1) continue;
            used[i] = 1;
            q.push(i);
        }
    }

    return 0;
}

- Node사용하기

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int map[6][6] = {
    0,1,1,1,0,0,
    0,0,0,0,1,1,
};

struct Node {
    int n;
};

queue<Node> q;

int main()
{
    q.push({ 0 });

    while (!q.empty())
    {
        //1. 하나 뺸다. 
        Node now = q.front();
        q.pop();

        cout << now.n << " ";

        //2. now에서 다음 갈수있는길을 다 예약건다.
        for (int i = 0; i < 6; i++) {
            if (map[now.n][i] == 0) continue;
            q.push({ i });
        }
    }

    return 0;
}

- 그래프 DFS

#include <iostream>
#include <vector>
using namespace std;

int map[4][4] = {
    0, 1, 0, 1,
    0, 0, 1, 0,
    1, 0, 0, 1,
    0, 0, 1, 0,
};
int used[10];

void run(int now)
{
    cout << now << " ";
    for (int i = 0; i < 4; i++) {
        if (map[now][i] == 0) continue;
        if (used[i] == 1) continue;
        used[i] = 1;
        run(i);
    }
}

int main()
{
    used[0] = 1;
    run(0);

    return 0;
}

- 인접리스트 탐색

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> alist(9);
int val[9] = { 0, 1, 2, 7, 3, 6, 9, 15, 16 };

void run(int now)
{
    cout << val[now] << " ";
    for (int i = 0; i < alist[now].size(); i++) {

        int next = alist[now][i];
        run(next);

    }
}

int main()
{
    alist[0] = { 1, 2, 3 };
    alist[2] = { 4, 5 };
    alist[3] = { 6, 7, 8 };
    
    run(3);

    return 0;
}

- DFS

#include <iostream>
#include <vector>
using namespace std;

int map[6][6] = {
    0,1,1,0,0,0,
    0,0,0,1,1,0,
    0,0,0,0,0,1,
};

void run(int now)
{
    cout << now << " ";
    for (int i = 0; i < 6; i++) {
        if (map[now][i] == 0) continue;
        run(i);
    }
}

int main()
{
    run(0);

    return 0;
}

- 인접행렬/ 인접리스트로 풀어보기

#include <iostream>
#include <vector>
using namespace std;

char name[8] = "AGBTRSV";
int map[8][8] = {
    0,1,1,1,0,0,0,
    0,0,0,0,1,1,0,
    0,0,0,0,0,0,0,
    0,0,0,0,0,0,1,
};

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < 8; i++) {
        if (map[n][i] == 0) continue;
        cout << name[i];
    }

    return 0;
}
#include <iostream>
#include <vector>
using namespace std;

char name[8] = "AGBTRSV";
vector<vector<int>> alist(7);

int main()
{
    alist[0] = { 1, 2, 3 };
    alist[1] = { 4, 5 };
    alist[3] = { 6 };

    int n;
    cin >> n;

    for (int i = 0; i < alist[n].size(); i++) {
        cout << name[alist[n][i]];
    }

    return 0;
}

- 인접리스트활용 탐색

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> alist(4);
int name[4] = { 3, 5, 4, 0 };

int main()
{
    /*alist[0].push_back(1);
    alist[0].push_back(2);
    alist[0].push_back(3);
    alist[1].push_back(3);
    alist[2].push_back(3);
*/
    alist[0] = { 1, 2 };
    alist[1] = { 3 };
    alist[2] = { 3 };

    int n;
    cin >> n;

    for (int i = 0; i < alist[n].size(); i++) {
        cout << name[alist[n][i]];
    }

    return 0;
}

- vector활용법

#include <iostream>
#include <vector>
using namespace std;

//1차원 배열 같은 객체 t를 만듬
//만들어진 칸 수는 = 0칸
vector<int> t;

//1차원 배열 같은 객체 v하나 생성
//만들어진 칸 수는 = 다섯 칸
vector<int> v(5);

int main()
{
    t[1] = 15; //이건 에러 (만들어진 칸이 없음)
    v[1] = 15; //이건 가능

    t.push_back(1);
    t.push_back(2);
    t.push_back(3);

    return 0;
}
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> v;
vector<int> g;

int main()
{
    //g 에 한칸 추가 (3이 들어감)
    g.push_back(3);
    g.push_back(4);

    //v에 한칸 추가
    v.push_back({ 1, 2, 3 });
    v.push_back({ 9, 7 });

    return 0;
}

- 인접행렬이용한 탐색

#include <iostream>
using namespace std;

char name[6] = "ABCDF";
int map[5][5] = {
    0,0,0,1,0,
    1,0,0,1,0,
    0,0,0,1,0,
    0,0,0,0,1,
    0,1,1,0,0,
};

int main()
{
    int max = 0;
    char maxCh;
    for (int x = 0; x < 5; x++) {
        int cnt = 0;
        for (int y = 0; y < 5; y++) {
            if (map[y][x] == 0) continue;
            cnt++;
        }

        if (max < cnt) {
            max = cnt;
            maxCh = name[x];
        }
    }

    cout << maxCh;

    return 0;
}

- 배열과 링크드리스트 탐색 -> 추후 진행 예정

#include <iostream>
using namespace std;

struct Node {
    int n;
    Node *next;
};

Node *head, *last;

void addNode(int n)
{
    if (head == NULL) {
        head = new Node();
        head->n = n;
        last = head;
        return;
    }

    last->next = new Node();
    last = last->next;
    last->n = n;
}

int main()
{
    int v[5] = { 4, 8, 7, 6, 9 };

    addNode(4);
    addNode(8);
    addNode(7);
    addNode(6);
    addNode(9);

    for (int i = 0; i < 5; i++) {
        cout << v[i];
    }
    cout << endl;
    for (Node *p = head; p != NULL; p = p->next) {
        cout << p->n;
    }

    return 0;
}

+ Recent posts