1번 개수 세기

문제 

총 N개의 정수가 주어졌을 때, 정수 v가 몇 개인지 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 정수의 개수 N(1 ≤ N ≤ 100)이 주어진다. 둘째 줄에는 정수가 공백으로 구분되어 있다. 셋째 줄에는 찾으려고 하는 정수 v가 주어진다. 입력으로 주어지는 정수와 v는 -100보다 크거나 같으며, 100보다 작거나 같다.

 

출력

첫째 줄에 입력으로 주어진 N개의 정수 중에 v가 몇 개인지 출력한다.

 

배열에 저장하고 조건에 맞는 값을 출력한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int n, v, count;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++){
        cin >> arr[i];
    }
    
    cin >> v;
    for (int i = 0; i < n; i++){
        if (arr[i] == v)
            count++;
    }
    cout << count;
    return 0;
}

 

입력될 크기인 n 만큼의 크기의 배열을 선언하고 반복문으로 배열에 값들을 저장한다.

 

그리고 v의 입력을 받아 반복문으로 배열을 순회하면서 같은 값인 경우 count를 증가시키고 최종 개수를 출력한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        int[] arr = new int[n];
        string input = Console.ReadLine().Trim();
        string[] input_arr = input.Split(' ');
        for (int i = 0; i < n; i++){
            arr[i] = int.Parse(input_arr[i]);
        }
        int v = int.Parse(Console.ReadLine());
        int count = 0;
        for (int i = 0; i < n; i++){
            if (arr[i] == v)
                count++;
        }
        Console.WriteLine(count);
    }
}

 

Python

n = int(input())
values = input().strip().split(' ')
arr = [0] * n
for i in range(n):
    arr[i] = int(values[i]);
v = int(input())
count = 0;
for i in range(n):
    if arr[i] == v:
        count += 1
print(count)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').split('\n');
const n = parseInt(input[0]);
const values = input[1].split(' ');
const v = parseInt(input[2]);
let count = 0;
const val_arr = new Array(n);
for (let i = 0; i < n; i++){
    val_arr[i] = parseInt(values[i]);
}
for (let i = 0; i < n; i++){
    if (val_arr[i] === v)
        count++;
}
console.log(count);

 

더 효율적인 방법도 있지만 1차원 배열을 사용해서 푸는걸 중점으로 두었기 때문에 불필요한 변수와 반복문이 사용되기도 한다.

 

2번 X보다 작은 수

문제

정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 N과 X가 주어진다. 

(1 ≤ N, X ≤ 10,000) 둘째 줄에 수열 A를 이루는 정수 N개가 주어진다. 주어지는 정수는 모두 1보다 크거나 같고, 10,000보다 작거나 같은 정수이다.

 

출력

X보다 작은 수를 입력받은 순서대로 공백으로 구분해 출력한다. X보다 작은 수는 적어도 하나 존재한다.

 

1번을 풀었던 것처럼 배열을 사용하는데 중점을 둔다.

 

C++

#include <iostream>
using namespace std;
int main(){
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    int n, x;
    cin >> n;
    cin >> x;
    int arr[n];
    for (int i = 0; i < n; i++){
        cin >> arr[i];
    }
    for (int a : arr){
        if (a < x){
            cout << a << " ";
        }
    }
    return 0;
}

 

배열의 모든 요소를 순회할 때는 for (int a : arr)를 사용할 수 있다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string input = Console.ReadLine();
        string[] input_arr = input.Split(' ');
        int n = int.Parse(input_arr[0]);
        int x = int.Parse(input_arr[1]);
        input = Console.ReadLine();
        input_arr = input.Split(' ');
        int[] arr = new int[n];
        for (int i = 0; i < n; i++){
            arr[i] = int.Parse(input_arr[i]);
        }
        
        foreach(int a in arr){
            if (a < x){
                Console.Write($"{a} ");
            }
        }
    }
}

 

Python

n, x = map(int, input().split())
str_arr = input().split();
arr = [0] * n;
for i in range(n):
    arr[i] = int(str_arr[i])
for i in range(n):
    if arr[i] < x :
        print(f"{arr[i]} ", end="")

 

출력 시 print는 기본적으로 줄 바꿈을 실행하므로 end=""로 설정해서 줄 바꿈을 제거한다.

 

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').split('\n');
const [n, x] = input[0].split(' ').map(Number);
const values = input[1].split(' ').map(Number);
let result = [];
values.forEach(value => {
    if (value < x) {
        result.push(value);
    }
});

console.log(result.join(' '));

 

각각의 입력 값들을 정리하고 결과를 따로 배열에 저장한 뒤 일괄적으로 출력한다.

 

