fork(2) download
  1. #include <algorithm>
  2. #include <iostream>
  3.  
  4. template <typename Iterator>
  5. inline bool next_combination(Iterator first,
  6. Iterator k,
  7. Iterator last);
  8.  
  9. int main () {
  10. int array[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  11. do {
  12. do {
  13. std::cout << array[0] << array[1] << array[2] << "\n";
  14. } while(std::next_permutation(array, array+3));
  15. } while(next_combination(array,array+3,array+8));
  16. }
  17.  
  18. template <typename Iterator>
  19. inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
  20. {
  21. /* Credits: Thomas Draper */
  22. // http://stackoverflow.com/a/5097100/8747
  23. if ((first == last) || (first == k) || (last == k))
  24. return false;
  25. Iterator itr1 = first;
  26. Iterator itr2 = last;
  27. ++itr1;
  28. if (last == itr1)
  29. return false;
  30. itr1 = last;
  31. --itr1;
  32. itr1 = k;
  33. --itr2;
  34. while (first != itr1)
  35. {
  36. if (*--itr1 < *itr2)
  37. {
  38. Iterator j = k;
  39. while (!(*itr1 < *j)) ++j;
  40. std::iter_swap(itr1,j);
  41. ++itr1;
  42. ++j;
  43. itr2 = k;
  44. std::rotate(itr1,j,last);
  45. while (last != j)
  46. {
  47. ++j;
  48. ++itr2;
  49. }
  50. std::rotate(k,itr2,last);
  51. return true;
  52. }
  53. }
  54. std::rotate(first,k,last);
  55. return false;
  56. }
  57.  
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
123
132
213
231
312
321
124
142
214
241
412
421
125
152
215
251
512
521
126
162
216
261
612
621
127
172
217
271
712
721
128
182
218
281
812
821
134
143
314
341
413
431
135
153
315
351
513
531
136
163
316
361
613
631
137
173
317
371
713
731
138
183
318
381
813
831
145
154
415
451
514
541
146
164
416
461
614
641
147
174
417
471
714
741
148
184
418
481
814
841
156
165
516
561
615
651
157
175
517
571
715
751
158
185
518
581
815
851
167
176
617
671
716
761
168
186
618
681
816
861
178
187
718
781
817
871
234
243
324
342
423
432
235
253
325
352
523
532
236
263
326
362
623
632
237
273
327
372
723
732
238
283
328
382
823
832
245
254
425
452
524
542
246
264
426
462
624
642
247
274
427
472
724
742
248
284
428
482
824
842
256
265
526
562
625
652
257
275
527
572
725
752
258
285
528
582
825
852
267
276
627
672
726
762
268
286
628
682
826
862
278
287
728
782
827
872
345
354
435
453
534
543
346
364
436
463
634
643
347
374
437
473
734
743
348
384
438
483
834
843
356
365
536
563
635
653
357
375
537
573
735
753
358
385
538
583
835
853
367
376
637
673
736
763
368
386
638
683
836
863
378
387
738
783
837
873
456
465
546
564
645
654
457
475
547
574
745
754
458
485
548
584
845
854
467
476
647
674
746
764
468
486
648
684
846
864
478
487
748
784
847
874
567
576
657
675
756
765
568
586
658
685
856
865
578
587
758
785
857
875
678
687
768
786
867
876