레이블이 알고리즘인 게시물을 표시합니다. 모든 게시물 표시
레이블이 알고리즘인 게시물을 표시합니다. 모든 게시물 표시

2013년 5월 27일 월요일

Programming Challenges: Jolly Jumpers

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

public class AnswerExercise9 {

  /**
  * @param args
  */
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  List<Integer> g_list = new ArrayList<Integer>();
 
  while(sc.hasNextLine()){

    String inputLine = sc.nextLine();
    StringTokenizer st = new StringTokenizer(inputLine);
    int n = Integer.parseInt(st.nextToken()); //수열에 포함된 정수의 갯수(1<=n<=3000)
    int bfr_val = 0;
    int aft_val = 0;
    int gap = 0;
    boolean isJolly = true;
   
    //수열의 첫번째 값
    bfr_val = Integer.parseInt(st.nextToken());

    if(!g_list.isEmpty()) g_list.clear();
    while(st.hasMoreTokens()){
      aft_val = Integer.parseInt(st.nextToken());
      gap = Math.abs(aft_val-bfr_val); //인접한 두 수의 차의 절대값
      //gap이 범위를 벗어나거나 같은 gap이 하나라도 있을 경우 break;
      if(gap<1 || gap>(n-1) || g_list.contains(gap)){
        isJolly = false;
        break;
      }
      g_list.add(gap);
      bfr_val = aft_val;
    }
    if(isJolly) System.out.println("Jolly");
    else System.out.println("Not Jolly");
  }
 }
}

Programming Challenges: Australian Voting

문제 : 호주식 투표법 전문(영어)

Key point : 최다, 최소 득표(투표 용지의 생존 후보 번호 중 최우선순위의 후보에 득표)에 근거해 공동 우승(최다득표==최소득표) 또는 우승자 구하기. 단, 최다 득표율이 50% 미초과시, 최소득표 후보를 탈락 시킨다.



2013년 5월 24일 금요일

Programming Challenges: Check the Check

import java.util.NoSuchElementException;
import java.util.Scanner;

public class Exercise7 {

static int x_WhiteKing, y_WhiteKing, x_BlackKing, y_BlackKing = 0; //흑백의 왕위치
static final int x_Min = 0;
static final int y_Min = 0;
static final int x_Max = 7;
static final int y_Max = 7;
static char[][] fld; //chess 판 규격
static boolean inChk = false;
static char key;
static int chessNo = 0;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lineNo = 0;

try {
while(sc.hasNext()){
x_WhiteKing = 0;
y_WhiteKing = 0;
x_BlackKing = 0;
y_BlackKing = 0; //흑백의 왕위치 초기화
lineNo = 0; //chess 행라인 초기화
fld = new char[x_Max+1][y_Max+1]; //chess판의 필드 초기화

int validIsFinal = 0;
String line = ""; //입력 라인
//fld값 및 k(K)의 위치 저장.
while(lineNo<=x_Max && !(line = sc.nextLine()).equals("")){
setFldAndKingsLocate(line.toCharArray(), lineNo);
lineNo++;
if(line.equals("........")) validIsFinal = validIsFinal + 0;
else validIsFinal = validIsFinal + 1;
}

//빈칸을 건너뛰고, 체스가 모두 '.'으로 이뤄진 경우 전체 while문을 종료시킨다.
if(line.equals(""))continue;
else if(validIsFinal == 0) break;

// 1. r(Rook) 
// 2. b(Bishop) 
// 3. q(Queen) 
// 4. p(Pawn)
// 5. n(Knight)

chessNo++;
//White in check
if(doKnight(x_WhiteKing, y_WhiteKing, 'n')){
printResult(chessNo, "White");
continue;
}
if(doRook(x_WhiteKing, y_WhiteKing, 'r')){
printResult(chessNo, "White");
continue;
}
if(doBishop(x_WhiteKing, y_WhiteKing, 'b')){
printResult(chessNo, "White");
continue;
}
if(doQueen(x_WhiteKing, y_WhiteKing, 'q')){
printResult(chessNo, "White");
continue;
}
if(doUpperPawn(x_WhiteKing, y_WhiteKing, 'p')){
printResult(chessNo, "White");
continue;
}

//Black in check
if(doRook(x_BlackKing, y_BlackKing, 'R')){
printResult(chessNo, "Black");
continue;
}
if(doQueen(x_BlackKing, y_BlackKing, 'Q')){
printResult(chessNo, "Black");
continue;
}
if(doBishop(x_BlackKing, y_BlackKing, 'B')){
printResult(chessNo, "Black");
continue;
}
if(doKnight(x_BlackKing, y_BlackKing, 'N')){
printResult(chessNo, "Black");
continue;
}
if(doBottomPawn(x_BlackKing, y_BlackKing, 'P')){
printResult(chessNo, "Black");
continue;
}

printResult(chessNo, "No");
}
} catch (IllegalStateException ise) {
ise.printStackTrace();
} catch (NoSuchElementException nsee) {
nsee.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ae){
ae.printStackTrace();
}

}

