1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
public class Main {
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        //캐릭터로 입력을 받고
        char character = (charbr.read();
        //ascii코드로 변경하기 위해서 int로 형변환
        int ascii = (int) character;
        //write의 특성인 int를 입력하면 char로 출력하기 때문에 또다시 string으로 출력
        //scanner가 정말 편하다
        bw.write(String.valueOf(ascii));
        bw.flush();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 7단계(10809)  (0) 2019.12.07
백준 7단계(11720)  (0) 2019.12.07
백준 6단계(1065)  (0) 2019.12.07
백준 6단계(4673)  (0) 2019.12.07
백준 6단계(15596)  (0) 2019.12.07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
public class Main {
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int n = Integer.parseInt(br.readLine());
        int cnt = 0;
        for(int i = 1; i <= n; i++) {
            if(check(i)) cnt++;
        }
        bw.write(String.valueOf(cnt));
        bw.flush();
        bw.close();
        br.close();
    }
    
    public static boolean check(int i) {
        if(i < 100return true;
        
        int a = i % 10//일자리
        int b = i/10 % 10//십자리
        int c = i/100 % 10//백자리
        
        //여기서 절대값으로 처리하면 975같은 숫자들 처리가 불가능...
        int first = b - c;
        int second = a - b;
        
        if(i >= 1000return false;
 
        if(first == second) {
//            System.out.println(first + " " + second + " " + i);
//            System.out.println("\n");
            
            return true;
        } 
        
        return false;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

숫자가 등차수열이면 cnt++으로 입력된 숫자까지 등차수열이 몇개가 존재하는지 찾는 알고리즘.

십자리와 일자리를 뺀 first, 백자리와 십자리를 뺀 second가 같으면 true를 리턴해줘서 true면 cnt++.

 

 

'알고리즘' 카테고리의 다른 글

백준 7단계(11720)  (0) 2019.12.07
백준 7단계(11654)  (0) 2019.12.07
백준 6단계(4673)  (0) 2019.12.07
백준 6단계(15596)  (0) 2019.12.07
백준 5단계(4344)  (0) 2019.11.28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
public class Main {
    
    public static void main(String[] args) throws Exception{
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        boolean[] check = new boolean[10000];
        
        for(int i = 0; i < 10000; i++) {
            check[number(i)] = true;
        }
        
        for(int i = 0; i < 10000; i++) {
            if(!check[i]) bw.write(i + "\n");
        }
        bw.flush();
    }
    
    public static int number(int i) {
        
        int n = i;
        int ans = n;
        while(n > 0) {
            ans += n % 10;
            n /= 10;
        }
        if(ans > 9999return 9999;
        return ans;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

불리언 배열을 10000크기만큼 지정을 해준다.

number메소드에서 ans를 리턴해주는데, ans는 기존 값+ 일, 십, 백 천짜리까지 더해준다. 

리턴된 값을 boolean배열 방의 위치로 선정해주고, 방을 트루값으로 변환.

boolean의 디폴트 값은 false이니까 false이방만 출력해주면 셀프 넘버입니다

'알고리즘' 카테고리의 다른 글

백준 7단계(11654)  (0) 2019.12.07
백준 6단계(1065)  (0) 2019.12.07
백준 6단계(15596)  (0) 2019.12.07
백준 5단계(4344)  (0) 2019.11.28
백준 5단계(8958)  (0) 2019.11.28
1
2
3
4
5
6
7
8
9
public class Test {
    long sum(int[] a) {
        long ans = 0;
        for(int i = 0; i < a.length; i++){
            ans += a[i];
        }
        return ans;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

간단한 더하기 알고리즘

'알고리즘' 카테고리의 다른 글

백준 6단계(1065)  (0) 2019.12.07
백준 6단계(4673)  (0) 2019.12.07
백준 5단계(4344)  (0) 2019.11.28
백준 5단계(8958)  (0) 2019.11.28
백준 5단계(1546)  (0) 2019.11.28

1. select substring(datetime, 12, 2) as hour, count(datetime) 
from animal_outs
group by hour
having hour
between 9 and 19

 

--- if you want to only get hours using datetime, use a substring where you can define the start point and the end point of a certain column/data. 

datetime is formatted as YYYY-MM-DD HH:MI:SS, so the twelfth starting value is H while ending is also H resulting in hours only

 

-- extract(hour from datetime) much more simple i think also works as well

 

2. select a1.hour, ifnull(a2.count, 0)
from ( select 0 as hour
     union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 10 union select 11 union select 12 union select 13 union select 14 union select 15 union select 16 union select 17 union select 18 union select 19 union select 20 union select 21 union select 21 union select 22 union select 23) a1
     left join  (select hour(datetime) as hour, count(*) as count 
                 from animal_outs
                 group by hour) 
                 as a2 on a2.hour = a1.hour

 

--still baffled 

 

3.SELECT animal_type, ifnull(name, 'No name')name, sex_upon_intake 
from animal_ins

 

--use ifnull no make a exception, like number 2

 

4. -- 코드를 입력하세요
SELECT animal_id, name, sex_upon_intake
from animal_ins
where name in('lucy', 'ella', 'pickle', 'rogan', 'sabrina', 'mitty')

 

--if you have multiple condition that needs to be searched, using in like this would work

 

5. SELECT animal_id, name, 
    CASE WHEN sex_upon_intake like 'Intact%'
        THEN 'X'
        ELSE 'O' 
    END as 중성화
from animal_ins

 

--case end and when then else using like wildcard

 

SELECT animal_id, name, IF(sex_upon_intake like "Intact%", 'X', 'O')
from animal_ins
order by animal_id;

 

--here used a if like a 삼항연산자 ternary operation

 

6. -- 코드를 입력하세요
SELECT ai.animal_id, ai.name 
from animal_ins ai 
left join animal_outs ao
on ai.animal_id = ao.animal_id 
order by ao.datetime - ai.datetime desc
limit 2

 

-- 데이트 차이 제일 큰 2동물 선택

 

7. SELECT animal_id, name, date_format(datetime, '%Y-%m-%d') as 날짜 
from animal_ins
order by animal_id asc

 

or substring(datetime, 1, 10)

 

--prints year month day 

'데이터베이스' 카테고리의 다른 글

mysql notes 1 loop  (0) 2020.05.27

Java.lang.OutOfMemoryError ==not able to use heap because heap is full, NEED TO CHECK FOR MEMORY LEAKS!!!

 

Garbage collection has 3 steps:

 

Mark- starts from root node of your application, walks object graph and marks objects that are reachable as live

Sweep/delete – delete unreachable objects, sweeps from heap

Compacting- Arranging everything in order, when unreachable objects are sweeped, there are holes empty places so then compacting comes in and arranges objects in order.

 

Heap is divided into two spaces, young generation and old(tenured) generation :

 

Eden space – a place where new objects are created, references to a book of genesis

When eden space is full, that is when minor(small) garbage collector kicks in removes unreachable objects and moves them to survivor space

Survivor space - Having two survivor space prevents compacting step to be used again.

Old generation – a place in heap where long survived objects are stored

Major garabage collector kicks when old generation is almost full, marks, sweep and compacts new and old generation. Application comes to a halt while this is happening.

 

-XX:MaxTenuringThreshold  = how many times object need to survive to be placed into old generation

 

 

*Performance*

responsiveness/latency- how quickly an application response with a requested piece of data

ex. If a ui on a web application focuses on responsiveness, large pause times are not acceptable.

 

Throughput = throughput focuses on maximizing the amount of work by an application in a specific period of time.

Ex. The number of jobs that a batch of program can complete in an hour

The number of database queries that can be completed in an hour

*Type of garbage collectors*

 

A serial garbage collector – basic garbage collector that runs in a single thread, can be used for basic applications

Pause, runs, pause, runs

 

A concurrent collector – a thread that performs gc along with application execution as the application runs, does not wait for the old generation to be full – stop the world only during mark/re-mark

 

A parallel collector - Uses multiple cpus to perform gc. Multiple threads doing mark/sweep etc. does not kick in until heap is full or near full.

 

Use concurrent collector when(responsiveness/latency)

There is more memory

There is high number of cpus to spare

Application demands short pauses

 

Use a parallel collector when(throughput!)

Application demands high throughput and can withstand pauses

 

Most application use concurrent garbage collector because of high responsiveness! Of course!

 

As of Java 1.7, g1 was introduced

G1 divides heap into small regions. When a certain region has a lot of unreachable objects, gc kicks in. g1 does not care for young or old or eden survivor space.

-      Parallelism and concurrency together

-      Low pauses with fragmentation

-      Better heap utilization

Uptil 1.6, parallelgc was default

1.7 + g1gc is the default

 

Xmsvalue = setting the minimum value to heap

Xmxvalue = maxium value to heap(default 256)

Xx:newratio=ratio (2means 1/3 Y + 2/3 O(T))

Xx:newsize=size   how much amount of memory set aside for eden space

Xx:permsize    a size assigned to meta-data(static class data etc)

Xx:maxpermsize     def 64m          

 

 

게임회사에서 면접을 보면서 대답을 못 한 질문이 많았지만 개발자로서 꼭 알아야 하는 이론인데 공부를 하지 않아서 답변 못 했던 질문이 2개였는데 하나가

1. 가비지 컬렉터가 어떻게 돌아가는지

2. Big O에 대해서 



전에 자바 메모리 구조 포스트에 올렸듯이 meta-data에는 static 그리고 클래스 자료들이 저장되고, stack 안에서는 local variable들이 저장되면서 객체의 변수도 같이 저장되는데 heap 영역에서 객체의 자료가 저장된다. stack에서는 heap의 참고 주소만 가지고 있어서 만약 heap에서 자료를 참고하지 않으면 가비지 컬렌터가 돌아간다는 까지 알고 있었는데, 힙 영역 안에서 어떻게 작동하는 원리를 물어보셔서 많이 당황한 기억이 난다.



그래서 집에 와서 공부한 게 빅오랑 가비지 컬렉터다.



영어로 배워서 영어로 위에 설명을 적었는데 나중에 면접 가서 설명은 한국말로 해야 해서 간략하게 정리해보겠습니다



가비지 컬렉터는 3가지 단계로 작동을 한다

mark, sweep, compact

힙안에는 new generation 그리고 old generation이 존재한다

new generation 안에는 eden 그리고 2개의 survivor 영역

old generation은 그냥 old generation

가비지 컬렉터는 new generation에 eden이 다 찾을 때 minor garbage collector가 작동하면서 참조 안 되는 객체는 지우면서 참조되는 자료는 survivor 영역으로

만약 오래 존재하는 자료면 old generation으로 이동

old generation 메모리 영역이 거의 다  찼을 때 major gc 발동. major gc는 new와 old다 mark sweep compact 함

이런 식으로 메모리가 정리된다



가비지 컬렉터의 종류는 현재 4가지

원래는 parallel gc 를 default로 사용했지만 1.7 이후부터 g1 gc 사용

g1서부터는 old new generation 구분 없이 영역을 나누어서 해당 영역이 차면 gc 발동, g1이 parallel 그리고 concurrent와 같이 사용하는 느낌



다음 면접 때 물어보면 확실히 설명할 수 있을 것 같다

source : https://www.youtube.com/watch?v=UnaNQgzw4zY&t=198s

'ETC' 카테고리의 다른 글

이것이 자바다 노트2(스레드 + 멀티스레드)  (0) 2019.12.14
이것이 자바다 노트1  (0) 2019.12.09
Comparable vs Comparator  (0) 2019.12.01
Algorithm time complexity  (2) 2019.12.01
자바 메모리 구조  (0) 2019.11.23

Comparable is a interface you need to implement to a Object where a specific compare standard has to be defined by overriding compareTo method.

compareTo needs to be returned as an int value, + for moving up a list, - for moving down, 0 for staying at the same place.

Wrapper type data does NOT need comparable interface to be compared since all Wrapper class already has been implemented with a Comparable interface. String, char are compared by unicode, numbers are obviously compared by numbers. You could implement Comparable on an object class if standard comparing method does not suit your needs. 

Comparator on the other hand is another interface used with purpose of for Collections.sort or Arrays.sort to directly assign comparable standards. anonymous class(?) is assigned on the back of collections.sort or arrays.sort and overrides compare method. the compare method is also an int return method and is same as compareTo method but the difference is number of parameter. compare requires two while compareTo only requires one. This is very simple to understand because you implement comparable to a object class, comparing class variable to parameter while for comparator you do not have a class object to compare to so you need two parameter to be compared. 

Collections.sort performs merge sort algorithm

 

 

'ETC' 카테고리의 다른 글

이것이 자바다 노트1  (0) 2019.12.09
Garbage Collector  (0) 2019.12.01
Algorithm time complexity  (2) 2019.12.01
자바 메모리 구조  (0) 2019.11.23
various query  (0) 2019.11.14

There are three things to consider when choosing which code to use

1. Time complexity(Big o)

2. Space complexity(How much memory it would consume)

3. Code readability

 

면접날 빅오 대해서 질문을 받았는데 답변을 못해서 집에서 찾아보니 코드를 선택할 때 세가지 요소가 있다는걸 발견했다.

간단하게 첫번째인 빅오에대해서 설명을 적어보도록 하겠습니다

 

입출력 상관없이 똑같은 속도를 유지하는 것은 O(1), 파라미터, 값에 변화에 영향을 받지 않고 똑같은 속도(constant complexity)
O(n)는 증가하는 값에 따라 같이 변화하는 것, linear complexity ex. for loop
O(n^2)는 제일 오래 걸리는 속도, quadratic complexity ex·이중 포문


O(1) = 주방장이 손님 수 상관없이 대량으로 조리해주는 속도  

O(log n) = 주방장이 주문들어온 음식들을 한번에 같이 조리해서 주는 속도
O(n) = 주방장이 손님마다 하나의 음식을 조리해서 주는 속도
O(n^2) = 주방장이 각 손님이 한에 모든 요리를 하나씩 다 조리해 주는 속도

 

 

'ETC' 카테고리의 다른 글

Garbage Collector  (0) 2019.12.01
Comparable vs Comparator  (0) 2019.12.01
자바 메모리 구조  (0) 2019.11.23
various query  (0) 2019.11.14
Various html  (0) 2019.11.14

+ Recent posts