Practice1

2차원 배열 열로 정렬하기 :

 

	public static void main(String[] args) {
		
		int [][] inputArray = {{4,5,6,1},{7,8,9,2},{1,42,2,3},{5,2,5,1}};
		
		System.out.println(Arrays.deepToString(orderByColumns(inputArray)));
		
	}

	private static int[][] orderByColumns(int[][] inputArray) {
		
		int[][] resultArray = new int[inputArray.length][inputArray[0].length];
		
		ArrayList<int[]> list = new ArrayList<int[]>();
		
		for(int inx=0; inx<inputArray.length; inx++) {
			Arrays.sort(inputArray[inx]);
			list.add(inputArray[inx]);
		}
		
		for(int inx=0; inx<inputArray.length; inx++) {
			for(int jnx=0; jnx<inputArray[inx].length; jnx++) {
				resultArray[inx][jnx] = list.get(inx)[jnx];
			}
		}
        //result will be : [[1, 4, 5, 6], [2, 7, 8, 9], [1, 2, 3, 42], [1, 2, 5, 5]]
		return resultArray;
	}

 

Practice2

2차원 배열 행으로 정렬하기 :

 

	private static int[][] orderByRows(int[][] inputArray) {
		
		int [][] resultArray = new int[inputArray.length][inputArray[0].length];
		int [][] reorderedArray = new int[inputArray.length][inputArray[0].length];
		
		ArrayList<int[]> list = new ArrayList<int[]>();
		
		for(int inx=0; inx<inputArray.length; inx++) {
			for(int jnx=0; jnx<inputArray[inx].length; jnx++) {
				reorderedArray[inx][jnx] = inputArray[jnx][inx];
			}
			Arrays.sort(reorderedArray[inx]);
			list.add(reorderedArray[inx]);
		}
		
		for(int inx=0; inx<inputArray.length; inx++) {
			for(int jnx=0; jnx<inputArray[inx].length; jnx++) {
				resultArray[inx][jnx] = list.get(jnx)[inx]; 
			}
		}
		
		return resultArray;
	}

 

Practice3  

initialize 2d array like above :

a b c d e        
        f h s d w

String inputData = "abcde, fhsdw"

	private void solution(String inputData) {
		
		String [] strArray = inputData.split(",");
		
		char [] charArr1 = strArray[0].toCharArray();
		char [] charArr2 = strArray[1].toCharArray();
		
		int totLength = charArr1.length + charArr1.length -1;
		
		char[][] initArray = initArray(charArr1, charArr2, totLength);
        
    }
     
     private char[][] initArray(char[] charArr1, char[] charArr2, int totLength) {
		char [][] initArray = new char[2][totLength];
		int pos = 0;
		
		for(int inx=0; inx<initArray.length; inx++) {
			for(int jnx=0; jnx< totLength; jnx++) {
				if(inx == 0 && charArr1.length > jnx) {
					initArray[inx][jnx] = charArr1[jnx];
					pos++;
				} else if(inx == 1 && charArr2.length > jnx) {
					initArray[1][pos -1] = charArr2[jnx];
					pos++;
				}
			}
		}
		System.out.println(Arrays.deepToString(initArray));
		
		return initArray;
	}

 

Practice4

Move(shift) Array 1step Forward

 

private void solution(String inputData) {
		
		String [] strArray = inputData.split(",");
		
		char [] charArr1 = strArray[0].toCharArray();
		char [] charArr2 = strArray[1].toCharArray();
		
		int totLength = charArr1.length + charArr1.length -1;
		
		char[][] initArray = initArray(charArr1, charArr2, totLength);
		
		//move 1st array 1step forward

		int moveStep = totLength - charArr1.length;
		
		char [] modifiedArray = new char[totLength];
		
		for(int inx=0; inx<moveStep ; inx++) {
			modifiedArray = moveOneStepFwd(initArray[0]);
			System.out.println(Arrays.toString(modifiedArray));
		}
  }
  
  
  	private char[] moveOneStepFwd(char[] charArr1) {
		// 오른쪽으로 한 칸 shift
		char temp = charArr1[charArr1.length - 1];
		for(int inx = charArr1.length-1 ; inx > 0 ; inx--) {
			charArr1[inx] = charArr1[inx-1];
		}
		charArr1[0] = temp;
		
		return charArr1;
	}
  

Practice5

