-
Notifications
You must be signed in to change notification settings - Fork 36
/
strtk_combinations.cpp
79 lines (61 loc) · 2.51 KB
/
strtk_combinations.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
*****************************************************************
* String Toolkit Library *
* *
* Combinations *
* Author: Arash Partow (2002-2020) *
* URL: http://www.partow.net/programming/strtk/index.html *
* *
* Copyright notice: *
* Free use of the String Toolkit Library is permitted under the *
* guidelines and in accordance with the most current version of *
* the MIT License. *
* http://www.opensource.org/licenses/MIT *
* *
*****************************************************************
*/
/*
Description: This example demonstrates the use of the next_combination
and for_each combination routines. Input is taken from the
command line as one positive integer (k) and a series of N
unique strings. Then all n-choose-k combinations are
streamed one per line to stdout.
Example usage:
strtk_combination 3 abc 123 def 456
Output:
123 456 abc
123 456 def
123 abc def
456 abc def
*/
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "strtk.hpp"
void usage(const std::string& msg = "")
{
std::cout << "usage: strtk_combination <r> <s_1> <s_2> .... <s_k>" << std::endl;
if (!msg.empty())
std::cout << "error message: " << msg << std::endl;
}
void print(std::vector<std::string>::iterator begin,
std::vector<std::string>::iterator end)
{
std::cout << strtk::join("\t",begin,end) << std::endl;
}
int main(int argc, char* argv[])
{
if (argc < 3) return (usage(),1);
std::size_t r = 0;
if (!strtk::string_to_type_converter(std::string(argv[1]),r))
return (usage("Invalid 'r' value."),1);
if (0 == r) return 0;
std::vector<std::string> str_lst;
strtk::parse(argc - 2, argv + 2, str_lst);
std::sort(str_lst.begin(),str_lst.end());
if (r > str_lst.size()) return (usage("r > k"),1);
strtk::for_each_combination(str_lst.begin(), str_lst.end(), r, &print);
return 0;
}