Proper use of recursion in C - c

I'm working on some basic programs for learning purposes. Struggling to find out logic in this kind of recursion fuction. How does the "loop" inside histogram function works? Is it possible to get rid of it and make it only main function? Any info is appreciate.
The task is to create horizontal histogram with given integers.
#include <stdio.h>
#include <string.h>
void histogram(int numbers[], int length, int n) {
int finished = 1;
for(int i = 0; i < length; i++){
if(numbers[i] - n > 0)
finished = 0;}
if(finished)
return;
else {
histogram(numbers, length, n +1);
int counter = 0;
for(int i = 0; i < length; i++) {
int number = numbers[i] -n;
if(number > 0)
printf("* ");
else
printf(" ");
}
printf("\n");
}
}
int main(void) {
int numbers[] = {1, 3, 1};
int length = sizeof(numbers) / sizeof(int);
histogram(numbers, length,0);
return 0;
}

Each iteration of the recursion is drawing a line of and * character, a horizontal slice of the histogram.
For n-th level the values numbers[i] that are larger or equal than n are marked by *, other become whitespaces.
Note that recursion is called before drawing anything. Thus the deepest level is drawn first:
For example:
numbers[] = {1, 2, 3, 1}
Level3: * \n as 1<3, 2<3, 3>=3, 1<3
Level2: ** \n as 1<2, 2>=2, 3>=2, 1<2
Level1:****\n as 1>=1, 2>=1, 3>=1, 1>=1
Level0:****\n as 1>=0, 2>=0, 3>=0, 1>=0
This recursion can rewritten as two nested loops.
Find maximal height. Set it max_number:
Iterate over heights from max_number to 0 inclusive.
For each height iterate over whole array printing * is numbers[i] >= height, otherwise print
Code:
#include <stdio.h>
void histogram(int numbers[], int length) {
int max_number = 0;
for (int i = 0; i < length; ++i)
if (numbers[i] > max_number)
max_number = numbers[i];
for (int height = max_number; height >= 0; --height) {
for (int i = 0; i < length; ++i)
if (numbers[i] >= height)
putchar('*');
else
putchar(' ');
putchar('\n');
}
}
int main() {
int A[] = {1,2,3,1};
histogram(A, 4);
return 0;
}
produces:
*
**
****
****
to make a horizontal histogram ... just switch the loops.
void horiz_histogram(int numbers[], int length) {
int max_number = 0;
for (int i = 0; i < length; ++i)
if (numbers[i] > max_number)
max_number = numbers[i];
for (int i = 0; i < length; ++i) {
for (int height = max_number; height >= 0; --height)
if (numbers[i] >= height)
putchar('*');
else
putchar(' ');
putchar('\n');
}
}
produces:
**
***
****
**

Imagine drawing a table wide as the length of the array of numbers and high as its maximum value:
// Pseudocode
width = length = sizeof(numbers) / sizeof(int) // = 3
height = max(numbers[] = {1, 3, 1}) // = 3
At each step histogram() checks if it has reached the top of the graph.
If so, it prints the top line and returns.
Otherwise it goes up one line and checks again.
This way histogram() prints the top line first and then the others "climbing down"

Related

Sorting integers by sum of their digits