Move(shift) Array 1step Backward 

 

	private void solution(String inputData) {
		
		String [] strArray = inputData.split(",");
		
		char [] charArr1 = strArray[0].toCharArray();
		char [] charArr2 = strArray[1].toCharArray();
		
		int totLength = charArr1.length + charArr1.length -1;
		
		char[][] initArray = initArray(charArr1, charArr2, totLength);
		
		//move 2nd array 1step backward
		int moveStep2 = totLength - charArr2.length;
		
		char [] modifiedArray2 = new char[totLength];
		
		for(int inx=0; inx<moveStep2 ; inx++) {
			modifiedArray2 = moveOneStepBwd(initArray[1]);
			System.out.println(Arrays.toString(modifiedArray2));
		}
        
   }
   
   	private char[] moveOneStepBwd(char[] charArr2) {
		// 왼쪽으로 한 칸 shift
		char temp = charArr2[0];
		for(int inx=0; inx<charArr2.length - 1; inx++) {
			charArr2[inx] = charArr2[inx+1];
		}
		charArr2[charArr2.length-1] = temp;
		
		return charArr2;
	}

 

Practice6
With similarity counter

 

	private void solution(String inputData) {
		
		String [] strArray = inputData.split(",");
		
		char [] charArr1 = strArray[0].toCharArray();
		char [] charArr2 = strArray[1].toCharArray();
		
		int totLength = charArr1.length + charArr1.length -1;
		
		char[][] initArray = initArray(charArr1, charArr2, totLength);
		
		//move 1st array 1step forward
		int moveStep = totLength - charArr1.length;
		
		char [] modifiedArray = new char[totLength];
		
		for(int inx=0; inx<moveStep ; inx++) {
			modifiedArray = moveOneStepFwd(initArray[0]);
			System.out.println(Arrays.toString(modifiedArray));
		}
		
		//move 2nd array 1step backward
		int moveStep2 = totLength - charArr2.length;
		
		char [] modifiedArray2 = new char[totLength];
		
		for(int inx=0; inx<moveStep2 ; inx++) {
			modifiedArray2 = moveOneStepBwd(initArray[1]);
			System.out.println(Arrays.toString(modifiedArray2));
		}
		
		//count similarity for 1st and 2nd array 
		ArrayList<Integer> list = new ArrayList<Integer>();
		
		list.add(countSimilarity(modifiedArray, modifiedArray2));
		System.out.println(list);
		
	}

	private int countSimilarity(char[] inputArray1, char[] inputArray2) {
		int similarity = 0;
		
		for(int inx=0; inx<inputArray1.length; inx++) {
			if(inputArray1[inx] == inputArray2[inx] && inputArray1[inx] != 0 ) {
				similarity++;
			}
		}
		return similarity;
	}

Practice1 : 제일 작은 수 제거하기

 

정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다.

arr return
[4,3,2,1] [4,3,2]
[10] [-1]

 

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int[] result = obd.solution(new int[] {4,3,2,1,7,190});
	
		System.out.println(Arrays.toString(result));
		
	}
	 public int[] solution(int[] arr) {

		 int[] answer = {};
	      if(arr.length <= 1 ) {	    	  
	    	  return new int[]{-1};
	      } else {
	    	  int cnt = 0;
	    	  answer = new int[arr.length - 1];
	    	  Arrays.sort(arr);
	    	  for(int inx=arr.length-1; inx>0; inx--) {
	    		  answer[cnt] = arr[inx];
	    		  cnt++;
	    	  }
	      }
	      return answer;
	 }
	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int[] result = obd.solution(new int[] {4,3,2,1,7,190});
	
		System.out.println(Arrays.toString(result));
		
	}
	 public int[] solution(int[] arr) {
	      if (arr.length <= 1) return new int[]{ -1 };		 
	      int min = Arrays.stream(arr).min().getAsInt();
	      return Arrays.stream(arr).filter(i -> i != min).toArray();

	 }

Practice2 : 하샤드 수

 

양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요.

arr return
10 true
12 true
11 false
13 false
public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		boolean result = obd.solution( 10 );
	
		System.out.println(result);
		
	}
	public boolean solution(int inputNumber) {
	      boolean answer = true;
	      int copyOfNum = inputNumber;
	      int sum = 0;
	      while(copyOfNum != 0 ) {
	    	  int lastDigit = copyOfNum % 10;
	    	  sum+=lastDigit;
	    	  copyOfNum /= 10;
	      }
	      
	      if(inputNumber % sum == 0 ) {
	    	  answer = true;
	      } else {
	    	  answer = false;
	      }
	      return answer;
	}

 

Practice3 : 행렬의 덧셈

 

행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요.

 

arr1 arr2 return
[[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]]
[[1],[2]] [[3],[4]] [[4],[6]]

 

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int [][] arr1 = {{1,2},{3,4}};
		int [][] arr2 = {{3,4},{5,6}};
		int[][] result = obd.solution( arr1, arr2 );
	
		System.out.println(Arrays.deepToString(result));
		
	}
	  public int[][] solution(int[][] arr1, int[][] arr2) {
	      int[][] answer = new int[arr1.length][arr1[0].length];
	      
	      for(int inx=0; inx<arr1.length; inx++) {
	    	  for(int jnx=0; jnx<arr1[inx].length; jnx++) {
	    		  answer[inx][jnx] = arr1[inx][jnx] + arr2[inx][jnx]; 
	    	  }
	      }
	      return answer;
	  }

 

