Extending inner for loop calls indefinitely [closed] - c

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 6 years ago.
Improve this question
The following code snippet will print every 4 character long combination (without repetition) of the elements of an array.
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++)
for (int k = j + 1; k < len; k++)
for (int l = k + 1; l < len; l++)
printf("%c%c%c%c\n", arr[i], arr[j], arr[k], arr[l]);
My problem is I don't know how to extend this to a general function (ie print every N character long combination). How can I make a function do the same thing but be called like this:
combinationPrint(array, numberOfForLoops); // With other params if needed

The recursive version of your function would work like this:
void recur (char* arr, int i, int len, char *x, int k, int n) {
if (k==n) { // the last inner loop
x[k]=0;
printf ("%s\n", x);
}
else {
for (int j=i+1; j<len; j++) { // recursive loop
x[k]=arr[j];
recur (arr, j, len, x, k+1, n); // call recursion for an inner loop
}
}
}
In this recursion, arr and len correspond to your definition and n is the depth of the loops you want to achieve (4 in your non recursive version).
The trick is to use a null terminated array of n+1 chars, that you keep across the recursion and build the string that you want to print at the last level. i is then the starting position of the loop and k is the current level of recursion.
You would call this:
recur (arr, -1, len, out, 0, 4 );
Online demo

Without recursion, you can use this (len = length of the array) :
int i, j, w, x;
for(i=0; i<pow(len,len); i++){ //n^n possibilities / combinaisons
w = i;
for(j=0; j<len; j++){ //Show the combinaison
x = w%len; //We have juste to calculate the correct position with some modulos
printf("%c", array[x]);
w = w/len;
}
printf("\n");
}
For exemple with this implementation :
#include <stdio.h>
#include <math.h>
int main(){
int array[] = {1,2,3};
int len = 3;
int i, j, w, x;
for(i=0; i<pow(len,len); i++){
w = i;
for(j=0; j<len; j++){
x = w%len;
printf("%d", array[x]);
w = w/len;
}
printf("\n%d\n", i);
}
}
You should have :
111
211
311
121
221 [...]
133
233
333

Well, instead of N loops - you just need one. Within this main loop you have to have just two inner loops for incrementing array of indices and for printing values:
int increment(int* index, int N, int len)
{
for (int i = N - 1; i >= 0; --i)
{
++index[i];
if (index[i] < len)
return 1;
index[i] = 0;
}
return 0;
}
So - the main loop:
int index[N] = {};
do
{
// print
for (int i = 0; i < N; ++i)
printf("%c", arr[index[i]]);
printf("\n");
} while (increment(index, N, len));

Related

How to connect puzzles so that right edge has same length as left edge of another puzzle?

