Prometheus란?? 시계열(Time Series) 데이터베이스 기반 모니터링 시스템

[root@zoomoney opt]# tree
.
├── grafana
│   ├── Containerfile
│   └── provisioning
│       ├── dashborads
│       └── datasources
└── prometheus
    ├── Containerfile
    └── prometheus.yml

 

<Prometheus연동>

1.prometheus 디렉토리 이동후

buildah bud -t prometheus:v1 . 명령어 수행

 

<빌드된 컨테이너 이미지 확인>

[root@zoomoney opt]# podman images
REPOSITORY                 TAG                IMAGE ID      CREATED       SIZE
localhost/prometheus       v1                 9290fb8f4fad  24 hours ago  303 MB

 

<Container 이미지 기동>

podman run -d --name prometheus_v1 --pod zoomoney_pro localhost/prometheus:v1

 

<Grafana 연동>

1.grafana 디렉토리 이동후

buildah bud -t grafana:v1 . 명령어 수행

 

<빌드된 컨테이너 이미지 확인>

[root@zoomoney ~]# podimg
REPOSITORY                 TAG                IMAGE ID      CREATED       SIZE
localhost/prometheus       v1                 9290fb8f4fad  24 hours ago  303 MB
localhost/backend          v1                 163c2883438f  24 hours ago  573 MB
localhost/grafana          v1                 2d2ae498da92  29 hours ago   671 MB

 

<Container 이미지 기동>

podman run -d --name grafana_v1 --pod zoomoney_pro localhost/grafana:v1

 

<Container 확인>

CONTAINER ID  IMAGE                                    COMMAND               CREATED       STATUS       PORTS                                                                                                  NAMES               POD ID        PODNAME
2365106ac006  localhost/grafana:v1                                           24 hours ago  Up 24 hours  0.0.0.0:80->80/tcp, 0.0.0.0:7777->7777/tcp, 0.0.0.0:9091->9090/tcp, 0.0.0.0:33000->3000/tcp, 3000/tcp  grafana_v1          89a757316fa5  zoomoney_pro
005a100371c9  localhost/prometheus:v1                  --config.file=/et...  24 hours ago  Up 24 hours  0.0.0.0:80->80/tcp, 0.0.0.0:7777->7777/tcp, 0.0.0.0:9091->9090/tcp, 0.0.0.0:33000->3000/tcp, 9090/tcp  prometheus_v1       89a757316fa5  zoomoney_pro

 

 

<접속확인>

1.Grafana 접속 확인

 

2. Prometheus 가 Zoomoney 프로젝트 엔드포인트에 매트릭스를 수집하는지 Curl 명령어로 확인 결과

[root@zoomoney ~]# curl http://192.168.0.174:7777/zoomoney/actuator/prometheus
# HELP application_ready_time_seconds Time taken for the application to be ready to service requests
# TYPE application_ready_time_seconds gauge
application_ready_time_seconds{main_application_class="com.shinhan.zoomoney.ZooMoneyBackEndApplication"} 10.454
# HELP application_started_time_seconds Time taken to start the application
# TYPE application_started_time_seconds gauge
application_started_time_seconds{main_application_class="com.shinhan.zoomoney.ZooMoneyBackEndApplication"} 10.359
# HELP disk_free_bytes Usable space for path
# TYPE disk_free_bytes gauge
disk_free_bytes{path="/."} 2.43263488E9
# HELP disk_total_bytes Total space for path
# TYPE disk_total_bytes gauge
disk_total_bytes{path="/."} 1.1416895488E10
# HELP executor_active_threads The approximate number of threads that are actively executing tasks
# TYPE executor_active_threads gauge
executor_active_threads{name="applicationTaskExecutor"} 0.0
# HELP executor_completed_tasks_total The approximate total number of tasks that have completed execution
# TYPE executor_completed_tasks_total counter
executor_completed_tasks_total{name="applicationTaskExecutor"} 0.0
# HELP executor_pool_core_threads The core number of threads for the pool
# TYPE executor_pool_core_threads gauge
executor_pool_core_threads{name="applicationTaskExecutor"} 8.0
# HELP executor_pool_max_threads The maximum allowed number of threads in the pool
# TYPE executor_pool_max_threads gauge
executor_pool_max_threads{name="applicationTaskExecutor"} 2.147483647E9
# HELP executor_pool_size_threads The current number of threads in the pool
# TYPE executor_pool_size_threads gauge
executor_pool_size_threads{name="applicationTaskExecutor"} 0.0
# HELP executor_queue_remaining_tasks The number of additional elements that this queue can ideally accept without blocking
# TYPE executor_queue_remaining_tasks gauge
... 생략...