Practice4 : 예산

 

S사에서는 각 부서에 필요한 물품을 지원해 주기 위해 부서별로 물품을 구매하는데 필요한 금액을 조사했습니다. 그러나, 전체 예산이 정해져 있기 때문에 모든 부서의 물품을 구매해 줄 수는 없습니다. 그래서 최대한 많은 부서의 물품을 구매해 줄 수 있도록 하려고 합니다.

 

물품을 구매해 줄 때는 각 부서가 신청한 금액만큼을 모두 지원해 줘야 합니다. 예를 들어 1,000원을 신청한 부서에는 정확히 1,000원을 지원해야 하며, 1,000원보다 적은 금액을 지원해 줄 수는 없습니다.

부서별로 신청한 금액이 들어있는 배열 d와 예산 budget이 매개변수로 주어질 때, 최대 몇 개의 부서에 물품을 지원해 줄 수 있는지 return 하도록 solution 함수를 완성해주세요.

d budget return
[1,3,2,5,4] 9 3
[2,2,3,3] 10 4
public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int [] arr = {1,3,2,5,4};
		int result = obd.solution( arr, 9 );
	
		System.out.println(result);
		
	}
	  public int solution(int[] d, int budget) {
	      int answer = 0;
	      Arrays.sort(d);
	      
	      for(int inx=0; inx<d.length; inx++) {
    		  if(budget >= d[inx] ) {
    			  budget -= d[inx];
    			  answer++;
    		  } 
	      }
	      
	      return answer;
  }

 

Practice5 : 소수 찾기

 

1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, solution을 만들어 보세요.

소수는 1과 자기 자신으로만 나누어지는 수를 의미합니다.
(1은 소수가 아닙니다.)

 

n result
10 4
5 3
    int numberOfPrime(int n) {
        int count = 0;
        int result = 0;

        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j <= i ; j++){
                if ( i % j == 0) count++;
            }
            if(count == 2) result++;
            count = 0;
        }

        return result;
    }

    public static void main(String[] args) {
        NumOfPrime prime = new NumOfPrime();
        System.out.println( prime.numberOfPrime(10) );
    }

 

Practice6 : 정수 제곱근 판별

 

임의의 정수 n에 대해, n이 어떤 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.

n return
121 144
3 -1

 

	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		
		long result = obd.solution( 121 );
	
		System.out.println(result);
		
	}
	  public long solution(long n) {
	      if (Math.pow((int)Math.sqrt(n), 2) == n) {
	            return (long) Math.pow(Math.sqrt(n) + 1, 2);
	        }

	        return -1;
	  }

 

Practice7 : 최대공약수와 최소공배수

 

두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. 예를 들어 두 수 3, 12의 최대공약수는 3, 최소공배수는 12이므로 solution(3, 12)는 [3, 12]를 반환해야 합니다.

n m return
3 12 [3, 12]
2 5 [1, 10]
public static void main(String[] args) {
	       TryHelloWorld c = new TryHelloWorld();
	       System.out.println(Arrays.toString(c.gcdlcm(3, 12)));
	}
    public int[] gcdlcm(int a, int b) {
        int[] answer = new int[2];

        answer[0] = gcd(a,b);
        answer[1] = (a*b)/answer[0];
        
        return answer;
    }

   public static int gcd(int p, int q){
	    if (q == 0) {
	    	return p;
	    }
	    return gcd(q, p%q);
   }
class TryHelloWorld {
     
  public static void main(String[] args) {
        TryHelloWorld c = new TryHelloWorld();
        System.out.println(Arrays.toString(c.gcdlcm(3, 12)));
  }
  
  public int[] gcdlcm(int a, int b) {
        int[] answer = new int[2];
        int standard = (a > b) ? a : b;

        for(int i=1; i<=standard; i++){
          if(a % i == 0 && b % i == 0) answer[0] = i;
        }
        answer[1] = (a * b) / answer[0];

        return answer;
    }

}

Practice1 : 문자열 내림차순으로 배치하기

 

문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.

 

public class OrderByDesc {

	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		String str = "Zbcdefg";
		String reversed = obd.solution(str);
	