I have puzzles that looks like this:
=== ====
=== ===
=== ====
left edge has length from 0 to 10 000 and right also, middle part is from 1 to 10 000.
So the question is if i can build a rectangle? like first puzzle has length of left edge equal to 0 and the last puzzle has right edge of length 0 and in the middle they fit perfectly?
I am given the number of puzzle i have and their params like this:
6
1 9 2
0 3 1
0 4 1
8 9 0
2 9 0
1 5 0
and result can be any of that:
2
0 3 1
1 5 0
or
3
0 3 1
1 9 2
2 9 0
or
2
0 4 1
1 5 0
But if there is no result i have to printf("no result")
I have to do this in C, I thought about doing some tree and searching it with BFS where vertices would have edge lengths and edge would have middle length and when reached 0 i would go all way up and collect numbers but it's hard to code. So i decided to do recursion but im also stuck:
#include<stdio.h>
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int tab[a][3];//array for puzzles
int result[][3];//result array
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
int findx(int x, int a, int *tab[], int *result[], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[a][0] == x){//there i look for puzzles with x length at start
if(tab[a][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[a][m];
}
return print_result(result, k);//we will return result go to print_result function
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[a][m];
k += 1;
}
findx(tab[a][2], a, tab, result, k);
}
}
}
printf("no result");
}
int print_result(int *result[], int k){
printf("%d", &k);//how many puzzles i have
printf("\n");
for(int i = 0; i < k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", &result[i][j]);
}
printf("\n");//...in separate lines
}
}
I have an error that result array can't look like this int result[][3] because of of [] but I don't know how many puzzles I'm gonna use so?... and I have implicit declaration for both of my functions. Guys please help, I dont know much about C and its super hard to solve this problem.
I'm not sure I understand the overall logic of the problem, but you definitely are in need of some variable sized containers for result AND tab. Arrays are fixed size and must be defined at compile time. The following should at least compile without warnings:
#include<stdio.h>
#include<stdlib.h>
void print_result(int (*result)[3], int k){
printf("%d", k);//how many puzzles i have
printf("\n");
for(int i = 0; i <= k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", result[i][j]);
}
printf("\n");//...in separate lines
}
}
void findx(int x, int a, int (*tab)[3], int (*result)[3], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[i][0] == x){//there i look for puzzles with x length at start
if(tab[i][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[i][m];
}
print_result(result, k);//we will return result go to print_result function
return;
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[i][m];
k += 1;
///** Increase size of result **/
//int (*newptr)[3] = realloc(result, (k+1) * sizeof(int[3]));
//if (newptr)
// result = newptr;
}
findx(tab[i][2], a, tab, result, k);
}
}
}
printf("no result\n");
}
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int (*tab)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int (*result)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
Note that I changed the tab and result types to (*int)[3]. Due to order of operations, we need parentheses here. Because they are variable size, they require dynamic memory allocations. In the interest of brevity and readability, I did not check the returned values of malloc or realloc. In practice, you should be checking that the returned pointer is not NULL. Because we are using dynamic memory allocations, we should also use free if you plan on doing anything else with this program. Otherwise, it doesn't really matter because exiting the program will free the resources anyway. You actually don't want to free. because we are passing a pointer by value to findx and the realloc can change the address, it may come back with a different address. Also, take note that I needed to include <stdlib.h> for the dynamic memory allocations.
Additional Issues
Your functions print_results and findx are not declared when you call them in main. Your function either need to be above main or have "function prototypes" above main.
In the printfs you do not need the &. You do not want to send the address of the variable to printf. You want to send what will actually be printed.
Now what?
The program still does not provide you with the correct results. It simply outputs 0 as the result every time. This should at least give you a starting point. By changing this line in print_results:
for(int i = 0; i < k; i++){//printing puzzles...
to
for(int i = 0; i <= k; i++){//printing puzzles...
I was at least able to output 0 0 0. This seems more correct because if k is 0, we don't loop at all.
#include<stdio.h>
void findx(int x, int a, int tab[a][3], int result[200000][3], int puzzlesinresult) { //i am looking for puzzle with length x on start
for (int i = 0; i < a; i++) {
if (tab[i][0] == x) { //there i look for puzzles with x length at start
if (tab[i][2] == 0) { //if i find such puzzle i check if this is puzzle with edge length zero at the end
for (int m = 0; m < 3; m++) { //this for loop add to my result array last puzzle
result[puzzlesinresult][m] = tab[i][m];
}
return print_result(result, puzzlesinresult); //we will return result go to print_result function
} else { //if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
while (result[puzzlesinresult - 1][2] != tab[i][0] && puzzlesinresult > 0) {
puzzlesinresult -= 1;
}
int isusedpuzzle = 0;
for (int j = 0; j < puzzlesinresult; j++) {
if (result[j][0] == tab[i][0] && result[j][1] == tab[i][1] && result[j][2] == tab[i][2]) {
isusedpuzzle = 1;
} else {
//pass
}
}
if (isusedpuzzle == 0) {
for (int m = 0; m < 3; m++) {
result[puzzlesinresult][m] = tab[i][m];
}
puzzlesinresult += 1;
findx(tab[i][2], a, tab, result, puzzlesinresult);
}
}
}
}
}
void print_result(int result[200000][3], int puzzlesinresult) {
printf("%d\n", puzzlesinresult + 1); //how many puzzles i have
for (int i = 0; i < puzzlesinresult + 1; i++) { //printing puzzles...
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n"); //...in separate lines
}
exit(0);
}
int main() {
int a;
scanf("%d", & a); //here i get how many puzzles i have
int tab[a][3]; //array for puzzles
int result[100][3]; //result array
int puzzlesinresult = 0; //this will help me track how many puzzles has my result array
for (int i = 0; i < a; i++) { //upload puzzles to array
for (int j = 0; j < 3; j++) {
scanf("%d", & tab[i][j]);
}
}
for (int i = 0; i < a; i++) { //here i delete puzzles that doesnt contribute anything like 1 x 1,2 x 2,..
if (tab[i][0] == tab[i][2] && tab[i][0] != 0) {
for (int p = i; p < a; p++) {
for (int j = 0; j < 3; j++) {
tab[p][j] = tab[p + 1][j];
}
}
}
}
findx(0, a, tab, result, puzzlesinresult); //start of recursion, because start has to be length 0
printf("NONE");
}
This returns sometimes correct result. If you can find when this program fails I would rly appreciate sharing those cases with me :)

How to fix this code output is not showing in rat in mace problem

I'm solving this rat in mace problem by recursion.
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem.
This code i write by my own but output is not showing
#include <stdio.h>
//#where a[][] means denoting maze and b[][] means solution matrix and i put all zero in b[][]
int move(int a[3][3], int, int);
int recursion(int a[3][3], int b[3][3], int i, int j);
int main() {
int i, j, n = 3, a[20][20], b[20][20];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
scan("%d", &a[i][j]);
print("\n");
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
scan("%d", &b[i][j]);
print("\n");
}
int move(int a[3][3], int i, int j);
int recursion(int a[3][3], int b[3][3], int i, int j);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
print("%d", b[i][j]);
print("\n");
}
return 0;
}
int recursion(int a[3][3], int b[3][3], int i, int j) {
if (move(a, i, j) == 1) {
b[i][j] = 1;
if (recursion(a, b, i, j + 1) == 1)
return 1;
if (recursion(a, b, i + 1, j) == 1)
return 1;
b[i][j] = 0;
return -1;
}
return -1;
}
int move(int a[3][3], int i, int j) {
int n = 3;
if (i >= 0 && i < n && j >= 0 && j < n && a[i][j] == 1) {
return 1;
}
return -1;
}
This code does not show output please help me where is the error that its not showing output.
I expect the result will be if i take in maze array
for example a[][] is maze matrix
110
101
111
in solution matrix and print b[][] denoting solution matrix
this is actual solution i want
100
100
111
everything is fine but output is not showing.
Here i took 3 by 3 matrix to solve only the problem is output is not showing
Welcome to Stack Overflow, and welcome to C programming.
There is a lot that is wrong with your code. The first thing that jumps out at me are the lines:
int move(int a[3][3], int i, int j);
int recursion(int a[3][3], int b[3][3], int i, int j);
inside of your main() (lines 22 and 24). I imagine that what you intend to be doing there is calling move() and recursion(), but the syntax you are using is for a function declaration, not function calling.
Second, after both of your loops with scan() in them, i and j are each going to be "3"; I'm betting you want to call move() with i of "0" and j of "0", but that's not the value they will have after those input loops.
Third, speaking of scan(), my compiler warns about scan() and print() being implicitly defined; from context, I'm betting you want scanf() and printf().
Fourth, if you are inputing literally:
110
101
111
000
000
000
then you aren't even making it out of your input loops. Your input loops perform a total of 18 inputs, so your input would be more like:
1
1
0
1
0
1
1
1
1
0
0
0
0
0
0
0
0
0
(This is after I replaced scan() with scanf(), per my note above.)
Fifth, you declare move() and recursion() as accepting as their first parameters a type int[3][3], but a and b are of type int[20][20]; your input populates (part of) a and b, but you aren't going to be able to pass a nor b as the array arguments to move() and recursion().
I have not even looked into the logic of your functions. Likely, there are several other issues, as well.
I strongly recommend you start much smaller and much simpler. e.g., here's a much simpler program that compiles as-is without warnings, and will give you immediate feedback on what it is doing. Add to this in small steps, including relevant output lines, so that you can see exactly how it is all taking shape.
#include <stdio.h>
int main() {
int i, j, n = 3, input;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &input);
printf("input is : %d\n", input);
}
}
printf("i and j are : %d, %d\n", i, j);
return 0;
}
Good luck as you learn C -- there are great things ahead for you!

