문제

M이상 N이하의 소수를 모두 출력하는 프로그램을 작성하시오.


입력

첫째 줄에 자연수 M과 N이 빈 칸을 사이에 두고 주어진다. (1 ≤ M ≤ N ≤ 1,000,000) M이상 N이하의 소수가 하나 이상 있는 입력만 주어진다.


출력

한 줄에 하나씩, 증가하는 순서대로 소수를 출력한다.


코드

#include <iostream>
#include <cmath>

using namespace std;

int main()
{   
    // :: Input
    int start, end;
    cin >> start >> end;

    // :: Array
    bool* isNotPrime = new bool[end + 1];
    isNotPrime[0] = true;
    isNotPrime[1] = true;

    // :: Process
    string result = "";
    // :: 소수인지 판별 할 자연수의 제곱근을 기준으로 그 숫자의 약수들의 곱셈은 대칭적으로 곱셈이 일어나게 됩니다. 
    // :: 따라서 소수인지 판별할때는 그 자연수의 제곱근 이하의 수까지만 검사를 하면 됩니다.
    // :: 출처: https://velog.io/@tmpks5/Algorithm-소수를-판별하는-방법-제곱근-나누기
    for (int i = 1; i <= sqrt(end); i++)
    {
        // :: Skip if not prime
        if(isNotPrime[i] == true) continue;
        
        // :: Mark as not prime
        for (int j = i * 2; j <= end; j += i)
        {
            isNotPrime[j] = true;
        }
    }
    
    // :: Output
    for (int i = start; i <= end; i++){
        if (isNotPrime[i] == false){
            result += to_string(i) + "\n";
        }
    }
    cout << result;
    return 0;
}

참고

'C++ > Baekjoon' 카테고리의 다른 글

백준 1978: 소수 찾기  (0) 2023.01.28
백준 11653: 소인수분해  (0) 2023.01.26
백준 5597: 과제 안 내신 분..?  (0) 2022.12.23
백준 10807: 개수 세기  (0) 2022.12.17
백준 2839: 설탕 배달  (0) 2022.12.14
블로그 이미지

RIsN

,

[Unity] 가로 Swipe 판단

Unity 2023. 1. 22. 17:44

목표: 가로 Swipe를 토대로 캐릭터 카메라 회전

  • Event에 익숙해지기 위해서 Event 사용
    • Scene이 바뀌어도 딱히 문제 없이 사용하기 위함
private Coroutine iCoroutine_Input = null;
public void StartInput()
{
    this.iCoroutine_Input = this.StartCoroutine(this.IENInput());
}
public event System.Action<float> eSwipeHorizontal = null;
private IEnumerator IENInput()
{
    while (true)
    {
        // :: Swipe Horizontal
        // :: 처음 터치
        if (Input.GetMouseButtonDown(0))
        {
            // :: 터치 시작 위치
            Vector2 startPos = Input.mousePosition;
            // :: 터치 중
            while (Input.GetMouseButton(0))
            {
                // :: 터치 끝 위치
                Vector2 endPos = Input.mousePosition;
                // :: 터치 방향
                Vector2 swipe = endPos - startPos;
                // :: 터치 방향 이벤트
                this.eSwipeHorizontal?.Invoke(swipe.x);
                yield return null;
            }
        }
        yield return null;
    }
}
public void StopInput()
{
    if (this.iCoroutine_Input != null)
    {
        this.StopCoroutine(this.iCoroutine_Input);
        this.iCoroutine_Input = null;
    }
}

 

블로그 이미지

RIsN

,

목표: 게임의 레시피 UI가 카메라를 계속 바라볼 필요가 있음

  • 주의
    • 빈 게임 오브젝트를 만들고 거기에 스크립트를 부착할 필요가 있음.
    • 내부의 이미지나 글은 조금 각도 등이 수정이 가능한 형태로 만들어야 나중에 편해짐

예) 방식

using System.Collections;
using UnityEngine;

public class GearTool_LookAtCamera : _Gear
{
    public override void Init() { }

    // :: 따라갈 카메라 혹은 오브젝트
    [SerializeField] private Transform iCamera = null;

    // :: 쳐다보기
    void Update()
    {
        if (this.iCamera == null) this.iCamera = Camera.main.transform;

        this.transform.LookAt(
            this.transform.position + this.iCamera.rotation * Vector3.forward,
            this.iCamera.rotation * Vector3.up);
    }
}
  • _Gear는 현재 쓰고 있는 형식, MonoBehaviour로 사용하거나, 상황에 맞춰서 사용할 것