		System.out.println(reversed);
		
	}
	  public String solution(String s) {
	        int temp, pos;
	      
	        StringBuffer sb = new StringBuffer();
	
	        char[] strArray = s.toCharArray();
	
	        for (int inx = 0; inx < strArray.length - 1; inx++) {
	            pos = inx;
	            for (int jnx = inx + 1; jnx < strArray.length; jnx++) {
	                if (strArray[jnx] > strArray[pos]) {
	                    pos = jnx;
	                }
	            }
	            temp = strArray[inx];
	            strArray[inx] = strArray[pos];
	            strArray[pos] = (char) temp;
	        }
	      
	        for (int inx = 0; inx < strArray.length; inx++) {
	            sb.append(strArray[inx]);
	        }      
	      
	        return sb.toString();
	  }
}

 

Practice2 : 가운데 글자 가져오기

 

단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 

단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.

 

public class OrderByDesc {

	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		String str = "abcde";
//		String str = "qwer";
		String reversed = obd.solution(str);
	
		System.out.println(reversed);
		
	}
	 public String solution(String s) {
	        String answer = "";

	        int strLength = s.length();

	        if (strLength % 2 != 0) {
	            answer = s.substring(strLength / 2 , strLength / 2 + 1);
	        } else {
	            answer = s.substring(strLength / 2 - 1, strLength / 2 + 1);
	        }
	        return answer;
	  }
}

 

Practice3 : 나누어 떨어지는 숫자 배열

 

array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int[] inputArr = {5, 9, 7, 10};
		int divisor = 5;
		int [] result = obd.solution(inputArr, 5);
	
		System.out.println(Arrays.toString(result));
		
	}
	 public int[] solution(int[] array, int divisor) {
	        int[] resultArray = {};
	        boolean isNotDivised = true;
	        ArrayList<Integer> list = new ArrayList<Integer>();

	        for (int inx = 0; inx < array.length; inx++) {
	            if (array[inx] % divisor == 0) {
	                list.add(array[inx]);
	                isNotDivised = false;
	            }
	        }

	        if (isNotDivised) {
	            list.add(-1);
	            resultArray = new int[1];
	        } else {
	            resultArray = new int[list.size()];
	        }

	        int counter = 0;
	        for (int value : list) {
	            resultArray[counter++] = value;
	        }

	        Arrays.sort(resultArray);
	        return resultArray;
	  }

 

Practice4 : 두 정수 사이의 합

 

두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. 
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.

 

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		long result = obd.solution(3, 5);
	
		System.out.println(result);
		
	}
	 public long solution(int a, int b) {
	      long answer = 0;
	      
	      if( a < b || a == b){
	          for(int inx=a; inx <= b ; inx++){
	              answer += inx;
	          }          
	      } else {
	          for(int inx=b; inx <= a ; inx++){
	              answer += inx;
	          }
	      }      
	      return answer;
	  }

 

Practice5 : 문자열 내 마음대로 정렬하기

 

문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 

예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1의 문자 u, e, a로 strings를 정렬합니다

public static void main(String[] args) {
		OrderByStrIWant orderbyI = new OrderByStrIWant();
		String [] inputArray = {"sun", "bed", "car"};
		int n = 1;
		System.out.println(Arrays.toString(orderbyI.solution(inputArray, n)));
	}
	
	public String[] solution(String[] inputArray, int n) {
	      String[] answer = {};
	      ArrayList<String> list = new ArrayList<String>(); 
	      ArrayList<String> tempList = new ArrayList<String>();

	      for(int inx=0; inx< inputArray.length; inx++) {
	    	  String tempStr = inputArray[inx].substring(n,n+1);
	    	  tempList.add(tempStr+"-"+inputArray[inx]);
	      }
	      Collections.sort(tempList);
	      
	      for(int inx=0; inx<tempList.size(); inx++) {
	    	  list.add(tempList.get(inx).substring(tempList.get(inx).indexOf("-")+1));
	      }
	      
	      answer = new String[list.size()];
	      
	      for(int inx=0 ; inx < answer.length; inx++) {
	    	  answer[inx] = list.get(inx);
	      }
	      
	      return answer;
}

Practice6 : 문자열 내 p와 y의 개수

 

대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요. 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.

예를들어 s가 pPoooyY면 true를 return하고 Pyy라면 false를 return합니다.

 

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		boolean flag = obd.solution("pPoooyY");
	
		System.out.println(flag);
		
	}
	 boolean solution(String inputStr) {
	        boolean resultFlag = true;

	        char[] strArray = inputStr.toLowerCase().toCharArray();
	        
	       HashMap<Character, Integer> counterMap = new HashMap<>();

	       for (Character inputChar : strArray) {
	            if (counterMap.containsKey(inputChar)) {
	                counterMap.put(inputChar, counterMap.get(inputChar) + 1);
	            } else {
	                counterMap.put(inputChar, 1);
	            }
	        }

	        if (counterMap.get('p') != counterMap.get('y')) {
	            resultFlag = false;
	        }
	        return resultFlag;
	    }

 

 