Maximum value of every contiguous subarray

Given an unsorted array A[0...n-1] of integers and an integer k; the desired algorithm in C should calculate the maximum value of every contiguous subarray of size k. For instance, if A = [8,5,10,7,9,4,15,12,90,13] and k=4, then findKMax(A,4,10) returns 10 10 10 15 15 90 90.
My goal is to implement the algorithm as a C programm that reads the elements of A, reads k and then prints the result of the function findKMax(A,4,10). An input/output example is illustrated bellow (input is typeset in bold):
Elements of A: 8 5 10 7 9 4 15 12 90 13 end
Type k: 4
Results: 10 10 10 15 15 90 90
What I've tried so far? Please keep in mind that I am an absolute beginner in C. Here is my code:
#include <stdio.h>
void findKMax(int A[], int k, int n) {
int j;
int max;
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
}
}
int main() {
int n = sizeof(A);
int k = 4;
printf("Elements of A: ");
scanf("%d", &A[i]);
printf("Type k: %d", k);
printf("Results: %d", &max);
return 0;
}
Update March 17th:
I've modified the source code, i.e. I've tried to implement the hints of Michael Burr and Priyansh Goel. Here is my result:
#include <stdio.h>
// Returning the largest value in subarray of size k.
void findKMax(int A[], int k, int n) {
int j;
int largestValueOfSubarray;
for (int i = 0; i <= n-k; i++) {
largestValueOfSubarray = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > largestValueOfSubarray)
largestValueOfSubarray = A[i+j];
}
printf("Type k: %d", k);
}
return largestValueOfSubarray;
}
int main() {
int n = 10;
int A[n];
// Reading values into array A.
for (int i = 0; i < n; i++) {
printf("Enter the %d-th element of the array A: \n", i);
scanf("%d", &A[i]);
}
// Printing of all values of array A.
for (int i = 0; i < n; i++) {
printf("\nA[%d] = %d", i, A[i]);
}
printf("\n\n");
// Returning the largest value in array A.
int largestValue = A[0];
for (int i = 0; i < n; i++) {
if (A[i] > largestValue) {
largestValue = A[i];
}
}
printf("The largest value in the array A is %d. \n", largestValue);
return 0;
}
I guess there is not so much to code. Can anybody give me a hint how to do the rest. I need an advice how to "combine" the pieces of code into a running program.
Since you are a beginner, lets begin with the simplest algorithm.
for every i, you need to find sum of k continous numbers starting from that i. And then find the max of it.
Before that you need to see how to take input to an array.
int n;
scanf("%d",&n);
int a[n];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
Also, you will need to call the function findKMax(a,n,k);
In your findKMax function, you have to implement the algorithm that I mentioned.
I will not provide the code so that you may try on your own. If you face any issue, do tell me.
HINT : You need to use nested loops.
You find max value in window many times, but output only the last max value.
The simplest correction - add output in the end of main cycle:
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
printf("Type k: %d", k);
}
The next step - collect all local max values in a single string "10 10 10 15 15 90 90" or additional array of length n-k+1: [10,10,10,15,15,90,90] and print it after the main cycle (I don't know the best approach for this in C)

Second least occurring element in an array in 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 6 years ago.
Improve this question
I am currently working on a project and for one of the parts I need to determine the second least occurring element in a C array. In any case, the maximum number of elements in the array is going to be 100. I have a function written already to find the least occurring element:
int minRepeat(int arr[], int i){
int j = 0;
int l = 0;
int minimum = 100;
int minNum = 0;
for(j = 0; j < i; j++){
int m = 0;
for(l = 0; l < i; l++){
if(arr[j] == arr[l]){
m++;
}
}
if(m < minimum){
minimum = m;
minNum = arr[j];
}
}
return minNum;
}
arr[] is the inputted array and int i is the size of that array.
I am trying to create a function that will find the second least occurring element in a C array. The function is currently:
int secMin(int arr[], int i){
int j = 0;
int l = 0;
int minimum = 0;
int minNum = 0;
int q = 0;
int k = minRepeat(arr, i);
for(q = 0; q < i; q++){
if(arr[q] == k){
minimum++;
}
}
int minimum2 = 100;
for(j = 0; j < i; j++){
int m = 0;
for(l = 0; l < i; l++){
if(arr[j] == arr[l]){
m++;
}
}
if(m < minimum2){
if(m > minimum){
minimum2 = m;
minNum = arr[j];
}
}
}
return minNum;
}
I am calling the first function to find the least occurring element. Looping through that to see how many times that element occurs in the array, and then doing the same as the first function to find the least occurring, but compare it to the first least element at the end to make sure that this element is the second least occurring.
When arr[] = {1, 1, 1, 2, 2, 3, 2, 2, 4, 1}
I get the least occurring number to be 3 and the second least occurring to be 1.
Sometimes the function works with other input and sometimes it does not, such as in the case above.
Thank you for your help!
Just adjust your first example a little to also store the second least element:
if(m < minimum){
secondminimum = minimum;
secondminNum = minNum
minimum = m;
minNum = arr[j];
}
Edit: I just realised that will only work if least and seconleast element do not have the same number of appearances, but you can capture that case.

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.

Resources