<Grafana 대쉬보드 구성> 

'Cloud' 카테고리의 다른 글

Jenkins  (0) 2025.04.22
Docker 와 Podman 차이  (0) 2025.03.23
Podman 으로 Zoomoney 프로젝트 배포하기  (0) 2025.03.22
Skopeo  (0) 2025.01.21
Dev-Ops  (0) 2025.01.20

Jenkins는 오픈 소스 자동화 서버로, 소프트웨어 개발의 빌드, 테스트, 배포 과정을 자동화하여 지속적인 통합(CI)과 지속적인 배포(CD)를 지원 

Jenkins의 주요 기능

  • 자동화된 빌드 및 테스트: 코드 변경 시 자동으로 빌드와 테스트를 수행하여 품질을 유지
  • 다양한 플러그인 지원: Git, Maven, Docker, Kubernetes 등과의 연동을 통해 유연한 파이프라인 구성이 가능
  • 웹 기반 인터페이스: 직관적인 UI를 통해 파이프라인 관리와 모니터링이 용이
  • Jenkinsfile을 통한 파이프라인 정의: 코드로 파이프라인을 정의하여 버전 관리와 협업

Jenkinsfile과 파이프라인 문법

Jenkinsfile은 Jenkins 파이프라인을 정의하는 스크립트 파일로, 두 가지 문법을 지원

  1. Declarative Pipeline: 구조화된 문법으로, 초보자에게 적합하며 가독성이 높아짐
  2. Scripted Pipeline: Groovy 기반의 유연한 스크립트 문법으로, 복잡한 로직 구현에 적합

Declarative Pipeline 

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
    post {
        success {
            echo 'Pipeline succeeded!'
        }
        failure {
            echo 'Pipeline failed.'
        }
    }
}

'Cloud' 카테고리의 다른 글

Zoomoney 프로젝트 Prometheus 와 Grafana 연동  (0) 2025.04.23
Docker 와 Podman 차이  (0) 2025.03.23
Podman 으로 Zoomoney 프로젝트 배포하기  (0) 2025.03.22
Skopeo  (0) 2025.01.21
Dev-Ops  (0) 2025.01.20
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main_9081_단어맞추기 {

	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int testCase = Integer.parseInt(br.readLine());
		for(int i=1; i<=testCase; i++) {
			String word = br.readLine();
			//각번지의 알파벳 문자를 비교하기 위하여 문자열 배열로 변환
			char [] array =word.toCharArray();
			
			nextPermutation(array);
			
			System.out.println(new String(array));
		}
		
        br.close();
	}//main

	private static void nextPermutation(char[] array) {
        // Step 1:   a<b 를 만족하는 두 수 찾기!! ==> 기준점(인덱스) 찾기
        //         arr[i]<  arr[i+1]
        //         위의 식을 만족하는 것을 찾는데 가장 오른쪽에 있는것을 선택
        //        그리고 arr[i]의 i가 기준점(피벗)이 된다!!
		int i=array.length-2;
		/*
		 ------------------
		 D   R   I   N   K
		 ------------------
index    0   1   2   3   4
		 
		 ------------------
		 B   O   O
		 ------------------
index    0   1   2 

		 
		 */
		while(i>=0 &&  array[i]  >=  array[i+1] ) {   //i>=0 : 반복문에서 배열의 인덱스를 벗어나는 참조를 하지 않기 위해
						
			                                     //array[i]  >=  array[i+1]   ==> 계속 i값을 감소하며
			                                     //array[i]  <  array[i+1] 를 만족하는 인덱스를 찾기 위해
			i--;
		}
		
		//다음 순열이 없다면  (전체 내림차순이라면)
//		if(i==-1)return;
		if(i<0)return;
		
 
        // Step 2: i번지의 값보다 큰값을 뒤에서 부터 찾기!!  ==>찾았으면 swap
		int j=array.length-1;
		while(array[i] >= array[j] ) {
			j--;
		}

		char temp = array[i];
		array[i]  = array[j];
		array[j]  = temp;
		
		
        // Step 3: i번지 뒤의 숫자들을 오름차순으로 정렬 (반전)
		int start=i+1 , end=array.length-1;
		while(start < end) {
			//앞뒤 교환
				temp     = array[start];
			array[start] = array[end];
			array[end]   = temp;
			
			//시작번지 증가,  끝번지 감소
			start++;  end--;
		}
		
//4
//HELLO
//DRINK
//SHUTTLE
//ZOO

	}

}