private static void printResult(int chessNo, String blackOrWhite){
StringBuffer sb = new StringBuffer();
sb.append("Game #");
sb.append(chessNo);
sb.append(": ");
sb.append(blackOrWhite);
sb.append(" king is in check.");

System.out.println(sb.toString());
}

private static boolean doRook(int x, int y, char keyName){
key = keyName;
if(goLeftStraight(x, y)) return true;
else if(goRightStraight(x, y)) return true;
else if(goUpperStraight(x, y)) return true;
else if(goBottomStraight(x, y)) return true;
else return false;
}

private static boolean doBishop(int x, int y, char keyName){
key = keyName;
if(goLeftUpperStraight(x, y)) return true;
else if(goLeftBottomStraight(x, y)) return true;
else if(goRightUpperStraight(x, y)) return true;
else if(goRightBottomStraight(x, y)) return true;
else return false;
}

private static boolean doQueen(int x, int y, char keyName){
key = keyName;
if(goLeftStraight(x, y)) return true;
else if(goRightStraight(x, y)) return true;
else if(goUpperStraight(x, y)) return true;
else if(goBottomStraight(x, y)) return true;
else if(goLeftUpperStraight(x, y)) return true;
else if(goLeftBottomStraight(x, y)) return true;
else if(goRightUpperStraight(x, y)) return true;
else if(goRightBottomStraight(x, y)) return true;
else return false;
}

private static boolean doKnight(int x, int y, char keyName){
key = keyName;
if(((x-1)>=x_Min)&&((y-2)>=y_Min)&&isBreakForKnight(x-1,y-2)) return inChk;
if(((x-2)>=x_Min)&&((y-1)>=y_Min)&&isBreakForKnight(x-2,y-1)) return inChk;
if(((x+1)<=x_Max)&&((y+2)<=y_Max)&&isBreakForKnight(x+1,y+2)) return inChk;
if(((x+2)<=x_Max)&&((y+1)<=y_Max)&&isBreakForKnight(x+2,y+1)) return inChk;
if(((x-1)>=x_Min)&&((y+2)<=y_Max)&&isBreakForKnight(x-1,y+2)) return inChk;
if(((x-2)>=x_Min)&&((y+1)<=y_Max)&&isBreakForKnight(x-2,y+1)) return inChk;
if(((x+1)<=x_Max)&&((y-2)>=y_Min)&&isBreakForKnight(x+1,y-2)) return inChk;
if(((x+2)<=x_Max)&&((y-1)>=y_Min)&&isBreakForKnight(x+2,y-1)) return inChk;

return false;
}

private static boolean doUpperPawn(int x, int y, char keyName){
key = keyName;
if(goLeftUpperOnce(x, y)) return true;
else if(goRightUpperOnce(x, y)) return true;
else return false;
}

private static boolean doBottomPawn(int x, int y, char keyName){
key = keyName;
if(goLeftBottomOnce(x, y)) return true;
else if(goRightBottomOnce(x, y)) return true;
else return false;
}

private static boolean goLeftStraight(int x, int y){
while((--x>=x_Min))
isBreak(x,y);
return inChk;
}

private static boolean goRightStraight(int x, int y){
while((++x<=x_Max))
isBreak(x,y);
return inChk;
}

private static boolean goUpperStraight(int x, int y){
while((--y>=y_Min))
isBreak(x,y);
return inChk;
}