블로그 이미지

RIsN

,

목표: TextMeshPro에서 숫자가 바뀔 때마다 카운팅 하여 숫자를 집어 넣도록 처리

using System.Collections;

public static class ToolText
{
    public static void CountingTo(this TMPro.TMP_Text _targetText, int _goal)
    {
        // :: 코루틴을 실행할 녀석 확인
        // :: 지금 구조에서는 App이 모든 코루틴을 실행하고 관리할 예정
        App.oInstance.StartCoroutine(_targetText.IENCountingTo(_goal));
    }
    public static IEnumerator IENCountingTo(this TMPro.TMP_Text _targetText, int _goal)
    {
        // :: 현재 값
        int current = int.Parse(_targetText.text);

        // :: Up일 경우
        while (current < _goal)
        {
            if (current + 100 < _goal) current += 100;
            else if (current + 10 < _goal) current += 10;
            else current++;

            _targetText.text = string.Format("{0}", current);
            yield return null;
        }
        // :: Down일 경우
        while (current > _goal)
        {
            if (current - 100 > _goal) current -= 100;
            else if (current - 10 > _goal) current -= 10;
            else current--;

            _targetText.text = string.Format("{0}", current);
            yield return null;
        }

        // :: 마지막 재확인
        _targetText.text = string.Format("{0}", _goal);
    }
}
블로그 이미지

RIsN

,

목표: 3D 카메라로 바라보는 3D 오브젝트의 위치에 UI 카메라 상의 캔버스에 이미지를 표시
>> 사용 이유: 내가 선호하는 구조가 3D 카메라와 UI카메라의 복합적인 구조

using System;
using UnityEngine;

public static class ToolCamera
{
    public static Vector3 ConvertPosition3DTo2DLocal(this Camera _camera3D,
    Camera _camera2D, Canvas _canvas, Vector3 _position3D)
    {
        // :: 3D 카메라에서의 3D 위치를 3D 카메라에서의 2D 위치로 변경
        Vector3 position2Din3D = _camera3D.WorldToScreenPoint(_position3D);

        // :: 3D 카메라에서의 2D 위치를 UI(2D) 카메라에서의 2D 로컬 위치로 변경
        Vector2 result;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            _canvas.transform as RectTransform, position2Din3D, _camera2D, out result);

        // :: Z축은 0으로 고정
        return new Vector3(result.x, result.y, 0);
    }
}

 

블로그 이미지

RIsN

,

1. 애니메이터 컨트롤러 켜기

2. 2개의 레이어(행동, 표정)를 만들기
>> 마스크 등으로 행동 + 행동 등도 가능하지만, 우선 지금 필요한 건 행동 + 표정

3. 2개의 레이어(행동, 표정) 전부 weight 수치를 1로 설정

4. 실행시키면 동시에 애니메이션 2개(앉아서 움직임 + 눈 깜빡임)가 같이 실행되는 것을 확인 가능합니다.

 

블로그 이미지

RIsN

,

  • 해당 이미지의 Sprite Mode가 설정이 안되어 있는 경우가 있으며, 그럴 경우 해당 항목을 설정해줘야 합니다.
블로그 이미지

RIsN

,

문제

X대학 M교수님은 프로그래밍 수업을 맡고 있다. 교실엔 학생이 30명이 있는데, 학생 명부엔 각 학생별로 1번부터 30번까지 출석번호가 붙어 있다.

교수님이 내준 특별과제를 28명이 제출했는데, 그 중에서 제출 안 한 학생 2명의 출석번호를 구하는 프로그램을 작성하시오.


입력

입력은 총 28줄로 각 제출자(학생)의 출석번호 n(1 ≤ n ≤ 30)가 한 줄에 하나씩 주어진다. 출석번호에 중복은 없다.


출력

출력은 2줄이다. 1번째 줄엔 제출하지 않은 학생의 출석번호 중 가장 작은 것을 출력하고, 2번째 줄에선 그 다음 출석번호를 출력한다.


코드

#include <iostream>
#include <map>

using namespace std;

int main() {
    // >> Contain
    map<int, bool> dictionary; // : 키, 밸류 격납 변수 제작
    for(int index = 1; index <= 30; index++) {
        dictionary.insert(pair<int, bool>(index, false));
    }

    // >> Input
    for(int index = 0; index < 28; index ++) {
        // >> Process
        int input;
        cin >> input;
        dictionary.erase(input); // : 키를 통해 밸류를 삭제
    }

    // >> Output
    for(pair<int, bool> ele:dictionary){
		cout << ele.first << endl;
	}
}