I'm trying to write a program that will sort an array of 20 random numbers by the sums of their digits.
For example:
"5 > 11" because 5 > 1+1 (5 > 2).
I managed to sort the sums but is it possible to return to the original numbers or do it other way?
#include <stdio.h>
void sortujTab(int tab[], int size){
int sum,i;
for(int i=0;i<size;i++)
{
while(tab[i]>0){//sum as added digits of an integer
int p=tab[i]%10;
sum=sum+p;
tab[i]/=10;
}
tab[i]=sum;
sum=0;
}
for(int i=0;i<size;i++)//print of unsorted sums
{
printf("%d,",tab[i]);
}
printf("\n");
for(int i=0;i<size;i++)//sorting sums
for(int j=i+1;j<=size;j++)
{
if(tab[i]>tab[j]){
int temp=tab[j];
tab[j]=tab[i];
tab[i]=temp;
}
}
for(int i=0;i<20;i++)//print of sorted sums
{
printf("%d,",tab[i]);
}
}
int main()
{
int tab[20];
int size=sizeof(tab)/sizeof(*tab);
for(int i=0;i<=20;i++)
{
tab[i]=rand()%1000;// assamble the value
}
for(int i=0;i<20;i++)
{
printf("%d,",tab[i]);//print unsorted
}
printf("\n");
sortujTab(tab,size);
return 0;
}
There are two basic approach :
Create a function that return the sum for an integer, say sum(int a), then call it on comparison, so instead of tab[i] > tab [j] it becomes sum(tab[i]) > sum (tab[j])
Store the sum into a different array, compare with the new array, and on swapping, swap both the original and the new array
The first solution works well enough if the array is small and takes no extra memory, while the second solution didn't need to repeatedly calculate the sum. A caching approach is also possible with map but it's only worth it if there are enough identical numbers in the array.
Since your numbers are non-negative and less than 1000, you can encode the sum of the digits in the numbers itself. So, this formula will be true: encoded_number = original_number + 1000 * sum_of_the_digits. encoded_number/1000 will decode the sum of the digits, and encoded_number%1000 will decode the original number. Follow the modified code below. The numbers enclosed by parentheses in the output are original numbers. I've tried to modify minimally your code.
#include <stdio.h>
#include <stdlib.h>
void sortujTab(int tab[], int size)
{
for (int i = 0; i < size; i++) {
int sum = 0, n = tab[i];
while (n > 0) { //sum as added digits of an integer
int p = n % 10;
sum = sum + p;
n /= 10;
}
tab[i] += sum * 1000;
}
for (int i = 0; i < size; i++) { //print of unsorted sums
printf("%d%c", tab[i] / 1000, i < size - 1 ? ',' : '\n');
}
for (int i = 0; i < size; i++) { //sorting sums
for (int j = i + 1; j < size; j++) {
if (tab[i] / 1000 > tab[j] / 1000) {
int temp = tab[j];
tab[j] = tab[i];
tab[i] = temp;
}
}
}
for (int i = 0; i < size; i++) { //print of sorted sums
printf("%d(%d)%c", tab[i] / 1000, tab[i] % 1000, i < size - 1 ? ',' : '\n');
}
}
int main(void)
{
int tab[20];
int size = sizeof(tab) / sizeof(*tab);
for (int i = 0; i < size; i++) {
tab[i] = rand() % 1000; // assamble the value
}
for (int i = 0; i < size; i++) {
printf("%d%c", tab[i], i < size - 1 ? ',' : '\n'); //print unsorted
}
sortujTab(tab, size);
return 0;
}
If the range of numbers doesn't allow such an encoding, then you can declare a structure with two integer elements (one for the original number and one for the sum of its digits), allocate an array for size elements of this structure, and initialize and sort the array using the digit sums as the keys.
You can sort an array of indexes rather than the array with data.
#include <stdio.h>
//poor man's interpretation of sumofdigits() :-)
int sod(int n) {
switch (n) {
default: return 0;
case 5: return 5;
case 11: return 2;
case 1000: return 1;
case 9: return 9;
}
}
void sortbyindex(int *data, int *ndx, int size) {
//setup default indexes
for (int k = 0; k < size; k++) ndx[k] = k;
//sort the indexes
for (int lo = 0; lo < size; lo++) {
for (int hi = lo + 1; hi < size; hi++) {
if (sod(data[ndx[lo]]) > sod(data[ndx[hi]])) {
//swap indexes
int tmp = ndx[lo];
ndx[lo] = ndx[hi];
ndx[hi] = tmp;
}
}
}
}
int main(void) {
int data[4] = {5, 11, 1000, 9};
int ndx[sizeof data / sizeof *data];
sortbyindex(data, ndx, 4);
for (int k = 0; k < sizeof data / sizeof *data; k++) {
printf("%d\n", data[ndx[k]]);
}
return 0;
}

How can I fill a 2D array spirally in C? Example/problem

