C program that uses functions to verify security codes - c

I'm trying to write a program that uses the Luhn algorithm to verify security codes. The program needs to:
read security codes from a file and enter them into an array
use one function to read the security codes
use another function to verify them
to verify them, the digits in the odd position will be summed together. The digits in the even positions will be multiplied by two; once they're multiplied by two, if the number is less than ten, it is added to a sum of the evens; if it's more than ten, the sum of the digits of the number are added to the sum of the evens. So, if the number in the second position in the array is 8, it's multiplied by 2 to get 16, then 1 + 6 = 7 is added to the sum of the evens. There's more to verifying the codes, but this is the part I'm working on right now.
The problems I have: I don't think my function for scanning the codes from the file is correct. Each of the codes in the file has 20 digits so when I was declaring the array variable I did: int sc[20]. However, there's more than one 20 digit security code, and I'm not sure how to fix that.
And second: I'm not sure how to approach the second part of summing the evens (the part where if the number multiplied by two is greater than ten, it's digits are added to the sum of the evens).
This is the first few lines from the file (the entire file is very long so I'm just listing the first few lines):
0 7 6 1 1 6 6 2 6 8 5 1 5 5 7 7 7 8 0 2
2 5 1 6 2 1 8 2 4 3 0 9 1 9 1 1 3 1 3 8
1 3 3 4 5 4 5 2 8 6 1 8 9 3 7 6 2 2 0 5
And this is my code so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
ReadSecurityCode(FILE* codes, int sc[]);
int main(void) {
int sc[20], i;
FILE* codes;
codes = fopen("SecurityCodes.txt", "r");
while (fscanf(codes, "%c\n", &sc) != EOF) {
ReadSecurityCode(codes, sc[20]);
}
fclose(codes);
return(0);
}
int ReadSecurityCode(FILE* codes, int sc[]) {
int i;
for (i = 0; i < 20; i++) {
fscanf(codes, "%d", &sc[i]);
}
return(sc[20]);
}
int isCodeValid(int sc[]) {
int i, sumodds = 0, sumevens = 0, sumtotal;
for (i = 1; i < 20; i = i + 2) {
sumodds = sumodds + sc[i];
}
for (i = 0; i < 20; i = i + 2) {
sc[i] = sc[i] * 2;
if (sc[i] < 10) {
sumevens = sumevens + sc[i];
}
else {
}
}
return(sumtotal);
}

The easiest option is to read and validate each line as you go. In the code you posted, this means calling isCodeValid() in while loop where you read the records:
while (fscanf(codes, "%c\n", &sc) != EOF) {
ReadSecurityCode(codes, sc);
isCodeValid(sc);
}
Consider using a char instead of int to store each digit (i.e. char sc[20]).
Not sure why ReadSecurityCode returns the first element, but scanf() can fail, so you might want to return an error code instead and check it. Also, I suggest that you use ReadSecurityCode() to read a line including the newline.
You probably also want to do something based the return value of isCodeValid(). The is-naming suggest you are returning a boolean but you are returning a sum.
With the above suggestions it would be:
while (!ReadSecurityCode(codes, sc)) {
if (!isCodeValid(sc)) {
printf("%s is invalid\n", sc);
}
}

Related

How to print a pattern using nested for loops?

How do I make my code have an output like this:
Enter your number: 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
I can't seem to figure out how to make it so the last digit prints the next value iteration.
#include <stdio.h>
int main(){
int num;
int i = 1;
printf("Enter your number: ");
scanf("%d", &num);
for(i = 1; i<=num; i++){
for(int j = 0; j<num; ++j)
{
printf("%d ",i);
}
printf("\n");
}
Doing this using nested loops are simple and doesn't require any kind of special calculations, if-statements or other more or less fancy stuff. Just keep it simple.
Your task is:
for each row:
print "rowindex+1 and a space" n-1 times
print "rowindex+2 and a newline" 1 time
"for each row" is one simple loop.
"n-1 times" is another (nested) simple loop.
So keep it simple... just two ordinary for-loops like:
#include <stdio.h>
int main()
{
int n = 4;
for (int i = 0; i < n; i++) // for each row
{
for (int j = 0; j < n-1; j++) // n-1 times
{
printf("%d ", i + 1);
}
printf("%d\n", i + 2); // 1 time
}
return 0;
}
Here is something kind of from out in the left field, and off topic, leaving behind not only the requirements of the homework, but the C language. However, we will find our way back.
We can solve this problem (sort of) using text processing at the Unix prompt:
We can treat the smallest square
12
23
as an initial seed kernel, which is fed through a little command pipeline to produce a square of the next size (up to a single digit limitation):
We define this function:
next()
{
sed -e 's/\(.\).$/\1&/' | awk '1; END { print $0 | "tr \"[1-9]\" \"[2-8]\"" }'
}
Then:
$ next
12
23
[Ctrl-D][Enter]
112
223
334
Now, copy the 3x3 square and paste it into next:
$ next
112
223
334
[Ctrl-D][Enter]
1112
2223
3334
4445
Now, several steps in one go, by piping through multiple instances of next:
$ next | next | next | next | next
12
23
[Ctrl-D][Enter]
1111112
2222223
3333334
4444445
5555556
6666667
7777778
The text processing rule is:
For each line of input, repeat the second-to-last character. E.g ABC becomes ABBC, or 1112 becomes 11112. This is easily done with sed.
Add a new line at the end which is a copy of the last line, with each digit replaced by its successor. E.g. if the last line is 3334, make it 4445. The tr utility helps here
To connect this to the homework problem: a C program could be written which works in a similar way, starting with an array which holds the 1 2 2 3 square, and grows it. The requirement for nested loops would be satisfied because there would be an outer loop iterating on the number of "next" operations, and then an inner loop performing the edits on the array: replicating the next-to-last column, and adding the new row at the bottom.
#include <stdio.h>
#include <stdlib.h>
#define DIM 25
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
if (n <= 2 || n > DIM) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
int array[DIM][DIM] = {
{ 1, 2 },
{ 2, 3 }
};
/* Grow square from size 2 to size n */
for (int s = 2; s < n; s++) {
for (int r = 0; r < s; r++) {
array[r][s] = array[r][s-1];
array[r][s-1] = array[r][s-2];
}
for (int c = 0; c <= s; c++) {
array[s][c] = array[s-1][c] + 1;
}
}
/* Dump it */
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++)
printf("%3d ", array[r][c]);
putchar('\n');
}
return 0;
}
#include<stdio.h>
int main(){
int n;
printf("Enter the number: ");
scanf("%d",&n);
for(int i =1; i<=n; i++){
for(int j=1;j<=n;j++) {
if(j==n)
printf("%d\t",i+1);
else
printf("%d\t",i);
}
printf("\n");
}
return 0;}
Nested loops will drive you crazy, trying figure out their boundaries.
While I usually oppose adding more variables, in this case it seems justified to keep track of things simply.
#include <stdio.h>
int main() {
int n = 4, val = 1, cnt1 = 1, cnt2 = 0;
for( int i = 1; i < n*n+1; i++ ) { // notice the 'square' calculation
printf( "%d ", val );
if( ++cnt1 == n ) // tired of this digit? start the next digit
cnt1 = 0, val++;
if( ++cnt2 == n ) // enough columns output? start the next line
cnt2 = 0, putchar( '\n' );
}
return 0;
}
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
A single example of desired output is hard to go by, especially when the code doesn't help... Anyway, here's the output when 'n' = 5.
1 1 1 1 2
2 2 2 2 3
3 3 3 3 4
4 4 4 4 5
5 5 5 5 6
All of these kinds of assignments are to try to get you to recognize a pattern.
The pattern you are given
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
is very close to
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
which is an easy nested loop. Write a solution to the easier pattern. Once you have that you can then you can fix it.
Hint: Notice that the only thing that changes is the last item of the inner loop.
Edit
This totally breaks the spirit of the assignment, and if you, dear student, ever try to submit something like this your professor will... probably not care, but also know full well that you didn’t do it. If I were your professor you’d lose marks, even if I knew you weren’t cheating and had written something this awesome yourself.
Single loop. Stuff added to pretty print numbers wider than one digit (except the very last). Maths, yo.
#include <stdio.h>
#include <math.h>
void print_off_by_one_square( int n )
{
int width = (int)log10( n ) + 1;
for (int k = 0; k++ < n*n ;)
printf( "%*d%c", width, (k+n)/n, (k%n) ? ' ' : '\n' );
}
int main(void)
{
int n;
printf( "n? " );
fflush( stdout );
if ((scanf( "%d", &n ) != 1) || (n < 0))
fprintf( stderr, "%s\n", "Not cool, man, not cool at all." );
else
print_off_by_one_square( n );
return 0;
}
The way it works is pretty simple, actually, but I’ll leave it as an exercise for the reader to figure out on his or her own.
Here is a different concept. Some of the answers are based on the idea that we first think about
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
and then tweak the logic for the item in the last line.
But we can regard it like this also:
We have a tape which goes like this:
1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
and we are blindly cutting the tape into four-element pieces to form a 4x4 square. Suppose someone deletes the first item from the tape, and then adds 5:
1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5
Now, if we cut that tape blindly by the same process, we will get the required output:
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5
Suppose we have a linear index through the tape, a position p starting at 0.
In the unshifted tape, item p is calculated using p / 4 + 1, right?
In the shifted tape, this is just (p + 1) / 4 + 1. Of course we substitute the square size for 4.
Thus:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("wrong usage\n", stderr);
return EXIT_FAILURE;
}
int n = atoi(argv[1]);
int m = n * n;
if (n <= 0) {
fputs("invalid n\n", stderr);
return EXIT_FAILURE;
}
for (int p = 0; p < m; p++) {
printf("%3d ", (p + 1) / n + 1);
if (p % n == n - 1)
putchar('\n');
}
return 0;
}
$ ./square 2
1 2
2 3
$ ./square 3
1 1 2
2 2 3
3 3 4
$ ./square 4
1 1 1 2
2 2 2 3
3 3 3 4
4 4 4 5