Practice7 : 핸드폰 번호 가리기

 

개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다.
전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요.

 

	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		String number = obd.solution("01000009999");
	
		System.out.println(number);
		
	}
	  public String solution(String phone_number) {
	      String answer = "";
	      for (int inx = 0; inx < phone_number.length(); inx++) {
	            if (phone_number.length() - 4 > inx) {
	                answer += "*";
	            } else {
	                answer += phone_number.charAt(inx);
	            }
	        }
	      return answer;
	  }

Practice8 : 시저 암호

 

어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다. 예를 들어 AB는 1만큼 밀면 BC가 되고, 3만큼 밀면 DE가 됩니다. z는 1만큼 밀면 a가 됩니다. 문자열 s와 거리 n을 입력받아 s를 n만큼 민 암호문을 만드는 함수, solution을 완성해 보세요.

s n result
AB 1 BC
z 1 a
a B z 4 e F d
public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		String result = obd.solution("AB", 1);
	
		System.out.println(result);
		
	}
	 public String solution(String s, int n) {
	      String answer = "";
	      char [] charArray = s.toCharArray();
	      
	      for(int inx=0; inx<charArray.length; inx++) {
	    	  char ch = charArray[inx];
	    	  if(ch != ' ') {
	    		  if(ch >= 'z') {
	    			  ch = (char) ((int)'a' + n - 1);
	    			  answer += (char)(ch);
	    		  } else {
	    			  answer += (char)(ch + n);
	    		  }
	    	  } else {
	    		  answer += (char)(' ');
	    	  }
	      }  
	      return answer;
 }

 

Practice9 : 약수의 합 :

 

자연수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요.

n return
12 28
5 6
	public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		int result = obd.solution(12);
	
		System.out.println(result);
		
	}
	public int solution(int n) {
	      int answer = 0;
	      for(int inx=1; inx<= n; inx++) {
	    	  if(n % inx == 0) {
	    		  answer += inx;
	    	  }
	      }
	      
	      return answer;
	}

Practice10 : 이상한 문자 만들기

 

문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요.

 

public static void main(String[] args) {
		OrderByDesc obd = new OrderByDesc();
		String result = obd.solution("try hello world");
	
		System.out.println(result);
		
	}
	 public String solution(String s) {
	        String ss = s.toUpperCase();
	        String answer = "";
	        int count = 0;
	        for (int j = 0; j < s.length(); j++) {

	            if (s.charAt(j) == ' ') {
	                count = 0;
	                answer += " ";
	            } else if (count % 2 == 0) {
	                answer += ss.charAt(j);
	                count++;
	            } else {
	                answer += (char)(ss.charAt(j) + 32);
	                count++;
	            }
	        }
	        return answer;
	    }

*Practice 1 : 124 World Practice

 

124 나라가 있습니다. 124 나라에서는 10진법이 아닌 다음과 같은 자신들만의 규칙으로 수를 표현합니다.

  1. 124 나라에는 자연수만 존재합니다.
  2. 124 나라에는 모든 수를 표현할 때 1, 2, 4만 사용합니다.

예를 들어서 124 나라에서 사용하는 숫자는 다음과 같이 변환됩니다.

10진법124 나라10진법124 나라

1 1 6 14
2 2 7 21
3 4 8 22
4 11 9 24
5 12 10 41

 

*Solution : 

public class WorldBy124_2 {
	public static void main(String[] args) {
		WorldBy124_2 wd = new WorldBy124_2();
		int number = 10;
		System.out.println(wd.solution(number));
	}

	private String solution(int number) {
	    String answer = "";
	    
	    while(number != 0 ) {
	    	int lastDigit = number % 3;
	    	number = number / 3;
	    	
	    	if(lastDigit == 0) {
	    		number = number - 1;
	    		lastDigit = 4;
	    	}
	    	answer = lastDigit + answer;
	    }
	    
		return answer;
	}
}

 

 

*Practice2 : Competition Practice

 

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.

 

[leo, kiki, eden] [eden, kiki] leo
[marina, josipa, nikola, vinko, filipa] [josipa, filipa, marina, nikola] vinko
[mislav, stanko, mislav, ana] [stanko, ana, mislav] mislav

 

*Solution : 

public class Competitions {

	public static void main(String[] args) {
		String [] participant = {"leo", "kiki", "eden"};
		String [] completion = {"eden", "filpa"};
		
		System.out.println(solution(participant, completion));
	}

	private static String solution(String[] participant, String[] completion) {
		
		Arrays.sort(participant);
		Arrays.sort(completion);
		
		for(int inx=0; inx < completion.length; inx++) {
			if(!participant[inx].equals(completion[inx])) {
				return participant[inx];
			}
		}
		
		return participant[participant.length-1];
		
	}

}

 