'코딩테스트' 카테고리의 다른 글

SORT 정리 / ArrayTesr  (0) 2025.04.12
NextPermutation  (0) 2025.04.12
CompleteBinaryTree(완전이진탐색)  (0) 2025.04.11
백준 - 1158 번 요세푸스  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11

예제 - 1 

import java.util.Arrays;

class Person  implements Comparable<Person> {
	String name;
	int age;
	String job;
	int score;
	
	public Person(String name, int age, String job, int score) {
		this.name = name;
		this.age = age;
		this.job = job;
		this.score = score;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age +
				", job=" + job + ", score=" + score + "]\n";
	}

	@Override
	public int compareTo(Person o) { //정렬의 기준을 정의~!!
		//this(Person)의 속성과 o(Person)의 속성을 비교
		//비교방법  this.속성 -  o.속성
		//결과: 음수, 0, 양수  ==> 음수의 경우 swap을 해줌  ==> 오름차순 정렬
		
//		return this.age - o.age; //오름차순정렬
		
		//만약 내림차순 정렬을 하고 싶다!!
		//1
		//return o.age - this.age;
		//2
		return -(this.age - o.age) ;
	}
	
}

public class ArraySortTest {

	public static void main(String[] args) {
	
		int[]su= {13, 8, 7, 10, 100, 5};	
		char[]ch= {'A','l','g','o','r','i','t','h','m'};
		String[]names= {"홍길동","길라임","김주원"};

		//API를 사용하여 배열에 대한 오름차순 정렬을 하자!!
	    Arrays.sort(su);
	    Arrays.sort(ch);
	    Arrays.sort(names);
		
		//배열 내용 출력
		System.out.println("정수배열>>"+Arrays.toString(su));
		System.out.println("문자배열>>"+Arrays.toString(ch));
		System.out.println("문자열배열>>"+Arrays.toString(names));
	
		//객체 배열 정렬

		Person p = new Person("갓길동",11,"학생",95);
//        ==>   이름    나이 직업   점수
		Person[] persons= {p ,
		    new Person("빛길동",19,"학생",80),
		 new Person("남길동",14,"학생",100),
		 new Person("여길동",17,"학생",99),
		 new Person("킹길동",15,"학생",56)};
		
		Arrays.sort(persons);
		System.out.println("사람배열>>"+Arrays.toString(persons));
//		class Person cannot be cast to class java.lang.Comparable 
//		(Person is in unnamed module of loader 'app'; 
//		java.lang.Comparable is in module java.base of loader 'bootstrap')
		
		
	}//main

}

 

예제 - 2

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;



public class ArraySortTest2 {
	
	static class Person  implements Comparable<Person> {
//	static class Person  implements Comparator<Person> {
		String name;
		int age;
		String job;
		int score;
		
		public Person() {
			// TODO Auto-generated constructor stub
		}
		
		public Person(String name, int age, String job, int score) {
			this.name = name;
			this.age = age;
			this.job = job;
			this.score = score;
		}

		@Override
		public String toString() {
			return "Person [name=" + name + ", age=" + age +
					", job=" + job + ", score=" + score + "]\n";
		}