so I've been struggling with this example for a good hour now and I can't even begin to process how should I do this.
Write a program that, for given n and m, forms a matrix as described.
The matrix should be m x m, and it's filled "spirally" with it's
beginning in the upper left corner. The first value in the matrix is
the number n. It's repeated until the "edge" of the matrix, at which
point the number increments. After the number 9 goes 0. 0 ≤ n ≤ 9, 0 ≤
m ≤ 9
Some time ago I had made a function to display the numbers 1 to n on an odd-sized grid.
The principle was to start from the center and to shift by ;
x = 1
x box on the right
x box on the bottom
x++
x box on the left
x box at the top
x++
With this simple algorithm, you can easily imagine to maybe start from the center of your problem and decrement your value, it seems easier to start from the center.
Here is the code that illustrates the above solution, to be adapted of course for your problem, it's only a lead.
#define WE 5
void clock(int grid[WE][WE])
{
int count;
int i;
int reach;
int flag;
int tab[2] = {WE / 2, WE / 2}; //x , y
count = 0;
flag = 0;
i = 0;
reach = 1;
grid[tab[1]][tab[0]] = count;
for (int j = 0; j < WE - 1 && grid[0][WE - 1] != pow(WE, 2) - 1; j++)
for (i = 0; i < reach && grid[0][WE - 1] != pow(WE, 2) - 1; i++, reach++)
{
if(flag % 2 == 0)
{
for(int right = 0 ; right < reach ; right++, tab[0]++, count++, flag = 1)
grid[tab[1]][tab[0]] = count;
if(reach < WE - 1)
for(int bottom = 0; bottom < reach; bottom++, count++, tab[1]++)
grid[tab[1]][tab[0]] = count;
}
else
{
for(int left = 0; left < reach; left++, count++, tab[0]--, flag = 0)
grid[tab[1]][tab[0]] = count;
for(int top = 0; top < reach; top++, tab[1]--, count++)
grid[tab[1]][tab[0]] = count;
}
}
}
I finally solved it. If anybody's interested, here's how I did it:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Fills the row number "row" with the number n
int fillRow(int m, int n, int arr[m][m], int row)
{
int j;
for(j=0;j<m;j++)
{
if(arr[row][j] == -1 || arr[row][j] == n-1) arr[row][j] = n;
}
}
//Fills the column number "col" with the number n
int fillCol(int m, int n, int arr[m][m], int col)
{
int i;
for(i=0;i<m;i++)
{
if(arr[i][col] == -1 || arr[i][col] == n-1) arr[i][col] = n;
}
}
int main()
{
int n, m, i, j, r=1, c=1, row=-1, col=-1;
scanf("%d %d",&n, &m);
int arr[m][m];
//Fill array with -1 everywhere
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
arr[i][j] = -1;
}
}
//Calculate which row/column to fill (variables row/col)
//Fill row then column then row than column...
for(i=0;i<2*m;i++)
{
if(i%2==0)
{
row = (r%2==0) ? m-r/2 : r/2;
fillRow(m, n, arr, row);
n++;
r++;
}
else if(i%2==1)
{
col = (c%2==0) ? c/2-1 : m-c/2-1;
fillCol(m, n, arr, col);
n++;
c++;
}
}
//If an element is larger than 9, decrease it by 10
//Prints the elements
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(arr[i][j]>9) arr[i][j] -=10;
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}

how to create a diamond in c using only 3 printf and 3 n\t\

I am attempting to create a diamond in c with the constraints of only 3 printfs and 3 n\t. this requires me to use loops. I know how to make an upside down triangle and a triangle but cant use that because there are too many printfs. i will attach my code so far. I am aware it does not make a diamond, and some awfully strange shape, but that it what i'm trying to work off and edit to make into a diamond, I just haven't been able to figure it out.
if (type_of_shape == 5)
{
for (i = 0; i < width; i++)
{
for (j = 0;j < ((width - 1) / 2) - i ||(width -1)/2 < i && j + (width-1)/2 < i; j++)
{
printf(" ");
}
for (k = 0;k<width && k < (j*2+1) ; k++)
{
printf("*");
}
printf("\n");
}
}
//int width = 5;
int row, col;
int spaces, stars;
int half, rate;
half = width / 2 + 1;
rate = 1;
for(row = 1; 0 < row && row <= half; row += rate) {
spaces = half - row;
stars = row * 2 -1;
printf("%*s", spaces, "");
for (col = 0; col < stars; col++)
printf("*");
printf("\n");
if(row == half)
rate = -rate;
}
I got it down to a single line which has a single loop, with a single printf statement.
It involved some tricky use of abs.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int w = 9;
for(int l=0; l < w; ++l) printf("%*.*s\n", abs(w/2 - l)+abs((2*l+1)-(2*l+1>w)*2*w), abs((2*l+1)-(2*l+1>w)*2*w), "**************");
return 0;
}
2 loops (one for, one while).
2 printf statements.
Note:
This works with odd Widths.
An even width produces a diamond with Width+1
My IDEOne code
int main(void)
{
int width = 9;
int layer;
width+=2;
for(layer=0; layer<width/2; ++layer)
{
printf("%*.*s\n", width/2+layer + 1,layer*2 + 1, "**************************");
}
layer--;
while (layer --> 0)
{
printf("%*.*s\n", width/2+layer + 1,layer*2 + 1, "**************************");
}
return 0;
}
Output
Success time: 0 memory: 2168 signal:0
*
***
*****
*******
*********
*******
*****
***
*
Here's a solution with no loops at all. (looping accomplished via recursion), and 3 printf statements:
#include <stdio.h>
void drawDiamond(int width, int stars)
{
static const char* txt = "*****************************";
if (stars == width) {
printf("%*.*s\n",width, width, txt);
return;
}
printf("%*.*s\n", (width+stars)/2, stars, txt);
drawDiamond(width, stars+2);
printf("%*.*s\n", (width+stars)/2, stars, txt);
}
int main(void)
{
drawDiamond(9, 1);
return 0;
}