*Practice3 : Find K Number Practice

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

  1. array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
  2. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
  3. 2에서 나온 배열의 3번째 숫자는 5입니다.

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

*Solution : 

public class FindKNumber {

	public static void main(String[] args) {
		FindKNumber fn = new FindKNumber();
		
		int [] inputArray = {1, 5, 2, 6, 3, 7, 4};
		int [][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};
		
		System.out.println(Arrays.toString(fn.solution(inputArray, commands)));
		
	}
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
//        List<Integer> list = new ArrayList<Integer>();
        
        for(int inx=0; inx<commands.length; inx++) {
        	int [] tempArr = Arrays.copyOfRange(array, commands[inx][0] - 1, commands[inx][1]);
        	Arrays.sort(tempArr);
        	answer[inx] = tempArr[commands[inx][2] - 1];
        }
//        answer = new int[list.size()];
//        
//        for(int inx = 0 ; inx<answer.length; inx++) {
//        	answer[inx] = list.get(inx).intValue();
//        }
//        
        return answer;
        
    }
}

 

*Practice4 : Find Local Date 

 

2016년 1월 1일은 금요일입니다. 2016년 a월 b일은 무슨 요일일까요? 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT

입니다. 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 TUE를 반환하세요.

제한 조건

  • 2016년은 윤년입니다.
  • 2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다)
a                                                  b result
5 24 TUE

 

*Solution 

public class LocalDatePractice {

	public static void main(String[] args) {
		LocalDatePractice lc = new LocalDatePractice();
		int month = 5;
		int days = 24;
		System.out.println(lc.solution(month, days));
	}

	  public String solution(int a, int b) {
	     LocalDate ld1 = LocalDate.of(2016,a,b);
	     String str = ld1.getDayOfWeek().toString().substring(0,3);
	     return str; 
	  }
}

 

*Practice5 : Hate Same Number Practice

 

배열 arr가 주어집니다. 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다. 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다. 배열 arr에서 제거 되고 남은 수들을 return 하는 solution 함수를 완성해 주세요. 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다.
예를들면

  • arr = [1, 1, 3, 3, 0, 1, 1] 이면 [1, 3, 0, 1] 을 return 합니다.
  • arr = [4, 4, 4, 3, 3] 이면 [4, 3] 을 return 합니다.

배열 arr에서 연속적으로 나타나는 숫자는 제거하고 남은 수들을 return 하는 solution 함수를 완성해 주세요.

 

arr answer
[1,1,3,3,0,1,1] [1,3,0,1]
[4,4,4,3,3] [4,3]

 

*Solution1 :

public class HateSameNumber {

	public static void main(String[] args) {
		HateSameNumber hsn = new HateSameNumber();
		int [] inputData = {};
		System.out.println(Arrays.toString(hsn.solution(inputData)));
	}
	
	public int[] solution(int []arr) {
        List<Integer> list = new ArrayList();
  
        for(int inx=0; inx<arr.length; inx++){
            if(inx==arr.length-1){
                list.add(arr[inx]);
                break;
            }
            if(arr[inx] != arr[inx+1]){
                list.add(arr[inx]);
            }
        }
        int [] answer = new int[list.size()];
        
        int counter = 0;
        
        for(int number : list){
            answer[counter++] = number;
        }
        return answer;

	}
}

*Solution2 :

public class HateSameNumber {

	public static void main(String[] args) {
		HateSameNumber hsn = new HateSameNumber();
		int [] inputData = {};
		System.out.println(Arrays.toString(hsn.solution(inputData)));
	}
	
	public int[] solution(int []arr) {
	        ArrayList<Integer> tempList = new ArrayList<Integer>();
	        int preNum = 10;
	        for(int num : arr) {
	            if(preNum != num){
	                tempList.add(num);
                   }
	            preNum = num;
	        }       
	        int[] answer = new int[tempList.size()];
	        for(int i=0; i<answer.length; i++) {
	            answer[i] = tempList.get(i).intValue();
	        }
	        return answer;
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sshd_config 수정
sudo vi /etc/ssh/sshd_config
 
# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no
 
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no
 
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication yes
 
 
 
SSH 서비스 재시작
sudo service ssh restart
OR
sudo service sshd restart
 
 
cs






*Sequence Data :

순서가 바뀔 수 있는(의미가 있는) data

예) 주식 Data : 6일차의 Data를 보유하고 있을 때, 전 날 Data와 전전 날 Data가 영향을 준다(각각의 단계 마다 시퀀스별 관계를 담는다).


=> Recurrent Data(Data가 해당 Data에 영향을 미친다)


*RNN 활용분야:
- Language Modeling

- Speech Recognition

- Machine Translation

- Conversation Modeling / Question Answering

- Image /Video Captioning

- Image /Music /Dance Generation



* LSTM(Long Short-Term Memory Units) :

RNNs의 변형으로 90년대 중반에 처음으로 등장

-> Back propagation 하는 과정에서 오차의 값이 더 잘 유지되는데, 결과적으로 1000단계가 넘게 거슬러 올라갈 수 있음


*LSTM 학습단계 :

1) Forget Gate Layer(무엇을 잊을지, 완전히 제거할지)에 의해 결정됨