		@Override
		public int compareTo(Person o) { //정렬의 기준을 정의~!!
			//this(Person)의 속성과 o(Person)의 속성을 비교
			//비교방법  this.속성 -  o.속성
			//결과: 음수, 0, 양수  ==> 음수의 경우 swap을 해줌  ==> 오름차순 정렬
			
			return this.age - o.age; //오름차순정렬
			
			//만약 내림차순 정렬을 하고 싶다!!
			//1
			//return o.age - this.age;
			//2
//			return -(this.age - o.age) ;
		}

//		@Override
//		public int compare(Person o1, Person o2) {
//			return -(o1.age - o2.age); //나이 오름차순 정렬
//		}
		
	}
	

	public static void main(String[] args) {
	
	
		//객체 배열 정렬
		ArrayList<Person> list = new ArrayList<>();
		list.add(new Person("갓길동",11,"학생",95));
		list.add(new Person("빛길동",19,"학생",80));
		list.add(new Person("남길동",14,"학생",100));
		list.add(new Person("여길동",17,"학생",99));
		list.add(new Person("킹길동",15,"학생",56));
		
//		Arrays.sort(list);//에러발생: Arrays클래스의 sort메소드를 통해 Collection(List)의 정렬을 할 수 없음~!!
		
	      Collections.sort(list); //Comparable일 경우
//        Collections.sort(list,new Person());  //Comparator일 경우 Collections.sort(list, Comparator객체);		
		
	      System.out.println(list);
	      
	}//main

}

 

예제 - 3

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;



public class ArraySortTest3 {
	
	static class Person {
		String name;
		int age;
		String job;
		int score;
		
		public Person() {
			// TODO Auto-generated constructor stub
		}
		
		public Person(String name, int age, String job, int score) {
			this.name = name;
			this.age = age;
			this.job = job;
			this.score = score;
		}

		@Override
		public String toString() {
			return "Person [name=" + name + ", age=" + age +
					", job=" + job + ", score=" + score + "]\n";
		}

	}//Person
	

	public static void main(String[] args) {
	
	
		//객체 배열 정렬
		ArrayList<Person> list = new ArrayList<>();
		list.add(new Person("갓길동",11,"학생",95));
		list.add(new Person("빛길동",19,"학생",80));
		list.add(new Person("남길동",19,"학생",100));
		list.add(new Person("여길동",19,"학생",99));
		list.add(new Person("킹길동",15,"학생",56));
		

		//나는 특정인터페이스를 상속받지 않는 Person을 사용하고 싶다!!
		
	   //추가 문제)  Person을 age오름차순으로 하되  같은 age의 경우 score내림차순으로 정렬하시오.
         Collections.sort(list, new Comparator<Person>() {//내부클래스 시작
        	             //implements Comparator의 의미        
			@Override
			public int compare(Person o1, Person o2) {
				if(o1.age == o2.age) return o2.score - o1.score;
				return o1.age - o2.age;
			}
        	                    
        	 
		  }//내부클래스 끝
         );
       
       
	      System.out.println(list);
	      
	}//main

}

정리

##### <sort정리>
1. 기본자료형, String 배열의 Sort
   ==> Arrays.sort( 기본자료형 배열 )사용

##### 2. 객체자료형(예:Person) 배열의 Sort
   ==> Arrays.sort( 객체자료형 배열 )  
   ==> ** 반드시 정렬객체에 implements Comparable 사용 **
            ==> compareTo메소드 오버라이딩 필요
                      return this.속성-o.속성;  //오름차순
                      return o.속성-this.속성; 또는 return -(this.속성-o.속성);  //내림차순

##### 3. List컬렉션을 사용하는 경우
   ==> ☆Collections.sort(컬렉션) 사용, ★Collections.sort(컬렉션, Comparator객체) 사용

   ==> ☆의 경우, 위의 2번처럼 ** 정렬객체에 implements Comparable **이면 동일하게 사용할 수 있음
            ==> compareTo메소드 오버라이딩 필요
                      return this.속성-o.속성;  //오름차순
                      return o.속성-this.속성; 또는 return -(this.속성-o.속성);  //내림차순

   ==> ★의 경우
          방법1)  ** 정렬 객체에 implements Comparator ** 사용
             ==> compare메소드 오버라이딩 필요
                      return o1.속성-o2.속성;  //오름차순
                      return o2.속성-o1.속성; 또는 return -(o1.속성-o2.속성);  //내림차순

          방법2)  정렬 객체에 implements Comparator 사용 하지 않고 익명의 내부클래스 사용
               ==> Collections.sort(컬렉션, new Comparator(){
                              compare메소드 오버라이딩
                        });

