All permutations of length k from n characters with repetition in CPP

后端 未结 4 1429
Happy的楠姐
Happy的楠姐 2020-12-15 14:43

I would like to know if there is already an implementation in CPP to find all permutations of n characters of length k(1,2,3,4 etc) with repetitions. I hope there is but i c

4条回答
  •  既然无缘
    2020-12-15 15:19

    This solution works out for all standard container and also static arrays. I think this can be used also for classes and structures

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    template
    bool nextPermutationWithRepetition(InputIt begin, InputIt end, T from_value, T to_value) {
        auto it = std::find_if_not(std::make_reverse_iterator(end),
                                   std::make_reverse_iterator(begin),
                                   [&to_value](auto current) { return to_value == current; });
    
        if (it == std::make_reverse_iterator(begin))
            return false;
    
        auto bound_element_iterator = std::prev(it.base());
    
        (*bound_element_iterator)++;
        std::fill(std::next(bound_element_iterator), end, from_value);
    
        return true;
    }
    
    int main() {
        std::list vec(3, 0);
    
        do {
            std::copy(vec.begin(), vec.end(), std::ostream_iterator(std::cout, " "));
            std::cout << std::endl;
        } while (nextPermutationWithRepetition(vec.begin(), vec.end(), 0, 2));
    
        return  0;
    }
    

提交回复
热议问题