How do I get the sum of a txt file and a binary file both of which have array size of 10?

My code is very likely to be incorrect everywhere since I just go started on learning files.
The array of the text file is {3 2 1 3 4 5 6 1 2 3}
The array of the binary is {1 2 3 4 5 6 7 8 9 10}
#include <stdio.h>
#define ARR_SIZ 10
int main()
{
int arr_in[ARR_SIZ];
int arr_bin[ARR_SIZ];
int i = 0;
FILE * fp_in = fopen("data/in.txt", "r");
FILE * fp_bin = fopen("data/in.bin", "wb");
fread(arr_in, sizeof(int), ARR_SIZ, fp_in);
fread(arr_bin, sizeof(int), ARR_SIZ, fp_bin);
int sum[ARR_SIZ];
for (i=0; i < ARR_SIZ; i++){
fscanf("%d", arr_in);
fscanf("%d", arr_in);
sum[i] = arr_in[i] + arr_bin[i];
} printf("%d", sum[i]);
return 0;
}
fread() reads binary data even when the file is not opened with "b" which just means it doesn't do funny stuff with things like Windows-style line breaks.
If you want to read a text file you will how to do more complex work like reading in the data, look for line breaks, and than use the data before each line break. As that data is still a string you will need to convert it to an integer (e.g. using atoi())
You can use this simple program (without fread()):
#include <stdio.h>
#define SIZE 10
int main(void) {
FILE *text = fopen("in.txt", "r"); // --- declaration
FILE *binr = fopen("in.bin", "r");
int text_number[SIZE], binary_number[SIZE], sum = 0;
// alt: you can change sum to sum[SIZE] = {0} if you want to hold into an array.
// --- reading data and assigning into arrays
for (int i = 0; i < SIZE; i++) {
fscanf(text, "%d", &text_number[i]);
fscanf(binr, "%d", &binary_number[i]);
}
// --- summation
for (int i = 0; i < SIZE; i++) {
sum += text_number[i] + binary_number[i]; // alt: do sum[i] when you do sum[SIZE]
printf("%d ", sum); // alt: do sum[i]
sum = 0; // should be omitted when you change into sum[SIZE]
}
printf("\n");
return 0;
}
in.bin contains: 1 2 3 4 5 6 7 8 9 10
Similarly, in.txt contains: 3 2 1 3 4 5 6 1 2 3
And the result is: 4 4 4 7 9 11 13 9 11 13 (sum of both files' integers taken by array).
Note: If you want to store the sum into array, then use the alt code.
I'm not very much aware of fread(), so I just did what I could at the moment.

function that returns the next number of a repeating sequence

First of all, this is a school assignment, so I can't use the <math.h> library as a handicap.
So as the title suggests, I tried to write a function that gets a sequence of positive numbers for its input, then returns the number of which the sequence would continue. For example, if the sequence is 3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1 then it would return a 3 because that's what the next number would be. The sequence of numbers always ends with -1, however, -1 is not part of the sequence, it merely marks its end.
Here's the function:
#include <stdio.h>
int predict(int seq[]) {
int i, j;
for (i = 0; seq[i] != -1; i++)
;
int seqLength = i;
int rep[i+1];
for (j = 0; j < i + 1; j++)
rep[j] = -1;
i = 0;
j = 1;
while (seq[i] != -1) {
if (rep[0] == seq[i]) {
for (j = 1; seq[i + j] != -1; j++) {
if (rep[j] == seq[i + j]) {
j++;
} else {
rep[i] = seq[i];
j = 1;
break;
}
}
i++;
} else {
rep[i] = seq[i];
i++;
}
}
for (i = 0; rep[i] != -1; i++)
;
int repLength = i;
return seq[seqLength % repLength];
}
int main() {
int seq[20] = {1, 2, 1, 1, 2, 1, 2, 3, 1, 2, 1, 1, 2, 1, 2, -1}; /*or any other positive numbers as long as it ends with -1*/
printf("%d\n",predict(seq));
return 0;
}
The seq (short for sequence) is the sequence of numbers the function gets as the input.
seqLength is the number of how many numbers the seq has.
The rep (short for repeat) is the part of the sequence which repeats itself.
repLength is the number of how many numbers the rep has.
The function works for all three test cases which I know, for example:
For 3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1 it returns 3.
For 1 2 3 1 2 3 4 1 2 3 1 2 3 4 1 2 3 it returns 1.
For 1 2 1 1 2 1 2 3 1 2 1 1 2 1 2 it returns 3.
However, when I upload it to the school system that tests and appraises my function, it tests for an additional two test cases, which are wrong. The problem is, that I don't know the input sequence for those additional two test cases and therefore I don't know what to change in order for my functions to work for all test cases. Can someone see an error in my work and have an idea of what to change in order for my function to work for any repeating number sequences, even for unknown ones?
There is a corner case for which your algorithm does not work: if the repeated sequence has length seqLength, you will not find -1 in the rep array because it was defined with a length of seqLength and the end of list marker was never copied there. Hence the last loop will run past the end of rep and cause undefined behavior.
I'm afraid there are other problems, let's try and simplify the code:
It would be safer to compare the index values to seqLength instead of testing for -1, which by the way you did not document as the end of list marker.
Furthermore, it seems superfluous to copy the sequence into a rep array as this array would always contain an initial portion of seq.
The problems seems to boil down to finding the length of the repeated pattern.
Here is a simplified version, with seqLength passed as an argument:
int predict(int seq[], int seqLength) {
/* find the mininum value of repLength such that the sequence is
a repeated pattern of length repLength */
int i, repLength;
for (repLength = 1; repLength < seqLength; replength++) {
for (i = 0; i < seqLength; i++) {
if (seq[i] != seq[i % repLength])
break;
}
if (i == seqLength) {
/* we found the pattern length */
break;
}
}
return seq[seqLength % repLength];
}

Calculating total number of adjacent integers

I want to calculate the number of integers excluding repeats line by line from the file.
The output I desire is:
Duplicates : 9
Duplicates : 4
Duplicates : 5
Duplicates : 5
Duplicates : 1
Duplicates : 1
Duplicates : 8
For further explanation of the concept:
Take the second line of the file:
1 2 3 4 5 6 5 4 5
At this line there is a 1 so increment the counter because 1 was found first.
Next comes a 2, 2 is not 1 so increment the counter. Next comes a 3, 3 is not a 2 so increment the counter. Next comes a 4, 4 is not a 3 so increment the counter. Next comes a 5, 5 is not a 4 so increment the counter. Next comes a 6, 6 is not a 5 so increment the counter. Next comes a 5, 5 is not a 6 so increment the counter. Next comes a 4, 4 is not a 5 so increment the counter. Next comes a 5, 5 is not a 4 so increment the counter. The number of integers excluding repeats is 9.
Another example:
Take a look a line 8 of the file:
34 34 34 34 34
At this line there is a 34 so increment the counter. Next comes a 34, 34 is 34 so do not increment the counter. Next comes 34, 34 is 34 so do not increment the counter. Next comes a 34, 34 is 34 so do not increment the counter. Next comes a 34, 34 is 34 so do not increment the counter. The number of integers excluding repeats is 1.
EDIT:
I took the suggestion of a user on here and looked at a few link related to adjacent strings and integers. The output is almost completely correct now when compared to the desired output that I listed above. I will only put the pertain code below:
Output:
check1:1
check1:1
check1:2
Duplicates : 6 (Wrong value)
check1:2
Duplicates : 5 (Wrong value)
Duplicates : 5
Duplicates : 5
check1:0
check1:0
check1:0
check1:0
Duplicates : 1
Duplicates : 1
check1:0
check1:0
check1:2
check1:3
check1:3
check1:3
check1:4
check1:5
check1:5
check1:5
check1:5
check1:6
check1:6
Duplicates : 7 (Wrong value)
From the output it appears that whenever a test case goes through the if statement if(array[check] == ch), the output is incorrect.
I have been staring at the loops in this function for a long and I am still stumped.
Any suggestions as to why that loop is leading to incorrect values? Thank you.
Your logic is too complicated, this simple logic should do it
Count the first value
Start a loop from the second value to the last
Subtract the current value from the previous, if the result is 0 then it's the same value, do not add to the counter otherwise add to the counter.
I wrote a program to show you how
numbers.txt
1 2 3 4 5 6 5 4 5
14 62 48 14
1 3 5 7 9
123 456 789 1234 5678
34 34 34 34 34
1
1 2 2 2 2 2 3 3 4 4 4 4 5 5 6 7 7 7 1 1
program.c
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
FILE *file;
char line[100];
file = fopen("numbers.txt", "r");
if (file == NULL)
return -1;
while (fgets(line, sizeof(line), file) != NULL)
{
char *start;
int array[100];
int count;
int value;
int step;
count = 0;
start = line;
while (sscanf(start, "%d%n", array + count, &step) == 1)
{
start += step;
count += 1;
}
fprintf(stderr, "%d ", array[0]);
value = 1;
for (int i = 1 ; i < count ; ++i)
{
value += (array[i] - array[i - 1]) ? 1 : 0;
fprintf(stderr, "%d ", array[i]);
}
fprintf(stderr, " -- %d\n", value);
}
fclose(file);
return 0;
}
You simply need to check the current value to previous value of the array and check if they are equal or not something like this ::
int ans = 1;
for (int i = 1 ; i < n ; i++) { //n is the number of elements in array
if (a[i] != a[i - 1]) {
ans++;
}
}
printf("%d", ans);
I do not exactly understand why you use so many check in your code. What I do in this code is that I check my current element in the array (starting from 1) and compare it with previous element, so if they are not equal you have a unique element in your array (sequentially), and hence I increment the ans which is the number of unique elements sequentially.
Here I start with ans = 1 because I assume that there will be at least 1 element in your array and that will be unique in any case.
I don't know what you are using that much code for.
But for what i understand you want to do, it a simple loop like this:
#include <stdio.h>
int main() {
int array[] = {1,3,5,7,9};
int count = 1;
int i = 0;
for(i=1; i<(sizeof(array)/sizeof(array[0])); i++) { //sizeof(array)/sizeof(array[0]) calculates the length of the array
if(array[i]!=array[i-1]) {
count++;
}
}
printf("%d", count);
}