Program Bugs with large sequences (C) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to code the Waterman algorithm in C.
Now when the length of the sequence exceeds 35 the program just lags.
I have no idea where to start looking, tried but got nothing worked out.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Max Function Prototype.
int maxfunction(int, int);
// Prototype of the random Sequences generator Function.
void gen_random(char *, const int);
int main(int argc, char *argv[]) {
// Looping variable and Sequences.
int i = 0, j = 0, k = 0;
char *X, *Y;
int length1, length2;
// Time Variables.
time_t beginning_time, end_time;
// Getting lengths of sequences
printf("Please provide the length of the first Sequence\n");
scanf("%d", &length1);
printf("Please provide the length of the second Sequence\n");
scanf("%d", &length2);
X = (char*)malloc(sizeof(char) * length1);
Y = (char*)malloc(sizeof(char) * length2);
int m = length1 + 1;
int n = length2 + 1;
int L[m][n];
int backtracking[m + n];
gen_random(X, length1);
gen_random(Y, length2);
printf("First Sequence\n");
for (i = 0; i < length1; i++) {
printf("%c\n", X[i]);
}
printf("\nSecond Sequence\n");
for (i = 0; i < length2; i++) {
printf("%c\n", Y[i]);
}
// Time calculation beginning.
beginning_time = clock();
// Main Part--Core of the algorithm.
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else
if (X[i-1] == Y[j-1]) {
L[i][j] = L[i-1][j-1] + 1;
backtracking[i] = L[i-1][j-1];
} else {
L[i][j] = maxfunction(L[i-1][j], L[i][j-1]);
backtracking[i] = maxfunction(L[i-1][j], L[i][j-1]);
}
}
}
// End time calculation.
end_time = clock();
for (i = 0; i < m; i++) {
printf(" ( ");
for (j = 0; j < n; j++) {
printf("%d ", L[i][j]);
}
printf(")\n");
}
// Printing out the result of backtracking.
printf("\n");
for (k = 0; k < m; k++) {
printf("%d\n", backtracking[k]);
}
printf("Consumed time: %lf", (double)(end_time - beginning_time));
return 0;
}
// Max Function.
int maxfunction(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Random Sequence Generator Function.
void gen_random(char *s, const int len) {
int i = 0;
static const char alphanum[] = "ACGT";
for (i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Since you null terminate the sequence in gen_random with s[len] = 0;, you should allocate 1 more byte for each sequence:
X = malloc(sizeof(*X) * (length1 + 1));
Y = malloc(sizeof(*Y) * (length2 + 1));
But since you define variable length arrays for other variables, you might as well define these as:
char X[length1 + 1], Y[length2 + 1];
Yet something else is causing a crash on my laptop: your nested loops iterate from i = 0 to i <= m, and j = 0 to j <= n. That's one step too many, you index out of bounds into L.
Here is a corrected version:
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
The resulting code executes very quickly, its complexity is O(m*n) in both time and space, but m and n are reasonably small at 35. It runs in less than 50ms for 1000 x 1000.
Whether it implements Smith-Waterman's algorithm correctly is another question.

N queens on a NxN chessboard

#include <stdio.h>
#include <math.h>
int n=4;
int GetQueenSettings(int board[4][4],int currentRow,int n)
{
//decide when the recursion stops
if(currentRow==n)
return 1; //successful setting
//otherwise we set column by column in this row and continue
int TotalSettingCount=0;
for(int i=0;i<n;i++)
{
//make sure it can be set (it is unset at that moment)
if(board[currentRow][i]==0)
{
board[currentRow][i]==1+currentRow;
//use row related info for settings
//now set invalid positions for remaining rows
setInvalid(board,currentRow,n,i);
//recover after this before trying the next
TotalSettingCount += GetQueenSettings(board,currentRow+1,n);
board[currentRow][i]=0;
RecoverBoard(board,currentRow,n);
}
}
return TotalSettingCount;
}
void setInvalid(int board[4][4],int currentRow,int n,int i)
{
//vertical and diagonal elements
for(int row=currentRow+1;row<n;row++) //start from the next line
{
//firstly make sure board can be set
if(board[row][i]==0)//vertical position
board[row][i]=-(1+currentRow);
//now check diagonal
int rowGap=row-currentRow;
if(i-rowGap>=0 && board[row][i-rowGap]==0)
{
//left bottom diagonal position
board[row][i-rowGap]=-(1+currentRow);
}
if(i+rowGap<n && board[row][i+rowGap]==0)
{
//bottom right diagonal position
board[row][i+rowGap]=-(1+currentRow);
}
}
}
void RecoverBoard(int board[4][4],int currentRow,int n)
{
//recover is to check all remaining rows if index is higher than current row(setters)
//OR less than -currentRow(invalids)!
for(int row=currentRow+1;row<n;row++)
{
for(int col=0;col<n;col++)
{
if(board[row][col]>currentRow || board[row][col]< -currentRow)
board[row][col]=0;
}
}
}
int main()
{
int board[n][n];
printf("Number of settings:-> %d",GetQueenSettings(board,0,n));
return 0;
}
There are N queeens placed on a NxN chessboard without interfering with each other. when i run this code i get the answer as zero instead of 2 . also i cant figure out a way of passing array board to functions with variable size(size will be given by user).What am i doing wrong?!
You should initialize your board. As is, you start with a board full of garbage values. You are using a variable-length array as board. Such arrays cannot be initialized, so you have to set the board to all zero with a loop or with memset from <string.h>:
int board[n][n];
memset(board, 0, sizeof(board));
You can pass variable-length arrays to functions when the dimensions are passed in as earlier arguments, for example:
int GetQueenSettings(int n, int board[n][n], int currentRow) { ... }
Also fix the =/== switch in setInvalid:
if (board[row][i] == 0)
board[row][i] = -(1 + currentRow);
Finally make sure that all functions have proper prototypes when they are called.
A loooooooong time ago I developed an algorithm like the one you have, maybe it can help you.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
long Solutions;
void AllocBoard(int *** Board, int Queens)
{
int i;
*Board = (int **)malloc(sizeof(int *) * Queens);
for(i = 0; i < Queens; i++)
{
(*Board)[i] = (int *)malloc(sizeof(int) * Queens);
memset((*Board)[i], 0, sizeof(int) * Queens);
}
}
void DeallocBoard(int *** Board, int Queens)
{
int i;
for(i = 0; i < Queens; i++)
free((*Board)[i]);
free(*Board);
}
void SavePosition(int *** Board, int Queens, int Col, int Row, int Inc)
{
int i, j;
for(i = 0; i < Queens; i++)
{
if((*Board)[Col][i] >= 0) (*Board)[Col][i] += Inc;
if((*Board)[i][Row] >= 0) (*Board)[i][Row] += Inc;
}
for(i = Col, j = Row; j < Queens && i < Queens; i++, j++)
if((*Board)[i][j] >= 0) (*Board)[i][j] += Inc;
for(i = Col, j = Row; j >= 0 && i >= Col; i--, j--)
if((*Board)[i][j] >= 0) (*Board)[Col][j] += Inc;
for(i = Col, j = Row; j >= 0 && i < Queens; i++, j--)
if((*Board)[i][j] >= 0) (*Board)[i][j] += Inc;
for(i = Col, j = Row; j < Queens && i >= Col; i--, j++)
if((*Board)[i][j] >= 0) (*Board)[i][j] += Inc;
}
void FindSolutions(int *** Board, int Queens, int Col)
{
int i, j;
for(i = 0; i < Queens; i++)
{
if((*Board)[Col][i] != 0) continue;
(*Board)[Col][i] = -1;
if(Col + 1 == Queens)
Solutions++;
else
{
SavePosition(Board, Queens, Col, i, 1);
FindSolutions(Board, Queens, Col + 1);
SavePosition(Board, Queens, Col, i, -1);
}
(*Board)[Col][i] = 0;
}
}
void main(int argc, char **argv)
{
int Queens, ** Board = NULL;
clock_t Start, End;
clrscr();
if(argc < 2)
Queens = 8;
else
Queens = atoi(argv[1]);
Solutions = 0;
Start = clock();
AllocBoard(&Board, Queens);
FindSolutions(&Board, Queens, 0);
DeallocBoard(&Board, Queens);
End = clock();
printf("Solutions %ld\n", Solutions);
printf("Estimated time: %f", (End - Start) / CLK_TCK);
getch();
}
Hope this helps
Asking "why it doesn't work" about short and simple programs is not very well. Try debug it yourself with any debugger or simply using printing in important places/on each step. Actually, C has no arrays, instead it has pointers. You can work with them very alike, that is why all you need is to change int board[4][4] to int **board and add one argument: int N(count of cells) and that's all. All your other code shouldn't be changed.

Resources