2) Input gate layer인 시그모이드 층이 어떤 값들을 갱신할지 결정

3) 이전 cell 상태 Ct-1을 새 cell 상태 Ct로 갱신하는 단계

4) 무엇을 출력할지 결정하는 단계




*RNN 구현 소스(teach hello):


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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)  # reproducibility
 
idx2char = ['h''i''e''l''o']
# Teach hello: hihell -> ihello
x_data = [[010233]]   # hihell
x_one_hot = [[[10000],   # h 0
              [01000],   # i 1
              [10000],   # h 0
              [00100],   # e 2
              [00010],   # l 3
              [00010]]]  # l 3
 
y_data = [[102334]]    # ihello
 
input_dim = 5  # one-hot size
hidden_size = 5  # output from the LSTM. 5 to directly predict one-hot
batch_size = 1   # one sentence
sequence_length = 6  # |ihello| == 6
 
= tf.placeholder(tf.float32, [None, sequence_length, hidden_size])  # X one-hot
= tf.placeholder(tf.int32, [None, sequence_length])  # Y label
 
#cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)
cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_size)
 
initial_state = cell.zero_state(batch_size, tf.float32)
outputs, _states = tf.nn.dynamic_rnn(
    cell, X, initial_state=initial_state, dtype=tf.float32)
 
weights = tf.ones([batch_size, sequence_length])
sequence_loss = tf.contrib.seq2seq.sequence_loss(
    logits=outputs, targets=Y, weights=weights)
loss = tf.reduce_mean(sequence_loss)
train = tf.train.AdamOptimizer(learning_rate=0.1).minimize(loss)
 
prediction = tf.argmax(outputs, axis=2)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        l, _ = sess.run([loss, train], feed_dict={X: x_one_hot, Y: y_data})
        result = sess.run(prediction, feed_dict={X: x_one_hot})
        print(i, "loss:", l, "prediction: ", result, "true Y: ", y_data)
 
        # print char using dic
        result_str = [idx2char[c] for c in np.squeeze(result)]
        print("\tPrediction str: "''.join(result_str))
 
'''
0 loss: 1.55474 prediction:  [[3 3 3 3 4 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  lllloo
1 loss: 1.55081 prediction:  [[3 3 3 3 4 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  lllloo
2 loss: 1.54704 prediction:  [[3 3 3 3 4 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  lllloo
3 loss: 1.54342 prediction:  [[3 3 3 3 4 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  lllloo
...
1998 loss: 0.75305 prediction:  [[1 0 2 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  ihello
1999 loss: 0.752973 prediction:  [[1 0 2 3 3 4]] true Y:  [[1, 0, 2, 3, 3, 4]]
    Prediction str:  ihello
'''
 
cs


*RNN - LSTM 구현 소스 (아리아리아리랑)

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
49
50
51
52
53
54
#-*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)  # reproducibility
 
idx2char = ['아''리''랑']
# 아리아리아리 -> 리아리아리랑
x_data = [[010101]]   # 아리아리아리랑
x_one_hot = [[[100],   # 아 0
              [010],   # 리 1
              [100],   # 아 0
              [010],   # 리 1
              [100],   # 아 0
              [010]]]  # 리 1
y_data = [[101012]]    # 리아리아리랑
 
input_dim = 3  # one-hot size
hidden_size = 3  # output from the LSTM.
batch_size = 1   # one sentence
sequence_length = 6  # |리아리아리랑| == 6
 
= tf.placeholder(tf.float32, [None, sequence_length, hidden_size])  # X one-hot
= tf.placeholder(tf.int32, [None, sequence_length])  # Y label
 
cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)
#cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_size)
 
initial_state = cell.zero_state(batch_size, tf.float32)
outputs, _states = tf.nn.dynamic_rnn(
    cell, X, initial_state=initial_state, dtype=tf.float32)
 
weights = tf.ones([batch_size, sequence_length])
sequence_loss = tf.contrib.seq2seq.sequence_loss(
    logits=outputs, targets=Y, weights=weights)
loss = tf.reduce_mean(sequence_loss)
train = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
 