'코딩테스트' 카테고리의 다른 글

백준 - 9081 번 단어 맞추기  (0) 2025.04.12
NextPermutation  (0) 2025.04.12
CompleteBinaryTree(완전이진탐색)  (0) 2025.04.11
백준 - 1158 번 요세푸스  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11
import java.util.Arrays;

public class NextPermutationTest {
	
    public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        
        // Step 1:   a<b 를 만족하는 두 수 찾기!!
        //         arr[i]<  arr[i+1]
        //         위의 식을 만족하는 것을 찾는데 가장 오른쪽에 있는것을 선택
        //        그리고 arr[i]의 i가 기준점(피벗)이 된다!!
        
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }

        // Step 2: i번지의 값보다 큰값을 뒤에서 부터 찾기!!  ==>찾았으면 swap
        if (i >= 0) {
            int j = nums.length - 1;
            while (nums[i] >= nums[j]) {
                j--;
            }
            swap(nums, i, j);
        }

        // Step 3: i번지 뒤의 숫자들을 오름차순으로 정렬 (반전)
        reverse(nums, i + 1);
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    private void reverse(int[] nums, int start) {
        int end = nums.length - 1;
        while (start < end) {
            swap(nums, start, end);
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
    	NextPermutationTest np = new NextPermutationTest();
        int[] nums = {1, 3, 2};
        np.nextPermutation(nums);
        System.out.println(Arrays.toString(nums)); // 출력: [1, 3, 2]
    }
}

'코딩테스트' 카테고리의 다른 글

백준 - 9081 번 단어 맞추기  (0) 2025.04.12
SORT 정리 / ArrayTesr  (0) 2025.04.12
CompleteBinaryTree(완전이진탐색)  (0) 2025.04.11
백준 - 1158 번 요세푸스  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11
import java.util.ArrayDeque;
import java.util.Queue;

public class CompleteBinaryTree<T> { //완전이진트리 탐색
	
	private Object[] nodes;//(어떠한 타입의 데이터라도 허용하는)노드를 담을 배열 선언
	private int lastIndex; //마지막추가된 노드의 인덱스 정보
	private final int SIZE; //배열크기
	
	public CompleteBinaryTree(int size) {
		SIZE = size;
		nodes = new Object[size+1];  //0인덱스 사용 안함  ==> 인덱스와 노드번호를 일치시키기 위하여
	}
	
	//꽉찬상태 체크
    private boolean isFull() {
    	return lastIndex == SIZE;
    }
    
    //빈상태 체크
    private boolean isEmpty() {
    	return lastIndex == 0;
    }
	
	//데이터 추가
	public void add(T e) {
		
		//배열이 꽉찬 상태라면 그만!!
		if(isFull()) {
			System.out.println("포화상태입니다..");
			return;
		}
				
		nodes[++lastIndex] = e;
	}

	
	public void printTreeByPreOrder() {
		System.out.print("PreOrder :");
		printTreeByPreOrder(1); //1 ==> 루트노드
		System.out.println();
	}
	
    //전위순회(탐색) - 재귀호출 (DFS)
	private void printTreeByPreOrder(int current) { //current:부모노드!!
//		 1.current처리!
//		 2.왼쪽자식처리
//		 3.오른쪽자식처리
		
		//1.
		System.out.print(nodes[current]+" ");//현재노드 처리
		
		//2.
		if(current*2 <= lastIndex) //노드 범위내에서 재귀호출을 하자
		printTreeByPreOrder(current*2);
		
		//3.
		if(current*2+1 <= lastIndex)
		printTreeByPreOrder(current*2+1);
	}
	
	//============================= 중위 순회 ================================
	public void printTreeByInOrder() {
		System.out.print("InOrder :");
		printTreeByInOrder(1); //1 ==> 루트노드
		System.out.println();
	}
	