private static boolean goBottomStraight(int x, int y){
while((++y<=y_Max))
isBreak(x,y);
return inChk;
}

private static boolean goLeftUpperStraight(int x, int y){
while((--x>=x_Min)&&(--y>=y_Min))
isBreak(x,y);
return inChk;
}

private static boolean goLeftBottomStraight(int x, int y){
while((--x>=x_Min)&&(++y<=y_Max))
isBreak(x,y);
return inChk;
}

private static boolean goRightUpperStraight(int x, int y){
while((++x<=x_Max)&&(--y>=y_Min))
isBreak(x,y);
return inChk;
}

private static boolean goRightBottomStraight(int x, int y){
while((++x<=x_Max)&&(++y<=y_Max))
isBreak(x,y);
return inChk;
}

private static boolean goRightUpperOnce(int x, int y){
if((++x<=x_Max)&&(--y>=y_Min))
isBreak(x,y);
return inChk;
}

private static boolean goLeftUpperOnce(int x, int y){
if((--x>=x_Min)&&(--y>=y_Min))
isBreak(x,y);
return inChk;
}

private static boolean goRightBottomOnce(int x, int y){
if((++x<=x_Max)&&(++y<=y_Max))
isBreak(x,y);
return inChk;
}

private static boolean goLeftBottomOnce(int x, int y){
if((--x>=x_Min)&&(++y<=y_Max))
isBreak(x,y);
return inChk;
}



private static boolean isBreak(int x, int y) throws ArrayIndexOutOfBoundsException{
try{
if(fld[x][y] == key){
inChk = true;
return true;
}else if(fld[x][y] == '.'){
return false;
}else{
return true;
}
}catch(ArrayIndexOutOfBoundsException ae){
ae.printStackTrace();
throw ae;
}
}

private static boolean isBreakForKnight(int x, int y){
if(fld[x][y] == key){
inChk = true;
return true;
}else{
return false;
}
}

private static void setFldAndKingsLocate(char[] val, int lineNo){
for(int y=0; y<val.length; y++){
fld[lineNo][y] = val[y];
if(val[y] == 'k'){
x_BlackKing = lineNo;
y_BlackKing = y;
}else if(val[y] == 'K'){
x_WhiteKing = lineNo;
y_WhiteKing = y;
}
}
}

}

2013년 5월 21일 화요일

Programming Challenges: LCD Display(PC/UVa ID: 110104/706)