prediction = tf.argmax(outputs, axis=2)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(2000):
        l, _ = sess.run([loss, train], feed_dict={X: x_one_hot, Y: y_data})
        result = sess.run(prediction, feed_dict={X: x_one_hot})
        print(i, "loss:", l, "prediction: ", result, "true Y: ", y_data)
 
        # print char using dic
        result_str = [idx2char[c] for c in np.squeeze(result)]
        print("\tPrediction str: "''.join(result_str))
 
 
 
 
 
cs





*문장을 Char별로 분석해서 숫자 부여하기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
tf.set_random_seed(777)  # reproducibility
 
sentence = ("A recurrent neural network is a class of artificial neural network "
            "where connections between units form a directed cycle. "
            "This allows it to exhibit dynamic temporal behavior. Unlike feedforward neural networks,"
            "RNNs can use their internal memory to process arbitrary sequences of inputs.")
 
print(sentence)
char_set = list(set(sentence))  # Set에 넣어서 중복 제거 후 List에 넣기
print(char_set)
 
char_dic = {w: i for i, w in enumerate(char_set)}
print(char_dic)
cs


*Full Sentence 분석하기 :

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
tf.set_random_seed(777)  # reproducibility
 
sentence = ("A recurrent neural network is a class of artificial neural network "
            "where connections between units form a directed cycle. "
            "This allows it to exhibit dynamic temporal behavior. Unlike feedforward neural networks,"
            "RNNs can use their internal memory to process arbitrary sequences of inputs.")
 
print(sentence) 
char_set = list(set(sentence))  # Set에 넣어서 중복 제거 후 List에 넣기
 
char_dic = {w: i for i, w in enumerate(char_set)}
print(char_dic)
 
data_dim = len(char_set)
hidden_size = len(char_set)
num_classes = len(char_set)
seq_length = 10  # Any arbitrary number
 
dataX = []
dataY = []
print(len(sentence))
for i in range(0len(sentence) - seq_length):
    x_str = sentence[i:i + seq_length]
    y_str = sentence[i + 1: i + seq_length + 1]
    print(i, x_str, '->', y_str)
 
    x = [char_dic[c] for c in x_str]  # x str to index
    y = [char_dic[c] for c in y_str]  # y str to index
 
    dataX.append(x)
    dataY.append(y)
 
 
batch_size = len(dataX)
print('batch_size:', batch_size)
 
= tf.placeholder(tf.int32, [None, seq_length])
= tf.placeholder(tf.int32, [None, seq_length])
 
# One-hot encoding
X_one_hot = tf.one_hot(X, num_classes) # one hot을 알아서 처리해주는 함수
print(X_one_hot)  # check out the shape
 
# Make a lstm cell with hidden_size (each unit output vector size)
cell = rnn.BasicLSTMCell(hidden_size, state_is_tuple=True) # LSTM으로 
cell = rnn.MultiRNNCell([cell] * 2, state_is_tuple=True) # MultiRNN 2개 계층으로 쌓기
 
# outputs: unfolding size x hidden size, state = hidden size
outputs, _states = tf.nn.dynamic_rnn(cell, X_one_hot, dtype=tf.float32)  # dynamic rnn 실행을 통해 output과 state 받기
 
print('output', outputs)
# (optional) softmax layer
X_for_softmax = tf.reshape(outputs, [-1, hidden_size])
softmax_w = tf.get_variable("softmax_w", [hidden_size, num_classes])
softmax_b = tf.get_variable("softmax_b", [num_classes])
outputs = tf.matmul(X_for_softmax, softmax_w) + softmax_b
 
# reshape out for sequence_loss
outputs = tf.reshape(outputs, [batch_size, seq_length, num_classes])
# All weights are 1 (equal weights)
weights = tf.ones([batch_size, seq_length])
sequence_loss = tf.contrib.seq2seq.sequence_loss(
    logits=outputs, targets=Y, weights=weights)
mean_loss = tf.reduce_mean(sequence_loss)
train_op = tf.train.AdamOptimizer(learning_rate=0.1).minimize(mean_loss)
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
for i in range(500):
    _, l, results = sess.run(
        [train_op, mean_loss, outputs], feed_dict={X: dataX, Y: dataY})
    for j, result in enumerate(results):
        index = np.argmax(result, axis=1)
        print(i, j, ''.join([char_set[t] for t in index]), l)
 
# Let's print the last char of each result to check it works
results = sess.run(outputs, feed_dict={X: dataX})
# result=170
 
# Full Sentense 뽑기
for j, result in enumerate(results):
    index = np.argmax(result, axis=1)
    if j is 0:  # print all for the first result to make a sentence
        print(''.join([char_set[t] for t in index]), end='')
    else:
        print(char_set[index[-1]], end='')
 
 
cs






+ Recent posts