	//중위순회(탐색) - 재귀호출 (DFS)
	private void printTreeByInOrder(int current) { //current:부모노드!!
		 if(current > lastIndex) return;
//		 2.왼쪽자식처리
//		 1.current처리!
//		 3.오른쪽자식처리
		
		//2.
		printTreeByInOrder(current*2);
		
		//1.
		System.out.print(nodes[current]+" ");//현재노드 처리
		
		//3.
		printTreeByInOrder(current*2+1);
	}
	
//========================= 후위 순회 ===============================
	public void printTreeByPostOrder() {
		System.out.print("PostOrder :");
		printTreeByPostOrder(1); //1 ==> 루트노드
		System.out.println();
	}
	
    //후위순회(탐색) - 재귀호출 (DFS)
	private void printTreeByPostOrder(int current) { //current:부모노드!!
		 if(current > lastIndex) return;
//		 2.왼쪽자식처리
//		 3.오른쪽자식처리
//		 1.current처리!
		
		
		//2.
			printTreeByPostOrder(current*2);
		
		//3.
			printTreeByPostOrder(current*2+1);
		
		//1.
		System.out.print(nodes[current]+" ");//현재노드 처리
	}
	
	//큐를 통한 탐색 ==> BFS 탐색
	public void bfs() {
		Queue<Integer> queue = new ArrayDeque<Integer>();
		
		queue.offer(1);//루트노드가 시작점!!
		int current;
		
		while(!queue.isEmpty()) {//자식노드 추가!!
			current = queue.poll();
			
			//노드처리
			System.out.println(nodes[current]);
			
			//대기열에서 빠진 노드 정보를 가지고 == 자식 노드들 얻어오기 *2,  *2+1
			if(current*2 <= lastIndex)queue.offer(current*2); //왼쪽자식
			if(current*2+1 <= lastIndex)queue.offer(current*2+1);//오른쪽자식
			
		}
		
	}
	
}

'코딩테스트' 카테고리의 다른 글

SORT 정리 / ArrayTesr  (0) 2025.04.12
NextPermutation  (0) 2025.04.12
백준 - 1158 번 요세푸스  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11
QueueArray  (0) 2025.04.10

풀이 -1 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main_1158_요세푸스문제 {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer tokens = new StringTokenizer(br.readLine());
		
		int N = Integer.parseInt(tokens.nextToken());// 사람 수
		int K = Integer.parseInt(tokens.nextToken());// 제거할 간격
		
		//대기열 생성(큐 생성)
		Queue<Integer> queue = new ArrayDeque<Integer>();

		//1부터 N까지 큐에 사람(번호) 입력(삽입)
		for(int i=1; i<=N; i++) {
			queue.offer(i);
		}
		
		StringBuilder sb = new StringBuilder();//순열 요소값 저장
		sb.append("<");
		
		while(!queue.isEmpty()) {//큐가 빈 상태가 될때까지
			
			//앞의 번호를 뒤로 보내기!!  ==>  K-1명은 뒤로 보낸다!!
			for(int i=0; i<K-1; i++) {
//				1. queue.poll()
//				2. queue.offer(value)
				queue.offer(queue.poll());
			}
			
			//K번째 도달 ==> K번째 사람 제거
			sb.append(queue.poll());   //제거한 값(숫자 번호)을 출력(StringBuilder)에 추가
			
            if(!queue.isEmpty())  //맨 마지막 요소가 아니라면
			   sb.append(", "); 
			  
		}//while
		sb.append(">");
				
		System.out.println(sb.toString());// 요세푸스 순열 출력

		br.close();
	}// main

}

 

풀이-2

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;


//11866 요세푸스 문제0
public class Main_1158_요세푸스문제v2 {
/*
    Deque (Double Ended Queue)
    
- 양쪽 끝에서 삽입과 삭제가 모두 가능한 자료구조
- 앞(front)과 뒤(rear)에서 데이터를 넣거나 뺄 수 있음.    
    
    ----------------------------
      d1  d2  d3  d4  d5   d6
    ----------------------------
    
input  --->                            <--- input
output <---	                           ---> output
    
    
addFirst()                               addLast()
offerFirst()                             offerLast()
                                         add()
                                         offer()
                                 
removeFirst()                            removeLast()
pollFirst()                              pollLast()
remove()
poll()
                                 
getFist()                                getLast()
peek()                                   peekLast()
peekFist()                                         
    
    
*/    
  static int N;
  static int K;
  static StringBuilder sb = new StringBuilder();
  static Deque<Integer> queue = new ArrayDeque<>();
  
