💡 퀵 접속: cpp.kr/shuffle

shuffle

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 요소들을 무작위로 섞습니다. shuffle은 원본 범위를 직접 수정하며, 주어진 난수 생성기를 사용하여 요소들의 위치를 무작위로 재배치합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    std::cout << "원본 벡터: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    // 난수 생성기 초기화
    std::random_device rd;
    std::mt19937 gen(rd());
    
    // 벡터 섞기
    std::shuffle(numbers.begin(), numbers.end(), gen);
    
    std::cout << "섞은 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 3 4 5 6 7 8 9 10
섞은 후: 7 2 9 1 5 8 3 10 4 6

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>
#include <random>

int main() {
    std::string str = "Hello, World!";
    
    std::cout << "원본 문자열: " << str << std::endl;
    
    // 난수 생성기 초기화
    std::random_device rd;
    std::mt19937 gen(rd());
    
    // 문자열 섞기
    std::shuffle(str.begin(), str.end(), gen);
    
    std::cout << "섞은 후: " << str << std::endl;
    
    return 0;
}

실행 결과:

원본 문자열: Hello, World!
섞은 후: lW!o,dlHlre o

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <random>

class Person {
    std::string name;
    int age;
public:
    Person(const std::string& n, int a) : name(n), age(a) {}
    
    void print() const {
        std::cout << name << " (" << age << "세)" << std::endl;
    }
};

int main() {
    std::vector<Person> people = {
        Person("Alice", 20),
        Person("Bob", 30),
        Person("Charlie", 25),
        Person("David", 35),
        Person("Eve", 22)
    };
    
    std::cout << "원본 리스트:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    // 난수 생성기 초기화
    std::random_device rd;
    std::mt19937 gen(rd());
    
    // 리스트 섞기
    std::shuffle(people.begin(), people.end(), gen);
    
    std::cout << "\n섞은 후:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    return 0;
}

실행 결과:

원본 리스트:
Alice (20세)
Bob (30세)
Charlie (25세)
David (35세)
Eve (22세)

섞은 후:
David (35세)
Alice (20세)
Eve (22세)
Charlie (25세)
Bob (30세)

참고사항

  • shuffle은 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위를 직접 수정합니다.
  • 시간 복잡도는 O(n)입니다. 여기서 n은 범위의 크기입니다.
  • 난수 생성기는 반드시 제공해야 합니다.
  • random 헤더의 난수 생성기를 사용하는 것이 권장됩니다.
  • Fisher-Yates 셔플 알고리즘을 사용합니다.
  • 모든 가능한 순열이 동일한 확률로 발생합니다.
  • random_shuffle은 C++17부터 deprecated되었습니다.
  • 사용자 정의 타입에 대해서도 동작합니다.
  • 반복자가 가리키는 요소들의 교환이 가능해야 합니다.
함수 설명
shuffle(first, last, g) 범위 [first, last)의 요소들을 난수 생성기 g를 사용하여 무작위로 섞음