Flow Diagram :


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AnswExercise4 {

  static final String REG_WHITESPACE = "\\s+";
  //가로바의 존재 여부(첫번째 행, 중간 행, 마지막 행)
  static final char[][] hor = {{1,0,1},{0,0,0},{1,1,1},{1,1,1},{0,1,0},
      {1,1,1},{1,1,1},{1,0,0},{1,1,1},{1,1,1}};
  //세로바의 존재 여부(위 왼쪽, 위 오른쪽, 아래 왼쪽, 아래 오른쪽)
  static final char[][] ver = {{1,1,1,1},{0,1,0,1},{0,1,1,0},{0,1,0,1},{1,1,0,1},
      {1,0,0,1},{1,0,1,1},{0,1,0,1},{1,1,1,1},{1,1,0,1}};
  /**
   * @param args
   */
  public static void main(String[] args) {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    String line = "";
    String[] sLine;
    int s = 0;
    String numLine = "";
    try {

      while((line = br.readLine()) != null){
        line = line.trim().replaceAll(REG_WHITESPACE, " ");
        sLine = line.split(REG_WHITESPACE);
        
        s = setNumber(Integer.parseInt(sLine[0]));    //숫자를 표시하는 크기( 1<= s <= 10)
        numLine = setNumLine(sLine[1]);         //표현할 숫자(0<=numLine<=99999999)
        
        // 0 0 이 들어오면 끝낸다.
        if(s == 0 && numLine == "0"){
          return;
        }
        
        String[] hor_bar = {"          ".substring(0, s),"---------".substring(0, s)};
        String[] ver_bar = {" ","|"};
        
        char[] num = numLine.toCharArray();
        String[][] fld = new String[num.length][5];
        for(int i=0; i<num.length; i++){
          int no = num[i] - '0';
          //첫번 행의 가로바
          fld[i][0] = " " + hor_bar[hor[no][0]] + " ";
          //위쪽 세로바
          fld[i][1] = ver_bar[ver[no][0]] + hor_bar[0] + ver_bar[ver[no][1]];
          //중간 행의 가로바
          fld[i][2] = " " + hor_bar[hor[no][1]] + " ";
          //아래쪽 세로바
          fld[i][3] = ver_bar[ver[no][2]] + hor_bar[0] + ver_bar[ver[no][3]];
          //마지막 행의 가로바
          fld[i][4] = " " + hor_bar[hor[no][2]] + " ";
        }
        
        //출력(출력 부분은 수정해야함.)
        StringBuffer sb = new StringBuffer();
        sb.append(System.getProperty("line.separator"));
        for(int b=0; b<5; b++){
          
          if(b==1 || b==3){
            for(int i=0; i<s; i++){
              for(int a=0; a<num.length; a++){
                sb.append(fld[a][b]);
              }
              sb.append(System.getProperty("line.separator"));
            }
          }else{
            for(int a=0; a<num.length; a++){
              sb.append(fld[a][b]);
            }
            sb.append(System.getProperty("line.separator"));
          }
        }
        System.out.println(sb.toString());
            
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    
  }
  
  private static int setNumber(int number){
    int l_number = Math.min(10, Math.max(number, 0));
    if(l_number != number){
      throw new IllegalArgumentException("s must be betwwen 1 and 10");
    }
    return l_number;
  }
  
  private static String setNumLine(String numLine){
    int l_numLine = Math.min(99999999, Math.max(Integer.parseInt(numLine), 0));
    if(l_numLine != Integer.parseInt(numLine)){
      throw new IllegalArgumentException("n must be betwwen 0 and 99999999");
    }
    return numLine;
  }

}

2013년 5월 20일 월요일

Programming Challenges: Minesweeper(PC/UVa ID: 110102/10189)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Exercise2Mdf {

  static int num = 0;
  final static String REG_WHITESPACE = "\\s+";
  /**
   * @param args
   */
  public static void main(String[] args) {
    System.out.println("Start!");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] nM;  //행렬(NxM)의 집합
    String[][] fld; //행렬에 따른 필드값
    String line = "";
    try {
      while((line = br.readLine())!=null){
        
        line = line.trim().replaceAll(REG_WHITESPACE, " ");
        nM = line.split(" ");
        int matrixN = Integer.parseInt(nM[0]);
        int matrixM = Integer.parseInt(nM[1]);
        
        fld = new String[matrixN][matrixM];
        if(Integer.parseInt(nM[0]) == 0 && Integer.parseInt(nM[1]) == 0){
          return;
        }
        
        //필드값 초기화
        for(int i=0; i<matrixN; i++){
          for(int j=0; j<matrixM; j++){
            fld[i][j] = "0";
          }
        }
        
        
        int bombLine = 0; //행렬 한 셋트당 지뢰밭의 행번호
        //행렬에 따른 지뢰의 갯수 저장.
        while((line = br.readLine())!=null){
          char[] bomb = line.toCharArray();
          
          for(int j=0; j<bomb.length; j++){
            if((j+1) == matrixM){
              break;
            }
            //핵심 : 현재 위치가 *이면 주위 8개 위치에 1을 더한다.
            if(bomb[j] == '*'){
              fld[bombLine][j] = "*";
              for(int a=bombLine-1; a<=bombLine+1; a++){
                for(int b=j-1; b<=j+1; b++){
                  if((a>=0) && (a<matrixN) &&(b>=0) && (b<matrixM)){
                    if(!fld[a][b].equals("*")){
                      fld[a][b] = String.valueOf(Integer.parseInt(fld[a][b])+1);
                    }
                  }
                }
              }
            }
          }
          
          bombLine++;
          
          if(bombLine == matrixN) break;
        }
        num++;  //지뢰밭 셋트 누적
        
        //출력 시작
        StringBuffer sb = new StringBuffer();
        sb.append(System.getProperty("line.separator"));
        sb.append("Field #"+num+":");
        for(int i=0; i<matrixN; i++){
          sb.append(System.getProperty("line.separator"));
          for(int j=0; j<matrixM; j++){
            sb.append(fld[i][j]);
          }
        }
        System.out.println(sb.toString());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}