  //요세푸스 순열
  public static void main(String[] args) throws Exception{
	 
	 input();
	 func();
	 print();
	 
  }//end main
  
  static void input() throws Exception {
	  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	  StringTokenizer tokens = new StringTokenizer(br.readLine());
	  N = Integer.parseInt(tokens.nextToken()); //사람수
	  K = Integer.parseInt(tokens.nextToken());//제거할 사람의 위치

	  for (int i = 1; i <= N; i++)
	     queue.addLast(i); //1부터 N까지 번호 입력
  }//input
  
  static void func() {
	  sb.append('<');	 
	 while(!queue.isEmpty()) {
			 for(int i=1; i<=K; i++) {
				 if(i==K) { //제거할 위치라면				 
					 sb.append(queue.pollFirst());//제거한 사람의 번호출력
					 if(queue.size()>0)sb.append(", ");
				 }else {
					 queue.addLast(queue.pollFirst());//맨앞의 사람을 맨뒤로 이동
				 }
			 }
	 }
	  sb.append('>');	  
  }//func
  
  static void print() {
	  System.out.println(sb.toString());
  }//print
  
}//end class

'코딩테스트' 카테고리의 다른 글

NextPermutation  (0) 2025.04.12
CompleteBinaryTree(완전이진탐색)  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11
QueueArray  (0) 2025.04.10
백준 - 2161번 카드1  (0) 2025.04.10
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main_10845 {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();//출력할 (라인)데이터가 많다면 각각 라인 출력하기 보다는 모아서 한번에!!

		int N = Integer.parseInt(br.readLine());// 명령어 수
		
		//대기열 생성(큐 생성)
		Queue<Integer> queue = new ArrayDeque<Integer>();
		/*
		  queue
		  ======================================
out <----                                          <---- in
		  ======================================
		 */
		int last=-1;//마지막 요소를 저장!
		
		for (int i = 0; i < N; i++) { //명령어 수 만큼 반복
			StringTokenizer tokens = new StringTokenizer(br.readLine());
			switch (tokens.nextToken()) {// push pop size empty front back //공백으로 구분된 첫번째 토큰

				case "push":
					//큐에 데이터 삽입
					int value = Integer.parseInt(tokens.nextToken());
					queue.offer(value); //"push 1" 중 두번째 토큰
					last = value;
					break;
				case "pop":
					sb.append(queue.isEmpty() ? -1 : queue.poll()).append('\n');
					break;
				case "size":
					sb.append(queue.size()).append('\n');
					break;
				case "empty":  //if~else ~ return 데이터 => 삼항 연산자 (조건식)? A : B
					sb.append(queue.isEmpty() ? 1 : 0).append('\n');
					break;
				case "front":
					sb.append(queue.isEmpty() ? -1 : queue.peek())
					  .append('\n');
					break;
				case "back":
					sb.append(queue.isEmpty() ? -1 : last)
					  .append('\n');
					break;
			}
		} // 각 명령어 처리

		System.out.println(sb.toString());// 결과 출력

		br.close();
	}// main

}

'코딩테스트' 카테고리의 다른 글

CompleteBinaryTree(완전이진탐색)  (0) 2025.04.11
백준 - 1158 번 요세푸스  (0) 2025.04.11
QueueArray  (0) 2025.04.10
백준 - 2161번 카드1  (0) 2025.04.10
백준 - 10845번 큐  (0) 2025.04.10
import java.util.Arrays;

public class QueueArray {
	//1차원 배열을 사용하여 큐를 표현, 큐는 대기열을 의미!!
	private int[] queue; //대기열
	private int front, rear, size; //맨앞idx, 맨뒤idx, 전체 데이터 수
	
	public QueueArray(int capacity) {//capacity:배열의 크기
		queue = new int[capacity];
		front = 0;
		rear = -1;
		size = 0;
	}
	
