거북이처럼 천천히

알고리즘 (6월 12일) 본문

Algorithm/알고리즘 문제 풀이

알고리즘 (6월 12일)

유로 청년 2022. 6. 12. 20:13

1. 문제 (코딩도장, 연립일차방정식의 해 계산기)

https://codingdojang.com/scode/719?answer=28026#answer_28026 

 

코딩도장

프로그래밍 문제풀이를 통해서 코딩 실력을 수련

codingdojang.com


2. 생각

연립일차방정식은 ax+by+c=0, a'x+b'y+c'=0 의 형태이다, 이때 연립일차방정식의 해를 자동으로 구해주는 프로그램을 만들어라.

 

  • x와 y의 계수가 소수 형태이거나 분수 형태, 0인 경우는 제외
  • 입력 값은 ax+by=c , a'x+b'y=c' 형태를 갖는다고 가정

 

  1. 입력 값은 ax+by=c , a'x+b'y=c' 형태로 받는다.
  2. split 메소드와 contains 메소드를 이용하여 x의 계수와 y의 계수를 구한다.
    (if. 계수가 0이거나 상수 c가 존재하지 않으면 다시 입력받는다.)
  3. 가감법을 이용하여 해 x, y를 구한다.
  4. 결과를 출력한다.

3. 풀이 및 코드 분석

import java.util.Scanner;

public class test {
    // x 계수 찾기
    public static Integer findCoeffx(String equation) {

        if(equation.split("x|X")[0].equals("")) {
            return 1;
        }else if(equation.split("x|X")[0].equals("-")){
            return -1;
        }else if((equation.contains("x")|equation.contains("X"))==false){
            return 0;
        }else {
            return Integer.parseInt(equation.split("x|X")[0]);
        }
    }
    // y 계수 찾기
    public static Integer findCoeffy(String equation) {

        if(equation.split("x|X|y|Y")[1].equals("+")) {
            return 1;
        }else if(equation.split("x|X|y|Y")[1].equals("-")){
            return -1;
        }else if(equation.split("y|Y")[0].equals("")|equation.split("y|Y")[0].equals("-")) {
            return 0;
        }else if((equation.contains("y")|equation.contains("Y"))==false) {
            return 0;
        }else {
            return Integer.parseInt(equation.split("x|X|y|Y")[1]);
        }
    }
    // 상수 찾기
    public static Integer findConstant(String equation) {
        if(equation.contains("=")==false) {
            return 0;
        }else {
            return Integer.parseInt(equation.split("=")[1]);
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String[] equations = new String[2];
        int[] coeffx = new int[2];
        int[] coeffy = new int[2];
        int[] constant = new int[2];

        // 일차방정식 입력 받기
        int count = 0;      
        float answery, answerx;
        String inputX, inputY;      

        while(true) {
            System.out.printf("%d번째 일차방정식(ax+by=c):", count+1);
            equations[count] = scan.next();

            // 일차방정식의 계수 뽑아서 배열에 저장
            coeffx[count] = findCoeffx(equations[count]);
            coeffy[count] = findCoeffy(equations[count]);
            constant[count] = findConstant(equations[count]);

            // 만약 계수가 0이면 다시 입력
            if(coeffx[count]==0|coeffy[count]==0|constant[count]==0) {
                System.out.println("잘못 입력하셨습니다. 다시 입력하시오.");
            }else {
                count++;
            }

            // 방정식을 2개 입력했는지 
            if(count==2) {
                break;
            }
        }

        // y 값 구하기
        int diffy = coeffy[0]*coeffx[1] - coeffy[1]*coeffx[0];
        int diffConstant = constant[0]*coeffx[1] - constant[1]*coeffx[0];       
        answery = (float)diffConstant/diffy;
        // x 값 구하기
        answerx = (constant[0]-coeffy[0]*answery)/coeffx[0];

        // 결과 출력
        System.out.printf("x : %f\n", answerx);
        System.out.printf("y : %f", answery);
    }
}

4. 메모

 

  • 여러 개의 조건와 split 메소드를 이용하여 String을 나누는 방법
    →  조건문을 작성하는 공간에서 "|"를 이용하여 여러 개의 조건을 부여할 수 있다.

    →  ex) .split("조건1 | 조건2 | 조건3")

'Algorithm > 알고리즘 문제 풀이' 카테고리의 다른 글

알고리즘 (6월 13일) - (2)  (0) 2022.06.13
알고리즘 (6월 13일)  (0) 2022.06.13
알고리즘 (6월 10일)  (0) 2022.06.11
알고리즘 (6월 9일)  (0) 2022.06.09
알고리즘 (6월 8일)  (0) 2022.06.08