달력

52024  이전 다음

  • 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

'그외 주제들/알고리즘 연습'에 해당되는 글 1건

  1. 2013.10.14 강아지와 병아리

문제 출처

http://www.jungol.co.kr/prog/Hanal/hanalView.php?qs_code=1001&sk=&sv=&menu=&sst=qs_code&sod=asc&page=10&fv=1


강아지와 병아리
Time Limit : 1000MS

 

문제
강아지와 병아리의 합과 다리의 수를 입력받아 강아지와 병아리가 각각 몇 마리씩인지 구하는 프로그램을 작성하시오.

입력형식
강아지와 병아리의 합 1000 이하, 다리의 합 4000 이하의 정수를 공백으로 구분하여 입력받는다.
하나의 결과가 나온 후에도 계속 새로운 입력을 받다가, 0 이 입력되면 프로그램을 종료한다.

출력형식
강아지와 병아리가 각각 몇 마리씩인지 공백으로 구분하여 출력한다.
주어진 데이터로 마리수를 정할 수 없을 때는 "0" 을 출력한다.
데이터의 크기가 주어진 범위를 벗어날 경우는 "INPUT ERROR!"를 출력한다.

입력 예
25 80
15 10
1500 2000
0 0

출력 예
15 10
0
INPUT ERROR!

풀이..

package com.syjung;

import java.util.Scanner;

public class problem1 {
	
	boolean calc_value(String input )
	{
		int ani_sum, count_regs, max_count; 
		int x,y;
		boolean find_answer=false;
	
       // 문자열을 공백을 기준으로 숫자로 분리하기  
		String [] values = input.split(" ", 2);

		// Parameter counter 체크
		if( values.length != 2 )
		{
			System.out.println("Error!! Parameter counters are not 2.");
			return false;
		}
		
		// 문자열을 숫자로 변환, 동물숫자 합과 다리갯수
		ani_sum = max_count = Integer.parseInt(values[0]);
		count_regs = Integer.parseInt(values[1]);
		
		if( ani_sum > 1000 ) 
		{
			System.out.println("Error!! 동물의 합은 1000을 초과 할수 없습니다.");
			return true;
		}
		
		if( count_regs > 4000 ) 
		{
			System.out.println("Error!! 동물의 합은 4000을 초과 할수 없습니다.");
			return true;
		}
		
		if( ani_sum == 0 && count_regs== 0 ) 
		{
			System.out.println("종료!! 감사합니다~");
			return false;
		}
		
		// 동물숫자 합과, 다리갯수의 합과 일치하는 x,y를 찾는다. 
		for( x =0; x < max_count; x++ )
		{
			for(y=0; y < max_count; y++ )
			{
				if( x + y == ani_sum )
				{
					if( 4*x + 2 * y == count_regs )
					{
						System.out.println( String.format( "정답, 강아지 :%d, 병아리:%d ", x, y ) );
						find_answer = true;
						break; 
					}
				}
			}
		}
		
		if ( find_answer == false ) 
		{
			System.out.println( "정답이 없습니다.");
		}
				
		
		return true; 
	}

	/**
	 * @param args
	 */
	// Create a single shared Scanner for keyboard input
    private static Scanner scanner = new Scanner( System.in );

    // Program execution starts here
    public static void main ( String [] args )
    {    	
    	problem1 prb1 = new problem1();
    	String input;
    	
    	do
    	{
        // Prompt the user
        System.out.print( "Type some data for the program: " );

        // Read a line of text from the user.
        input = scanner.nextLine();

        // Display the input back to the user.
        System.out.println( "input = " + input );
    	
    	} while( prb1.calc_value(input) );

    	System.out.println( "프로그램이 정상 종료되었습니다." );
    } // end main method
}
Posted by 행복한삶~!!
|