Segmentation fault due to recursion

I'm writing a program that is to take a number between 1-10 and display all possible ways of arranging the numbers.
Ex
input: 3
output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Whenever I input 9 or 10, the program gives a segmentation fault and dumps the core. I believe the issue is my recursive algorithm is being called too many times. Could someone help point out how I could limit the amount of recursive calls necessary? Here is my current code:
void rearange(int numbers[11], int index, int num, int fact) {
int temp = numbers[index];
numbers[index] = numbers[index-1];
numbers[index-1] = temp;
int i;
for (i = 1; i <= num; ++i) // print the current sequence
{
printf("%d ", numbers[i]);
}
printf("\n");
fact--; // decrement how many sequences remain
index--; // decrement our index in the array
if (index == 1) // if we're at the beginning of the array
index = num; // reset index to end of the array
if (fact > 0) // If we have more sequences remaining
rearange(numbers, index, num, fact); // Do it all again! :D
}
int main() {
int num, i; // our number and a counter
printf("Enter a number less than 10: ");
scanf("%d", &num); // get the number from the user
int numbers[11]; // create an array of appropriate size
// fill array
for (i = 1; i <= num; i++) { // fill the array from 1 to num
numbers[i] = i;
}
int fact = 1; // calculate the factorial to determine
for (i = 1; i <= num; ++i) // how many possible sequences
{
fact = fact * i;
}
rearange(numbers, num, num, fact); // begin rearranging by recursion
return 0;
}
9! (362880) and 10! (3628800) are huge numbers that overflow the call stack when you do as many recursive calls. Because all the local variables and formal parameters have to be stored. You either you have to increase the stack size or convert the recursion into iteration.
On linux, you can do:
ulimit -s unlimited
to set the stack size to unlimited. The default is usually 8MB.
Calculating permutations can be done iteratively, but even if you do it recursively there is no need to have a gigantic stack (like answers suggesting to increase your system stack say). In fact you only need a tiny amount of your stack. Consider this:
0 1 <- this needs **2** stackframes
1 0 and an for-loop of size 2 in each stackframe
0 1 2 <- this needs **3** stackframes
0 2 1 and an for-loop of size 3 in each stackframe
1 0 2
1 2 0
2 1 0
2 0 1
Permuting 9 elements takes 9 stackframes and a for-loop through 9 elements in each stackframe.
EDIT: I have taken the liberty to add a recursion-counter to your rearrange-function, it now prints like this:
Enter a number less than 10: 4
depth 1 1 2 4 3
depth 2 1 4 2 3
depth 3 4 1 2 3
depth 4 4 1 3 2
depth 5 4 3 1 2
depth 6 3 4 1 2
depth 7 3 4 2 1
depth 8 3 2 4 1
depth 9 2 3 4 1
depth 10 2 3 1 4
depth 11 2 1 3 4
depth 12 1 2 3 4
depth 13 1 2 4 3
depth 14 1 4 2 3
depth 15 4 1 2 3
depth 16 4 1 3 2 which is obviously wrong even if you do it recursively.
depth 17 4 3 1 2
depth 18 3 4 1 2
depth 19 3 4 2 1
depth 20 3 2 4 1
depth 21 2 3 4 1
depth 22 2 3 1 4
depth 23 2 1 3 4
depth 24 1 2 3 4
....
The recursion-leafs should be the only ones which output so the depth should be constant and small (equal to the number you enter).
EDIT 2:
Ok, wrote the code. Try it out:
#include "stdio.h"
void betterRecursion(int depth, int elems, int* temp) {
if(depth==elems) {
int j=0;for(;j<elems;++j){
printf("%i ", temp[j]);
}
printf(" (at recursion depth %u)\n", depth);
} else {
int i=0;for(;i<elems;++i){
temp[depth] = i;
betterRecursion(depth+1, elems, temp);
}
}
}
int main() {
int temp[100];
betterRecursion(0, 11, temp); // arrange the 11 elements 0...10
return 0;
}
I'd make your rearange function iterative - do while added, and recursive call removed:
void rearange(int numbers[11], int index, int num, int fact) {
int temp;
do
{
temp = numbers[index];
numbers[index] = numbers[index-1];
numbers[index-1] = temp;
int i;
for (i = 1; i <= num; ++i) // print the current sequence
{
printf("%d ", numbers[i]);
}
printf("\n");
fact--; // decrement how many sequences remain
index--; // decrement our index in the array
if (index == 1) // if we're at the beginning of the array
index = num; // reset index to end of the array
} while (fact > 0);
}
This is not a task for a deep recursion.
Try to invent some more stack-friendly algorithm.
Following code has rather troubles with speed than with stack size...
It's a bit slow e.g. for n=1000 but it works.
#include <stdio.h>
void print_arrangement(int n, int* x)
{
int i;
for(i = 0; i < n; i++)
{
printf("%s%d", i ? " " : "", x[i]);
}
printf("\n");
}
void generate_arrangements(int n, int k, int* x)
{
int i;
int j;
int found;
if (n == k)
{
print_arrangement(n, x);
}
else
{
for(i = 1; i <= n; i++)
{
found = 0;
for(j = 0; j < k; j++)
{
if (x[j] == i)
{
found = 1;
}
}
if (!found)
{
x[k] = i;
generate_arrangements(n, k + 1, x);
}
}
}
}
int main(int argc, char **argv)
{
int x[50];
generate_arrangements(50, 0, x);
}
Your program is using too many recursions unnecessarily. It is using n! recursions when actually n would be enough.
To use only n recursions, consider this logic for the recursive function:
It receives an array nums[] of n unique numbers to arrange
The arrangements can have n different first number in them, as there are n different numbers in the array
(key step) Loop over the elements of nums[], and in each iteration create a new array but with the current element removed, and recurse into the same function passing this shorter array as parameter
As you recurse deeper, the parameter array will be smaller and smaller
When there is only one element left, that's the end of the recursion
Using this algorithm, your recursion will not be deeper than n and you will not get segmentation fault. The key is in the key step, where you build a new array of numbers that is always 1 item shorter than the input array.
As a side note, make sure to check the output of your program before you submit, for example run it through | sort | uniq | wc -l to make sure you are getting the correct number of combinations, and check that there are no duplicates with | sort | uniq -d (the output should be empty if no dups).
Spoiler alert: here's my implementation in C++ using a variation of the above algorithm:
https://gist.github.com/janosgyerik/5063197

Resources