finding rank of the elements(vectors) in reverse way

problem : "To rank in every possible elements of the set {1,2, ..., n} so that the numbers i, i + 1, ..., i + k to be one after the other and in this order(i=1,i+k≤n)."

my question is how do i find k numbers and in that order i tried backtracking method but unfortunately it doesn't want to output numbers, probably must be like (k+1)k!=(k+1)!..(k+2)k!=(k+2)! and so on i guess
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
 #include <iostream>

using namespace std;


int n,v[20];
int valid(int k);
int solution(int k);
void output(int k);
void BK(int k);
int main()
{cout<<"n= ";
cin>>n;
BK(1);
return 0;
}
void BK(int k) //method backtracking
{int i;
for (i=1;i+k<=n;i++)
 {v[k]=i;
 if (valid(k))
 {if (solution(k))
 output(k);
 else
 BK(k+1);
 }
}
}
int valid(int k) //check if a number is still in set of elements(vector)
{int i;
for (i=1;i<=k-1;i++)
 if (v[i]==v[k])
 return 0;
return 1;
}
int solution(int k) //finding solution
{if (k==n)
 return 1;
return 0;
}
void output(int k) //output result
{int i;
for (i=1;i<=k;i++)
 cout<<v[i]<<" ";
cout<<endl;
}
Topic archived. No new replies allowed.