참고

'C++ > Baekjoon' 카테고리의 다른 글

백준 11653: 소인수분해  (0) 2023.01.26
백준 1929: 소수 구하기  (0) 2023.01.24
백준 10807: 개수 세기  (0) 2022.12.17
백준 2839: 설탕 배달  (0) 2022.12.14
백준 2869: 달팽이는 올라가고 싶다  (0) 2022.12.06
블로그 이미지

RIsN

,

Code

private short ByteToInt16(byte[] _byte, bool _littleEndian = false) {
    if(_littleEndian) {
        return (short)(_byte[0] | _byte[1] << 8);
    } else {
        return (short)(_byte[1] | _byte[0] << 8);
    }
}
private ushort ByteToUInt16(byte[] _byte, bool _littleEndian = false) {
    if(_littleEndian) {
        return (ushort)(_byte[0] | _byte[1] << 8);
    } else {
        return (ushort)(_byte[1] | _byte[0] << 8);
    }
}
  • Little Endian
    • Byte 저장 순서에 관한 것으로 낮은 바이트를 낮은 주소에 넣는다.
      • 반대는 Big Endian
      • 엔디언(Endian)이라는 용어가 나오는데, 이건 조너선 스위프트의 작품인 《걸리버 여행기》에서 유래한 단어다. 작중 릴리퍼트라는 난쟁이들이 사는 나라에서 달걀을 먹을 때 뭉툭한 끝을 깨먹은 사람들과 뾰족한 끝을 깨먹는 사람들이 자기들이 옳다며 논쟁을 벌이는데, 여기서 뭉툭한 끝을 깨먹는 사람들을 큰 끝(big end)을 깨먹는다고 ian을 붙여 big endian이라고 부르고, 반대의 경우를 작은 끝(little end)을 깨먹는다고 little endian이라고 부른다.
  • | or 연산
  • << 왼쪽 시프트 연산

P.S. getInt24()의 경우

private int ByteToInt24(byte[] _byte, bool _littleEndian = false) {
    if(_littleEndian) {
        return (int)(_byte[0] | _byte[1] << 8 | _byte[2] << 16);
    } else {
        return (int)(_byte[2] | _byte[1] << 8 | _byte[0] << 16);
    }
}
private uint ByteToUInt24(byte[] _byte, bool _littleEndian = false) {
    if(_littleEndian) {
        return (uint)(_byte[0] | _byte[1] << 8 | _byte[2] << 16);
    } else {
        return (uint)(_byte[2] | _byte[1] << 8 | _byte[0] << 16);
    }
}

'C#' 카테고리의 다른 글

[VSCode: Error] Mac OS에서 FSharp Path 에러 생길 때  (0) 2023.05.09
미로 생성 알고리즘  (0) 2023.02.07
GetHashCode  (0) 2021.04.23
백준 1193 : 분수찾기  (0) 2021.02.03
백준 2292 : 벌집  (0) 2021.02.02
블로그 이미지

RIsN

,

문제

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


입력

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


출력

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


코드

#include <iostream>
#include <map>

using namespace std;

int main() {
    // >> Input
    int count = 0;
    cin >> count;

    // >> Process
    map<int, int> dictionary; // : 키, 밸류 격납 변수 제작
    for(int index = 0; index < count; index++) {
        // :: 키 입력
        int key = 0;
        cin >> key;

        // : 키가 존재하지 않을 때
        if(dictionary.find(key) == dictionary.end()) {
            dictionary[key] = 1;
        } 
        // :: 키가 존재할 때
        else {
            dictionary[key]++;
        }
    }
    // :: 찾아야 하는 숫자 입력
    int number;
    cin >> number;

    // >> Output
    // :: 찾아야 하는 숫자가 격납 변수에 없을 때
    if(dictionary.find(number) == dictionary.end()) {
        cout << "0" << endl;
    } 
    // ::: 찾아야 하는 숫자가 격납 변수에 있을 때
    else {
        cout << dictionary[number] << endl;
    }
}

참고

'C++ > Baekjoon' 카테고리의 다른 글

백준 1929: 소수 구하기  (0) 2023.01.24
백준 5597: 과제 안 내신 분..?  (0) 2022.12.23
백준 2839: 설탕 배달  (0) 2022.12.14
백준 2869: 달팽이는 올라가고 싶다  (0) 2022.12.06
백준 10250: ACM 호텔  (0) 2022.12.05
블로그 이미지

RIsN

,