[DataStructure&Algorithm] 3. Implementation

Implementation

When it comes to solving algorithm problems, 'implementation' means the process of turning the algorithms in your head into source code.

Problem Solutions

# python

def solution(n):
    string = "abcdefghijklmnopqrstuvwxyz"
    answer = ""
    cnt = 0
    a = n
    while n > 26:
        cnt += 1
        n -= 26

    for i in range(cnt):
        answer += string

    if n % 2 == 0:
        answer += string[:n//2]
        answer += string[(n//2) * -1:]
        return answer

    sum_of_digits = sum(list(map(lambda x: int(x), str(a))))
    if sum_of_digits % 2 == 0:
        answer += string[:(n+1)//2]
        if n != 1:
            answer += string[((n-1)//2)*-1:]
        return answer

    if n != 1:
        answer += string[:(n-1)//2]
    answer += string[((n+1)//2)*-1:]
    return answer   

# Execution Time:0.05
// java

public class Solution {
    public static String balancedString(int n) {
        String str = "abcdefghijklmnopqrstuvwxyz";
        String answer = "";
        int cnt = 0;
        int a = n;

        while (n > 26) {
            cnt++;
            n -= 26;
        }

        for (int i=0; i < cnt; i++) {
            answer += str;
        }

        String begin = "";
        String end = "";

        if (n % 2 == 0) {
            begin = str.substring(0, n/2);
            end = str.substring(26-n/2);
            answer += begin;
            answer += end;
            return answer;
        }

        String aToString = Integer.toString(a);
        int sumOfDigits = 0;
        for (int i=0; i<aToString.length(); i++) {
            sumOfDigits += Integer.parseInt(aToString.substring(i,i+1));
        }
        if (sumOfDigits % 2 == 0) {
            begin = str.substring(0, (n+1)/2);
            if (n != 1) {
                end = str.substring(26-((n-1)/2));
            }
        } else {
            if (n != 1) {
                begin = str.substring(0, (n - 1) / 2);
            }
            end = str.substring(26 - ((n + 1) / 2));
        }
        return answer + begin + end;
    }
}

// Execution Time:1.50
# python

def solution(n,q,s,q1,q2):
    answer = []

    rotate = 0
    idx = 0
    for i in range(len(q1)):
        if q1[i] == 1:
            idx = n-((q2[i]+rotate) % n)
            rotate = (q2[i]+rotate) % n
        else:
            if q2[i] + idx >= n:
                answer.append(s[q2[i]+idx-n])
            else:
                answer.append(s[q2[i]+idx])

    return answer

print(solution(7,5,'abcdefg',[1,2,2,1,2],[2,0,6,4,1]))

# Execution Time:2.53
// java

public class Solution {
    static ArrayList<Character> rotateString(int n, int q, String s, int q1[], int q2[]) {
        ArrayList<Character> answer = new ArrayList<Character>();

        int idx = 0;
        int rotate = 0;

        for (int i=0; i<q1.length; i++) {
            if (q1[i] == 1) {
                idx = n-((q2[i]+rotate) % n);
                rotate = (q2[i]+rotate) % n;
            } else {
                if (q2[i] + idx >= n) {
                    answer.add(s.charAt(q2[i]+idx-n));
                } else {
                    answer.add(s.charAt(q2[i]+idx));
                }
            }
        }
        return answer;
    }
}

// Execution Time:3.02

상하좌우

# python

import sys

n = int(sys.stdin.readline())
directions = list(map(str,sys.stdin.readline().split()))

def move(current, n, direction):
    x, y = current[1], current[0]
    if direction == 'R':
        _x = x + 1
        if _x <= n:
            x = _x
    elif direction == 'L':
        _x = x - 1
        if _x > 0:
            x = _x
    elif direction == 'U':
        _y = y - 1
        if _y > 0:
            y = _y
    elif direction == 'D':
        _y = y + 1
        if _y <= n:
            y = _y

    return (y, x)

current = (1,1)
for direction in directions:
    current = move(current, n, direction)

print('final: ', current)
// java

public class Solution {
    static ArrayList<Integer> move(int x, int y, int n, char direction) {
        if (direction == 'R') {
            int _x = x + 1;
            if (_x <= n) {
                x = _x;
            }
        } else if (direction == 'L') {
            int _x = x - 1;
            if (_x > 0) {
                x = _x;
            }
        } else if (direction == 'U') {
            int _y = y - 1;
            if (_y > 0) {
                y = _y;
            }
        } else {
            int _y = y + 1;
            if (_y <= n) {
                y = _y;
            }
        }
        ArrayList<Integer> nextPosition = new ArrayList<Integer>();
        nextPosition.add(y);
        nextPosition.add(x);
        return nextPosition;
    }

    static ArrayList<Integer> upDownLeftRight(int n, char directions[]) {
        ArrayList<Integer> currentPosition = new ArrayList<Integer>();
        currentPosition.add(1);
        currentPosition.add(1);
        for (int i=0; i<=n; i++) {
            currentPosition = move(currentPosition.get(1), currentPosition.get(0), n, directions[i]);
        }
        return currentPosition;
    }
}

시각

# python

import sys

n = int(sys.stdin.readline())

answer = 0

for i in range(60):
    for j in range(60):
        for k in range(n+1):
            if '3' in str(i) + str(j) + str(k):
                answer += 1

print(answer)
// java

public class Solution {
    static long time(int n) {
        int answer = 0;
        for (int i=0; i<60; i++){
            String str_i = String.valueOf(i);
            for (int j=0; j<60; j++) {
                String str_j = String.valueOf(j);
                for (int k=0; k<n+1; k++){
                    String str_k = String.valueOf(k);
                    String total = str_k + str_j + str_i;
                    if (total.indexOf("3") != -1) {
                        answer++;
                    }
                }
            }
        }
        return answer;
    }
}

왕실의 나이트

# python

import sys

position = sys.stdin.readline()

columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
cases = [(2,1), (2,-1), (1,2), (1,-2), (-2,1), (-2,-1), (-1,2), (-1,-2)]

criteria = range(1,9)

c, r = horizontal.index(position[0]) + 1, int(position[1])


answer = 0
for case in cases:
    _c = c + case[0]
    _r = r + case[1]

    if _c in criteria and _r in criteria:
        answer += 1

print(answer)
// java

public class Solution {
    static int knight(String position){
        String columns = "abcdefgh";
        int[] case1 = {2,1};
        int[] case2 = {2,-1};
        int[] case3 = {-2,1};
        int[] case4 = {-2,-1};
        int[] case5 = {1,2};
        int[] case6 = {1,-2};
        int[] case7 = {-1,2};
        int[] case8 = {-1,-2};
        int[][] cases = {case1, case2, case3, case4, case5, case6, case7, case8};

        int column = columns.indexOf(position.charAt(0));
        int row = Integer.parseInt(String.valueOf(position.charAt(1))) - 1;

        int answer = 0;
        for (int[] each_case: cases) {
            int c = column + each_case[0];
            int r = row + each_case[1];
            System.out.println(c + ' ' + r);
            if (c >= 0 && c < 9 && r >= 0 && r < 9) {
                answer ++;
            }
        }
        return answer;
    }
}

게임 구현

# python

import sys

map_range = list(map(int, sys.stdin.readline().split()))
position = list(map(int, sys.stdin.readline().split()))
li = []
for i in range(map_range[0]):
    li.append(list(map(int, sys.stdin.readline().split())))

li[position[0]][position[1]] = 1


def turn(current_position):
    global li

    h, v, direction = current_position[0], current_position[1], current_position[2]

    cnt = 0
    _v = v
    _h = h

    is_end = False

    while li[_h][_v] == 1:
        if cnt > 3:
            is_end = True
            break

        if direction % 4 == 0:
            _v = v - 1
            _h = h
        elif direction %4 == 1:
            _v = v
            _h = h - 1
        elif direction %4 == 2:
            _v = v + 1
            _h = h
        else:
            _v = v
            _h = h + 1

        direction += 3        
        cnt += 1

    if is_end:
        return False

    return [_h, _v, direction]

answer = 1
while position:
    position = turn(position)
    if not position:
        break
    li[position[0]][position[1]] = 1
    answer += 1

print('answer: ', answer)
// java

public class Solution {
    static int[] turn(int[][] map, int[] current_position) {
        int row = current_position[0];
        int column = current_position[1];
        int direction = current_position[2];

        int cnt = 1;

        int _column = column;
        int _row = row;

        while (map[_row][_column] == 1){
            if (cnt > 3) {
                int[] returning = {-1, -1, -1};
                return returning;
            }
            if (direction % 4 == 0) {
                _column = column - 1;
                _row = row;
            } else if (direction % 4 == 1) {
                _column = column;
                _row = row - 1;
            } else if (direction % 4 == 2) {
                _column = column + 1;
                _row = row;
            } else {
                _column = column;
                _row = row + 1;
            }
            direction += 3;
            cnt++;
        }
        int[] returning = {_row, _column, direction};
        return returning;

    }

    static int game(int[] range, int[] position, int[][] map) {
        int answer = 0;
        while (position[0] != -1) {
            position = turn(map, position);
            if (position[0] == -1) {
                break;
            }
            map[position[0]][position[1]] = 1;
            answer++;
        }
        return answer;
    }
}

16