1, 2번 문제들은 고정 크기의 배열을 사용해서 풀었지만 가변 배열인 vector 나 list 등을 사용하면 더 간단하게 처리할 수 있는 문제이기 때문에 이후에는 가변 배열을 사용해서 풀어보기로 한다.

728x90
반응형

11번 A+B - 5

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10) 

입력의 마지막에는 0 두 개가 들어온다.

 

출력

각 테스트 케이스마다 A+B를 출력한다.

 

이번에는 얼마나 반복할지 횟수를 정해주지 않고 마지막 케이스를 통해 루프를 종료하는 조건으로 사용하면 된다.

 

C++

#include <iostream>
using namespace std;
int main(){
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    while(true){
        int a, b;
        cin >> a >> b;
        if (a + b == 0) break;
        else
            cout << a + b << "\n";
    }
}

 

두 값이 모두 0인 경우 반복문을 종료한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            while(true){
                int a, b;
                string input = Console.ReadLine();
                string[] arr = input.Split(' ');
                a = int.Parse(arr[0]);
                b = int.Parse(arr[1]);
                if (a + b == 0) break;
                else
                    Console.WriteLine(a + b);
            }
        }
    }
}

 

Python

while True:
    input_str = input()
    arr = input_str.split(' ')
    a = int(arr[0])
    b = int(arr[1])
    if a + b == 0:
        break
    print(a + b)

 

파이썬의 while문 사용법을 숙지한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
    const [a, b] = line.split(' ').map(Number);
    if (a + b === 0) break;
    console.log(a + b);
}

 

js는 입력을 한 번에 받은 다음 줄 별로 처리해야 하기 때문에 while이 아닌 for를 사용해서 처리한다.

 

12번 A+B - 4

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 A+B를 출력한다.

 

반복문 챕터의 마지막 문제이다. 종료 조건을 어떠한 것도 주지 않은 상태로 입력이 끝날 때까지 반복하여 처리해야 한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int a, b;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    while(cin >> a >> b){
        if (a + b == 0)
            break;
        cout << a + b << "\n";
    }
    return 0;
}

 

cin >> a >> b를 조건으로 체크하여 입력이 더 이상 없는 경우를 판단한다.

 

조건으로 사용하게 되면 EOF(End of File)에 도달하여 더 이상 입력이 없거나 잘못된 값이 입력된 경우 반복문이 종료된다.

 

using System;
class Program{
    static void Main(string[] args){
        using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            while (true){
                string input = Console.ReadLine();
                if (input == null) break;
                string[] arr = input.Split(' ');
                int a = int.Parse(arr[0]);
                int b = int.Parse(arr[1]);
                Console.WriteLine(a+b);
            }
        }
    }
}


C#에서 string의 초기화값은 null이기 때문에 input이 없는지 확인하기 위해서 null과 비교하여 검사한다.

 

Python

import sys
input = sys.stdin.read
arr = input().splitlines()
for line in arr:
    a, b = map(int, line.split())
    print(a+b)

 

기존 input 함수를 표준 입력으로 변경하여 전체 입력된 정보를 저장한 다음 배열을 읽어서 처리하여 입력된 값들만 처리한다.

 

또 다른 방법으로는 입력이 더 이상 없을 때 발생하는 에러를 체크해서 루프를 종료시킬 수 있다.

 

while True:
    try:
        input_str = input()
    except EOFError:
        break
    arr = input_str.split()
    a = int(arr[0]);
    b = int(arr[1]);
    print(a+b)

 

에러가 발생하는 지점을 예외처리하기 위해서 try ~ except를 사용한다. 입력이 더 이상 없을 때는 EOFError를 리턴한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
    const[a, b] = line.split(' ').map(Number);
    console.log(a+b);
}

 

모든 입력을 줄 바꿈으로 끊어서 배열로 저장한다. 그리고 이 배열을 순회하면서 각각의 케이스를 처리한다.

728x90
반응형

7번 A+B - 7

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력한다. 테스트 케이스 번호는 1부터 시작한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int t;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << "Case #" << i + 1 << ": " << a + b << "\n";
    }
    
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int t = int.Parse(Console.ReadLine());
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
        for (int i = 0; i < t; i++){
            int a, b;
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            a = int.Parse(arr[0]);
            b = int.Parse(arr[1]);
            Console.WriteLine($"Case #{i+1}: {a+b}");
        }
        Console.Out.Flush();
    }
}

 

Python