	//데이터 저장	
	public void enqueue(int value) {
		if(size == queue.length) {//ArrayIndexOutOfBoundsException에  대한 처리
			System.out.println("큐 오버플로우!"); //한개이상의 데이터를 삭제(조회) 후에 입력해야 함!!
			return;
		}
		
//		rear++;//계속 증가하여 ArrayIndexOutOfBoundsException발생!!
		rear = (rear+1)% queue.length;
		
		queue[rear]=value;//핵심코드
		size++;//전체 데이터 수 증가
	}	
	
	//데이터 삭제와 조회
	public int dequeue() {
		if(size == 0) {//enqueue를 한번도 실행하지 않았을때의 처리
			System.out.println("큐 언더플로우!"); //한개이상의 데이터를 삭제(조회) 후에 입력해야 함!!
			return -1; //출력(삭제)할 데이터없음
		}
		
		
		
		int value = queue[front]; //큐이기 때문에 맨앞에 입력된 데이터 가져오기 ==> front사용!
//		front++; //그다음 데이터를 얻기 위하여
		//front를 계속 증가하여 ArrayIndexOutOfBoundsException발생!!
		
		front = (front+1)% queue.length;  //배열 인덱스 바운더리 내에서 로테이션 돌자!! (예: length가 5인 경우=> 0~4)
		
		size--;  //전체 데이터 수 감소
		return value;
	}
	
	//데이터 단순 조회	
    public int peek() {
        if (size == 0) return -1;
        return queue[front];
    }
	
	//큐의 빈상태 확인	
    public boolean isEmpty() {
        return size == 0;
    }

	public static void main(String[] args) {
		QueueArray queue = new QueueArray(5);
		queue.enqueue(10);//데이터 추가
		queue.enqueue(20);//데이터 추가
		queue.enqueue(30);//데이터 추가
		queue.enqueue(40);//데이터 추가
		queue.enqueue(50);//데이터 추가
		
		queue.enqueue(60);//데이터 추가
		
		System.out.println("deque==>"+queue.dequeue());
		System.out.println("deque==>"+queue.dequeue());
		System.out.println("deque==>"+queue.dequeue());
//		System.out.println("deque==>"+queue.dequeue());
//		System.out.println("deque==>"+queue.dequeue());
		
//		System.out.println("deque==>"+queue.dequeue());
		queue.enqueue(70);//데이터 추가

		System.out.println("peek==>"+queue.peek());
		System.out.println("isEmpty==>"+queue.isEmpty());
		
		System.out.println(Arrays.toString(queue.queue));
	}

}

'코딩테스트' 카테고리의 다른 글

백준 - 1158 번 요세푸스  (0) 2025.04.11
백준 - 10845번  (0) 2025.04.11
백준 - 2161번 카드1  (0) 2025.04.10
백준 - 10845번 큐  (0) 2025.04.10
백준 - 10828번 스택(Stack)  (1) 2025.04.09
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main_2161_카드 {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();//출력할 (라인)데이터가 많다면 각각 라인 출력하기 보다는 모아서 한번에!!

		int N = Integer.parseInt(br.readLine());// 카드 개수
		
		//대기열 생성(큐 생성)
		Queue<Integer> queue = new ArrayDeque<Integer>();

		//1부터 N까지 큐에 입력(삽입)
		for(int i=1; i<=N; i++) {
			queue.offer(i);
		}
		
		while(queue.size() > 1) {//카드가 한 장 남기 전까지
			sb.append(queue.poll())//맨앞의 수를 출력(버림,삭제)
			  .append(" ");
			
			
//		    int temp = queue.poll();
//		    queue.offer(temp);
		    queue.offer(queue.poll());//그 다음 수는 맨 뒤로 보내기
			  
		}//while
		
		//카드가 한장 남음!!
		//마지막 카드 출력
		sb.append(queue.poll());
		
		System.out.println(sb.toString());// 결과 출력

		br.close();
	}// main

}

'코딩테스트' 카테고리의 다른 글

백준 - 10845번  (0) 2025.04.11
QueueArray  (0) 2025.04.10
백준 - 10845번 큐  (0) 2025.04.10
백준 - 10828번 스택(Stack)  (1) 2025.04.09
백준-9012 괄호  (0) 2025.04.09

+ Recent posts