My Code is:
#include <iostream>
#include <utility>
#include <algorithm>
//#include <iomanip>
#include <cstdio>
//using namespace std;
inline int overlap(std::pair<int,int> classes[],int size)
{
std::sort(classes,classes+size);
int count=0,count1=0,count2=0;
int tempi,tempk=1;
for(unsigned int i=0;i<(size-1);++i)
{
tempi = classes[i].second;
for(register unsigned int j=i+1;j<size;++j)
{
if(!(classes[i].first<classes[j].second && classes[i].second>classes[j].first))
{ if(count1 ==1)
{
count2++;
}
if(classes[i].second == tempi)
{
tempk =j;
count1 = 1;
}
////cout<<"\n"<<"Non-Overlapping Class:\t";
////cout<<classes[i].first<<"\t"<<classes[i].second<<"\t"<<classes[j].first<<"\t"<<classes[j].second<<"\n";
classes[i].second = classes[j].second;
count++;
if(count1==1 && j ==(size-1))
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
else
{
if(j ==(size-1))
{
if(count>0)
{
j= tempk;
classes[i].second = tempi;
count1= 0;
if(count2 !=0)
{
count = (count + ((count2)-1));
}
count2 =0;
}
}
}
}
}
count = count + size;
return count;
}
inline int fastRead_int(int &x) {
register int c = getchar_unlocked();
x = 0;
int neg = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar_unlocked());
if(c=='-') {
neg = 1;
c = getchar_unlocked();
}
for(; c>47 && c<58 ; c = getchar_unlocked()) {
x = (x<<1) + (x<<3) + c - 48;
}
if(neg)
x = -x;
return x;
}
int main()
{
int N;
////cout<<"Please Enter Number Of Classes:";
clock_t begin,end;
float time_interval;
begin = clock();
while(fastRead_int(N))
{
switch(N)
{
case -1 : end = clock();
time_interval = float(end - begin)/CLOCKS_PER_SEC;
printf("Execution Time = %f",time_interval);
return 0;
default :
unsigned int subsets;
unsigned int No = N;
std::pair<int,int> classes[N];
while(No--)
{
////cout<<"Please Enter Class"<<(i+1)<<"Start Time and End Time:";
int S, E;
fastRead_int(S);
fastRead_int(E);
classes[N-(No+1)] = std::make_pair(S,E);
}
subsets = overlap(classes,N);
////cout<<"\n"<<"Total Number Of Non-Overlapping Classes is:";
printf("%08d",subsets);
printf("\n");
break;
}
}
}
and Input and output of my program:
Input:
5
1 3
3 5
5 7
2 4
4 6
3
500000000 1000000000
1 5
1 5
1
999999999 1000000000
-1
Output:
Success time: 0 memory: 3148 signal:0
00000012
00000005
00000001
Execution Time = 0.000036
I tried to calculate by having clocks at start of main and end of main and found out the time.But it said only some 0.000036 secs.But when I tried to post the same code in Online Judge(SPOJ).My program got 'Time Limit Exceeded' Error. Time Limit for the above program in SPOJ is 2.365 secs.Could somebody help me figure out this?
I consider that your question is about the overlap function.
In it, you have
A sort call: O(n×ln(n))
two for loops:
the first is roughly 0..Size
the second (nested in the first) is roughly i..Size
The inside of the second loop is called Size(Size+1) / 2 (reverse sum of the N first integer) times with no breaks.
So your algorithm is O(n²) where n is the size.
Related
I have the following problem : I have a hex number (datatype : std::uint64_t) in C++, and the hex number contains all the digits from 1 to a given n. The question is now to rotate the first k digits of the hex number, for example :
hex = 0x436512, k = 3 --> 0x634512
I have already tried splitting the hex number into two parts, e.g
std::uint64_t left = hex >> ((n - k) * 4);
std::uint64_t right = ((1UL << ((n - k) * 4)) - 1) & hex;
and then rotating left and merging left and right together. Is there a possibility to do this in-place and by only using bit-manipulation and/or mathematical operators?
As a baseline you can use this which is basically converting to digits and back.
#include <cstdio>
#include <cstdint>
#include <array>
uint64_t rotate( uint64_t value, int k ) {
// decompose
std::array<uint8_t,16> digits;
int numdigits = 0;
while ( value > 0 ) {
digits[numdigits] = value % 16;
value = value / 16;
numdigits += 1;
}
if ( k>numdigits ) return 0;
// revert digits
int p1 = numdigits - 1;
int p2 = numdigits - k;
for ( ; p1>p2; p1--,p2++ ) {
uint8_t tmp = digits[p1];
digits[p1] = digits[p2];
digits[p2] = tmp;
}
// reconstruct
for ( int j=0; j<numdigits; ++j ) {
value = (value*16) + digits[numdigits-1-j];
}
return value;
}
int main() {
uint64_t value = 0x123ffffff;
for ( int j=0; j<8; ++j ) {
value = value >> 4;
printf( "%lx %lx\n", value, rotate(value,3) );
}
}
Godbolt: https://godbolt.org/z/77qWEo9vE
It produces:
Program stdout
123fffff 321fffff
123ffff 321ffff
123fff 321fff
123ff 321ff
123f 321f
123 321
12 0
1 0
You actually do not need to decompose the entire number, you can strictly decompose only the left digits.
#include <cstdio>
#include <cstdint>
#include <array>
uint64_t rotate( uint64_t value, int k ) {
// sanity check
if ( value == 0 ) return 0;
// fast find number of digits
int numdigits = (63-__builtin_clzl(value))/4 + 1;
if ( k>numdigits ) return 0;
// Decompose left and right
int rightbits = 4*(numdigits-k);
uint64_t left = value >> rightbits;
uint64_t right = rightbits==0 ? 0 : value & (uint64_t(-1)>>(64-rightbits));
// decompose left
uint64_t rot = 0;
for ( int j=0; j<k; ++j ) {
uint64_t digit = left % 16;
left = left / 16;
rot = (rot*16) + digit;
}
// rejoin
return right | (rot<<rightbits);
}
int main() {
uint64_t value = 0x123ffffff;
for ( int j=0; j<8; ++j ) {
value = value >> 4;
printf( "%lx %lx\n", value, rotate(value,3) );
}
}
Produces the same output.
Godbolt: https://godbolt.org/z/P3z6W8b3M
Running under Google benchmark:
#include <benchmark/benchmark.h>
#include <vector>
#include <iostream>
uint64_t rotate1(uint64_t value, int k);
uint64_t rotate2(uint64_t value, int k);
struct RotateTrivial {
uint64_t operator()(uint64_t value, int k) {
return rotate1(value, k);
}
};
struct RotateLeftOnly {
uint64_t operator()(uint64_t value, int k) {
return rotate2(value, k);
}
};
template <typename Fn>
static void Benchmark(benchmark::State& state) {
Fn fn;
for (auto _ : state) {
uint64_t value = uint64_t(-1);
for (int j = 0; j < 16; ++j) {
for (int k = 1; k < j; ++k) {
uint64_t result = fn(value, k);
benchmark::DoNotOptimize(result);
}
value = value >> 4;
}
}
}
BENCHMARK(Benchmark<RotateTrivial>);
BENCHMARK(Benchmark<RotateLeftOnly>);
BENCHMARK_MAIN();
Produces on an AMD Threadripper 3960x 3.5GHz
--------------------------------------------------------------------
Benchmark Time CPU Iterations
--------------------------------------------------------------------
Benchmark<RotateTrivial> 619 ns 619 ns 1158174
Benchmark<RotateLeftOnly> 320 ns 320 ns 2222098
Each iteration has 105 calls so it's about 6.3 ns/call or 20 cycles for the trivial version and 3.1ns/call or 10 cycles for the optimized version.
I want to find the number of numbers between 1 and n that are valid numbers in base two (binary).
1 ≤ n ≤ 10^9
For example, suppose n is equal to 101.
Input: n = 101
In this case, the answer is 5
Output: 1, 10, 11, 100, 101 -> 5
Another example
Input: n = 13
Output: 1, 10, 11 -> 3
Here is my code...
#include <iostream>
using namespace std;
int main()
{
int n, c = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
int temp = i;
bool flag = true;
while(temp != 0) {
int rem = temp % 10;
if (rem > 1)
{
flag = false;
break;
}
temp /= 10;
}
if (flag)
{
c++;
}
}
cout << c;
return 0;
}
But I want more speed.
(With only one loop or maybe without any loop)
Thanks in advance!
The highest binary number that will fit in a d-digit number d1 d2 ... dn is
b1 b2 ... bn where
bi = 0 if di = 0, and
bi = 1 otherwise.
A trivial implementation using std::to_string:
int max_binary(int input) {
int res = 0;
auto x = std::to_string(input);
for (char di : x) {
int bi = x == '0' ? 0 : 1;
res = 2 * res + bi;
}
return res;
}
Details:
In each step, if the digit was one, then we add 2 to the power of the number of digits we have.
If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0).
#include <iostream>
using namespace std;
int main()
{
long long int n, res = 0, power = 1;
cin >> n;
while(n != 0) {
int rem = n % 10;
if (rem == 1) {
res += power;
} else if (rem > 1) {
res = 2 * power - 1;
}
n /= 10;
power *= 2;
}
cout << res;
return 0;
}
For a N number (a..N) I am finding set of all combinations in the following way:
void create_print_combinations(int *t, int x, int n) {
if(x == 0) {
char p [2 * r + 2];
memset (p, 0, 2 * r +2);
for (int j=c;j>0;j--)
if(j == c)
sprintf(p, "%d", t[j]);
else
sprintf(p, "%s,%d", p,t[j]);
print_combi(p);
} else {
for (int i= n; i < r; i++) {
t[x] = a[i];
create_print_combinations(t, x-1, i+1);
}
}
}
So a call to function like:
int main() {
unsigned long int start=0, end=0;
printf ("\nEnter the a positive integer N:");
scanf("%d", &r);
start=time(NULL);
a = new int[r];
for (int i = 0;i<r;i++)
a[i]=i+1;
for(int j=1;j<=r;j++) {
a1 = new int[j];
c=j;
create_print_combinations(a1, c, 0);
delete[] a1;
}
end=time(NULL);
printf("Total time taken = %llu\n" , end - start);
return 0;
}
Gives me combinations like for N=4:
Enter the a positive integer N:4
Combo : [1]
Combo : [2]
Combo : [3]
Combo : [4]
Combo : [1,2]
Combo : [1,3]
Combo : [1,4]
Combo : [2,3]
Combo : [2,4]
Combo : [3,4]
Combo : [1,2,3]
Combo : [1,2,4]
Combo : [1,3,4]
Combo : [2,3,4]
Combo : [1,2,3,4]
Now my tasks is to fond the absolute values of all combinations like:
For Combo [1,2,3,4] it should be:
1+2+3+4 = abs(1+2+3+4)
1+2+3-4 = abs(1+2+3-4)
1+2-3-4 = ..
1-2-3+4 = ...
Ans so on
I am trying the below logic:
while(pos > 0)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else if(a == pos)
sprintf(p,"%s%c%d",p, minus, t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
print(p);
memset (p , 0, 2 * r +2);
pos --;
}
But I beleiev I am doing something wrong as all sets are not getting printed. I am unable to frame the logic though I feel I am near to completion. Below is my whole program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int *a;
int *a1;
int r;
int c;
unsigned long int no =1;
int stoi(char *var)
{
int n1 = 0;
int n2 = 0;
int n3 = 0;
char sign=0;
while(*var)
{
if(isspace(*var))
{
var++;
continue;
}
while(*var >= '0' && *var <= '9')
{
n1=(n1*10) + (*var - '0');
var++;
continue;
}
if(sign == '+')
{
n2=n2+n1;
n1=0;
}
else if(sign == '-')
{
n2=n2 - n1;
n1=0;
}
if(*var == '+' || *var == '-')
{
if(sign == 0)
{
n2=n1;
n1=0;
}
sign = *var;
}
var++;
}
if(sign == 0)
return abs(n1);
return abs(n2);
}
void print(char* var)
{
printf("[Combo %llu.] %s = %d\n" , no++, var, stoi(var));
}
void print_combi(char * a)
{
int t[c];
char *x = NULL;
char *y = a;
int i=0;
while((x=strchr(y, ',')) != NULL)
{
*x = '\0';
t[i++]=atoi(y);
y=x+1;
}
t[i++]=atoi(y);
int count =0;
int loop = 0;
char p [2 * r + 2];
memset (p , 0, 2 * r +2);
char plus = '+';
char minus = '-';
for(int k=0;k<2;k++)
{
if(k==1)
{
plus = '-';
minus = '+';
}
if(i>1)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
}
else if(i==1)
{
sprintf(p,"%d", t[i-1]);
print(p);
break;
}
print(p);
memset (p , 0, 2 * r +2);
if(i==2)
continue;
if(i==3 && k ==1)
break;
int pos = i-1;
while(pos > 0)
{
for(int a=0; a < i; a++)
{
if(a==0)
sprintf(p,"%d", t[a]);
else if(a == pos)
sprintf(p,"%s%c%d",p, minus, t[a]);
else
sprintf(p,"%s%c%d",p, plus, t[a]);
}
print(p);
memset (p , 0, 2 * r +2);
pos --;
}
}
}
void create_print_combinations(int *t, int x, int n)
{
if(x == 0)
{
char p [2 * r + 2];
memset (p, 0, 2 * r +2);
for (int j=c;j>0;j--)
if(j == c)
sprintf(p, "%d", t[j]);
else
sprintf(p, "%s,%d", p,t[j]);
print_combi(p);
}
else
for (int i= n; i < r; i++)
{
t[x] = a[i];
create_print_combinations(t, x-1, i+1);
}
}
int main()
{
unsigned long int start=0, end=0;
printf ("\nEnter the a positive integer N:");
scanf("%d", &r);
start=time(NULL);
a = new int[r];
for (int i = 0;i<r;i++)
a[i]=i+1;
for(int j=1;j<=r;j++)
{
a1 = new int[j];
c=j;
create_print_combinations(a1, c, 0);
delete[] a1;
}
end=time(NULL);
printf("Total time taken = %llu\n" , end - start);
return 0;
}
As per the program logic I am computing the combinations as strings and the generating the absolute values of the expression.
There is a simpler way to what you are doing. You want to add up a vector of N integers:
[ 1*k1, 2*k2, 3*k3 ... N*kN ]
where kx = -1, 0, +1.
There are 3^N combinations of kx for x=1..N.
Some code for #SteveC's solution:
#include <iostream>
#include <sstream>
using namespace std;
void print_sum(int N, int sum_so_far, string as_a_string) {
if(N) {
ostringstream oss; oss << N;
print_sum(N-1, sum_so_far+N, as_a_string + "+" + oss.str() + " ");
print_sum(N-1, sum_so_far-N, as_a_string + "-" + oss.str() + " ");
print_sum(N-1, sum_so_far, as_a_string);
} else {
if (sum_so_far < 0) sum_so_far *= -1;
cout << as_a_string << "\t= " << sum_so_far << endl; }
}
int main() {
print_sum(4, 0, "");
}
The output begins:
+4 +3 +2 +1 = 10
+4 +3 +2 -1 = 8
+4 +3 +2 = 9
+4 +3 -2 +1 = 6
+4 +3 -2 -1 = 4
+4 +3 -2 = 5
+4 +3 +1 = 8
+4 +3 -1 = 6
# .. and so on
What you are trying to do is very similar to enumerating all combinations from "N choose 1" to "N choose N". I would suggest you search in google under the terms "Enumerate Combinations"
Here is one of the link I have found:
http://www.codeproject.com/KB/recipes/CombC.aspx
Here is a logic on how to do it. Print all the binary digits of size n-1 where n is the size (number of elements) of the respective combo. For example to do what you want to do for the combo [1,2,3,4] create all the binary combinations of 3 (n-1 = 3, here n = 4 elements). i.e.
when n = 3, the possible combinations are:
000
001
010
011
100
101
110
111
Now run your combo in a for loop and inside it whenever you find a 0 do addition and whenever you find 1 do a subtraction. For example 000 would mean 1+2+3+4 and 101 would mean 1-2+3-4.
I'm working on Project Euler #27 in C++:
Euler published the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the
consecutive values n = 0 to 39. However, when n = 40, 40² + 40 + 41 =
40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² +
41 + 41 is clearly divisible by 41.
Using computers, the incredible formula n² − 79n + 1601 was
discovered, which produces 80 primes for the consecutive values n = 0
to 79. The product of the coefficients, −79 and 1601, is −126479.
Considering quadratics of the form:
n² + an + b, where |a| < 1000 and |b| < 1000
where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic
expression that produces the maximum number of primes for consecutive
values of n, starting with n = 0.
I keep getting -60939 when the real answer is -59231. What am I missing?
#include <iostream>
#include "Helper.h"
using namespace std;
int formula(int a, int b, int n) {
return ((n * n) + (a * n) + b);
}
int main() {
int most = 0;
int ansA = 0;
int ansB = 0;
bool end = false;
for(int a = 999; a >= -999; a--) {
for(int b = 999; b >= 2; b--) { //b must be prime
if(Helper::isPrime(b)) {
end = false;
for(int n = 0; !end; n++) {
if(!Helper::isPrime(formula(a, b, n))) {
if(n-1 > most) {
most = n-1;
ansA = a;
ansB = b;
}
end = true;
}
}
}
}
}
cout << ansA << " * " << ansB << " = " << ansA * ansB << " with " << most << " primes." << endl;
return 0;
}
In case it's the problem, here is my isPrime function:
bool Helper::isPrime(int num) {
if(num == 2)
return true;
if(num % 2 == 0 || num == 1 || num == 0)
return false;
int root = (int) sqrt((double)num) + 1;
for(int i = root; i >= 2; i--) {
if (num % i == 0)
return false;
}
return true;
}
You are allowing a to be negative, and your formula returns an int. Does calling Helper::isPrime with a negative number even make sense (in other words, does Helper::isPrime take an unsigned int?)
Here is my java version. Hope it helps:
static int function(int n, int a, int b){
return n*n + a*n + b;
}
static int consequitive_Primes(int a, int b, HashSet<Integer> primes){
int n = 0;
int number = 0;
while(true){
if(!primes.contains(function(n, a, b)))
break;
number++;
n++;
}
return number;
}
static HashSet<Integer> primes (int n){
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(3);
for(int i=3; i<n;i+=2){
boolean isPrime = true;
for(Integer k:primes){
if(i%k==0){
isPrime = false;
break;
}
}
if(isPrime) primes.add(i);
}
return new HashSet<Integer>(primes);
}
static long q27(){
HashSet<Integer> primes = primes(1000);
int max = 0;
int max_ab = 0;
for(int a = -999; a<1000;a++){
for(int b = -999; b<1000;b++){
int prime_No = consequitive_Primes(a,b,primes);
if(max<prime_No){
max = prime_No;
max_ab = a*b;
}
}
}
return max_ab;
}
Suppose I am given:
A range of integers iRange (i.e. from 1 up to iRange) and
A desired number of combinations
I want to find the number of all possible combinations and print out all these combinations.
For example:
Given: iRange = 5 and n = 3
Then the number of combinations is iRange! / ((iRange!-n!)*n!) = 5! / (5-3)! * 3! = 10 combinations, and the output is:
123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345
Another example:
Given: iRange = 4 and n = 2
Then the number of combinations is iRange! / ((iRange!-n!)*n!) = 4! / (4-2)! * 2! = 6 combinations, and the output is:
12 - 13 - 14 - 23 - 24 - 34
My attempt so far is:
#include <iostream>
using namespace std;
int iRange= 0;
int iN=0;
int fact(int n)
{
if ( n<1)
return 1;
else
return fact(n-1)*n;
}
void print_combinations(int n, int iMxM)
{
int iBigSetFact=fact(iMxM);
int iDiffFact=fact(iMxM-n);
int iSmallSetFact=fact(n);
int iNoTotComb = (iBigSetFact/(iDiffFact*iSmallSetFact));
cout<<"The number of possible combinations is: "<<iNoTotComb<<endl;
cout<<" and these combinations are the following: "<<endl;
int i, j, k;
for (i = 0; i < iMxM - 1; i++)
{
for (j = i + 1; j < iMxM ; j++)
{
//for (k = j + 1; k < iMxM; k++)
cout<<i+1<<j+1<<endl;
}
}
}
int main()
{
cout<<"Please give the range (max) within which the combinations are to be found: "<<endl;
cin>>iRange;
cout<<"Please give the desired number of combinations: "<<endl;
cin>>iN;
print_combinations(iN,iRange);
return 0;
}
My problem:
The part of my code related to the printing of the combinations works only for n = 2, iRange = 4 and I can't make it work in general, i.e., for any n and iRange.
Your solution will only ever work for n=2. Think about using an array (combs) with n ints, then the loop will tick up the last item in the array. When that item reaches max update then comb[n-2] item and set the last item to the previous value +1.
Basically working like a clock but you need logic to find what to uptick and what the next minimum value is.
Looks like a good problem for recursion.
Define a function f(prefix, iMin, iMax, n), that prints all combinations of n digits in the range [iMin, iMax] and returns the total number of combinations. For n = 1, it should print every digit from iMin to iMax and return iMax - iMin + 1.
For your iRange = 5 and n = 3 case, you call f("", 1, 5, 3). The output should be 123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345.
Notice that the first group of outputs are simply 1 prefixed onto the outputs of f("", 2, 5, 2), i.e. f("1", 2, 5, 2), followed by f("2", 3, 5, 2) and f("3", 4, 5, 2). See how you would do that with a loop. Between this, the case for n = 1 above, and traps for bad inputs (best if they print nothing and return 0, it should simplify your loop), you should be able to write f().
I'm stopping short because this looks like a homework assignment. Is this enough to get you started?
EDIT: Just for giggles, I wrote a Python version. Python has an easier time throwing around sets and lists of things and staying legible.
#!/usr/bin/env python
def Combos(items, n):
if n <= 0 or len(items) == 0:
return []
if n == 1:
return [[x] for x in items]
result = []
for k in range(len(items) - n + 1):
for s in Combos(items[k+1:], n - 1):
result.append([items[k]] + s)
return result
comb = Combos([str(x) for x in range(1, 6)], 3)
print len(comb), " - ".join(["".join(c) for c in comb])
Note that Combos() doesn't care about the types of the items in the items list.
Here is your code edited :D :D with a recursive solution:
#include <iostream>
int iRange=0;
int iN=0; //Number of items taken from iRange, for which u want to print out the combinations
int iTotalCombs=0;
int* pTheRange;
int* pTempRange;
int find_factorial(int n)
{
if ( n<1)
return 1;
else
return find_factorial(n-1)*n;
}
//--->Here is another solution:
void print_out_combinations(int *P, int K, int n_i)
{
if (K == 0)
{
for (int j =iN;j>0;j--)
std::cout<<P[j]<<" ";
std::cout<<std::endl;
}
else
for (int i = n_i; i < iRange; i++)
{
P[K] = pTheRange[i];
print_out_combinations(P, K-1, i+1);
}
}
//Here ends the solution...
int main()
{
std::cout<<"Give the set of items -iRange- = ";
std::cin>>iRange;
std::cout<<"Give the items # -iN- of iRange for which the combinations will be created = ";
std::cin>>iN;
pTheRange = new int[iRange];
for (int i = 0;i<iRange;i++)
{
pTheRange[i]=i+1;
}
pTempRange = new int[iN];
iTotalCombs = (find_factorial(iRange)/(find_factorial(iRange-iN)*find_factorial(iN)));
std::cout<<"The number of possible combinations is: "<<iTotalCombs<<std::endl;
std::cout<<"i.e.the combinations of "<<iN<<" elements drawn from a set of size "<<iRange<<" are: "<<std::endl;
print_out_combinations(pTempRange, iN, 0);
return 0;
}
Here's an example of a plain recursive solution. I believe there exists a more optimal implementation if you replace recursion with cycles. It could be your homework :)
#include <stdio.h>
const int iRange = 9;
const int n = 4;
// A more efficient way to calculate binomial coefficient, in my opinion
int Cnm(int n, int m)
{
int i;
int result = 1;
for (i = m + 1; i <= n; ++i)
result *= i;
for (i = n - m; i > 1; --i)
result /= i;
return result;
}
print_digits(int *digits)
{
int i;
for (i = 0; i < n; ++i) {
printf("%d", digits[i]);
}
printf("\n");
}
void plus_one(int *digits, int index)
{
int i;
// Increment current digit
++digits[index];
// If it is the leftmost digit, run to the right, setup all the others
if (index == 0) {
for (i = 1; i < n; ++i)
digits[i] = digits[i-1] + 1;
}
// step back by one digit recursively
else if (digits[index] > iRange) {
plus_one(digits, index - 1);
}
// otherwise run to the right, setting up other digits, and break the recursion once a digit exceeds iRange
else {
for (i = index + 1; i < n; ++i) {
digits[i] = digits[i-1] + 1;
if (digits[i] > iRange) {
plus_one(digits, i - 1);
break;
}
}
}
}
int main()
{
int i;
int digits[n];
for (i = 0; i < n; ++i) {
digits[i] = i + 1;
}
printf("%d\n\n", Cnm(iRange, n));
// *** This loop has been updated ***
while (digits[0] <= iRange - n + 1) {
print_digits(digits);
plus_one(digits, n - 1);
}
return 0;
}
This is my C++ function with different interface (based on sts::set) but performing the same task:
typedef std::set<int> NumbersSet;
typedef std::set<NumbersSet> CombinationsSet;
CombinationsSet MakeCombinations(const NumbersSet& numbers, int count)
{
CombinationsSet result;
if (!count) throw std::exception();
if (count == numbers.size())
{
result.insert(NumbersSet(numbers.begin(), numbers.end()));
return result;
}
// combinations with 1 element
if (!(count - 1) || (numbers.size() <= 1))
{
for (auto number = numbers.begin(); number != numbers.end(); ++number)
{
NumbersSet single_combination;
single_combination.insert(*number);
result.insert(single_combination);
}
return result;
}
// Combinations with (count - 1) without current number
int first_num = *numbers.begin();
NumbersSet truncated_numbers = numbers;
truncated_numbers.erase(first_num);
CombinationsSet subcombinations = MakeCombinations(truncated_numbers, count - 1);
for (auto subcombination = subcombinations.begin(); subcombination != subcombinations.end(); ++subcombination)
{
NumbersSet cmb = *subcombination;
// Add current number
cmb.insert(first_num);
result.insert(cmb);
}
// Combinations with (count) without current number
subcombinations = MakeCombinations(truncated_numbers, count);
result.insert(subcombinations.begin(), subcombinations.end());
return result;
}
I created a next_combination() function similar to next_permutation(), but valid input is required to make it work
//nums should always be in ascending order
vector <int> next_combination(vector<int>nums, int max){
int size = nums.size();
if(nums[size-1]+1<=max){
nums[size-1]++;
return nums;
}else{
if(nums[0] == max - (size -1)){
nums[0] = -1;
return nums;
}
int pos;
int negate = -1;
for(int i = size-2; i>=0; i--){
if(nums[i]+1 <= max + negate){
pos = i;
break;
}
negate --;
}
nums[pos]++;
pos++;
while(pos<size){
nums[pos] = nums[pos-1]+1;
pos++;
}
}
return nums;
}