import sys
t = int(input());
for i in range(t):
    input_str = sys.stdin.readline().rstrip()
    arr = input_str.split(' ');
    a = int(arr[0])
    b = int(arr[1])
    print(f"Case #{i+1}: {a+b}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
const t = parseInt(input[0], 10);
const output = [];
for (let i = 1; i <= t; i++){
    const[a,b] = input[i].split(' ').map(Number);
    output.push(`Case #${i}: ${a+b}`);
}
console.log(output.join('\n'));

 

readFileSync에서 utf8로 명시적으로 인코딩해주지 않으면 반환되는 데이터가 기본적으로 Buffer 객체이므로 문자열 메서드와 함께 사용할 때 에러가 발생할 수 있다.

 

8번 A+B - 8

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

 

출력

각 테스트 케이스마다 "Case #x: A + B = C" 형식으로 출력한다. x는 테스트 케이스 번호이고 1부터 시작하며, C는 A+B이다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int t;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> t;
    for (int i = 0; i < t; i++){
        int a, b;
        cin >> a >> b;
        cout << "Case #" << i + 1 << ": " << a << " + " << b << " = " << a+b << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int t = int.Parse(Console.ReadLine());
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()));
        for (int i = 0; i < t; i++){
            string input = Console.ReadLine();
            string[] arr = input.Split(' ');
            int a = int.Parse(arr[0]);
            int b = int.Parse(arr[1]);
            Console.WriteLine($"Case #{i+1}: {a} + {b} = {a+b}");
        }
        Console.Out.Flush();
    }
}

 

Python

import sys
t = int(input())
for i in range(t):
    input_str = sys.stdin.readline().rstrip()
    arr = input_str.split()
    a = int(arr[0])
    b = int(arr[1])
    print(f"Case #{i+1}: {a} + {b} = {a+b}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const t = parseInt(input[0], 10);
const output = [];
for (let i = 1; i <= t; i++){
    const[a,b] = input[i].split(' ').map(Number);
    output.push(`Case #${i}: ${a} + ${b} = ${a+b}`);
}
console.log(output.join('\n'));

 

7, 8번 문제들은 출력 형식만 다르고 앞에 풀었던 문제와 동일한 방식으로 해결되기 때문에 크게 설명할 내용은 없다.

 

9번 별 찍기 - 1 

문제

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제

 

입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

 

출력

첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.

 

C++

string(size_t count, char ch)를 사용해서 count 만큼 문자를 출력하도록 만들어 본다.

#include <iostream>
#include <string>
using namespace std;
int main() {
    int n;
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        string stars(i, '*');
        cout << stars << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        using(StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            for (int i = 1; i <= n; i++){
                string stars = new string('*', i);
                Console.WriteLine(stars);
            }
        }
    }
}

 

C#은 new string(char, count)로 사용이 가능하다. 단일 문자를 반복하는 것이기 때문에 문자열이 아닌 문자를 사용해야 한다는 걸 유의한다.

 

기존 코드를 좀 더 깔끔하게 정리하기 위해서 using을 사용해서 내부에서 동작이 끝나면 자동으로 객체가 해제되도록 한다. 자세히 정리하자면 StreamWriter의 객체의 Dipose 메서드는 내부적으로 Flush를 호출하는데 using을 사용할 경우 객체가 해제될 때 Dispose 메서드가 자동으로 호출되면서 Flush도 처리된다. 따라서 별도로 Flush를 해줄 필요가 없어진다.

 

Python

n = int(input())
for i in range(1, n + 1):
    stars = '*' * i;
    print(stars)

 

파이썬은 문자에 횟수만큼 곱연산을 해서 개수만큼 표기가 가능하다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim();
const count = parseInt(input);
for (let i = 1; i <= count; i++){
    const stars = '*'.repeat(i);
    console.log(stars);
}

 

자바스크립트에서는 char.repeat으로 문자를 개수만큼 입력할 수 있다.

 

10번 별 찍기 - 2

문제

첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제

하지만, 오른쪽을 기준으로 정렬한 별(예제 참고)을 출력하시오.

 

입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

 

출력

첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.

 

9번 문제의 변형이다. N만큼 찍힌 별을 기준으로 이전 별들에게 공백이 추가로 필요하며 이 공백은 n - i 개가 된다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++){
        string space(n - i, ' ');
        string stars(i, '*');
        string result = space + stars;
        cout << result << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        using(StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
            for (int i = 1; i <= n; i++){
                string space = new string(' ', n - i);
                string stars = new string('*', i);
                string result = space + stars;
                Console.WriteLine(result);
            }     
        }
    }
}

 

Python

n = int(input())
for i in range(1, n+1):
    space = ' ' * (n - i);
    stars = '*' * i;
    result = space + stars;
    print(result);

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim();
const n = parseInt(input);
for (let i = 1; i <= n; i++){
    const space = ' '.repeat(n - i);
    const stars = '*'.repeat(i);
    const result = space + stars;
    console.log(result);
}

 

728x90
반응형

+ Recent posts