Why isn't the code coming out of recursion? - c

The problem is to find the number of times a word occurs in a given N x N matrix of alphabets. We can move from any cell to other adjacent cell. The first line has one integer N and then a N x N matrix. Next line has M (size of the word) and then a string to be found in the matrix.
Input:
4
ABCD
ABCD
ABCD
ABCD
2
BC
Expected output:
10
I have written the following code for the same and used recursion for solving the problem. The function adj checks if the character is adjacent in the matrix with the previous character using their indexes. The function check increases the count whenever the string is completed. The 2-d array keeps a check on the visited and unvisited elements.
I am getting the output as
OUPUT
1
EDIT 1: This output is just because of the debugging print statement, so the if statement is being visited only once. It does not mean that the count variable is 1 after many recursion calls.
EDIT 2: There shouldn't be & in the scanf statement for word. But still the output is not the desired one.
EDIT 3:
Another input
7
SHELDON
HSTYUPQ
EHGXBAJ
LMNNQQI
DTYUIOP
OZXCVBN
NQWERTY
7
SHELDON
Expected output:
5
My output - 1
EDIT 4(Solved!): So the problem was in writing the no. of columns as 500 for the grid matrix, changing it to 5 did the job! Thanks to #gsamaras
Code
#include <stdio.h>
int vis[500][500], count;
int adj(int a, int b, int c, int d) {
if((c == a - 1) && (d == b - 1)) {
return 1;
}
else if((c == a - 1) && (d == b)) {
return 1;
}
else if((c == a) && (d == b - 1)) {
return 1;
}
else if((c == a - 1) && (d == b + 1)) {
return 1;
}
else if((c == a + 1) && (d == b)) {
return 1;
}
else if((c == a + 1) && (d == b + 1)) {
return 1;
}
else if((c == a) && (d == b + 1)) {
return 1;
}
else if((c == a + 1) && (d == b - 1)) {
return 1;
}
else {
return 0;
}
}
void check(char grid[][500],int i, int j, int id, char word[], int n, int m) {
if(id == m) {
count++;
printf("%d\n", count); // just to debug
}
else {
for(int p = 0; p < n; p++) {
for(int q = 0;q < n; q++) {
if((grid[p][q] == word[id]) && (adj(i, j, p, q)) && (vis[p][q] != 1)) {
vis[p][q] = 1;
check(grid, p, q, id + 1, word, n, m);
vis[p][q] = 0;
}
}
}
}
}
int main() {
int n, m, id = 0;
char blank;
scanf("%d", &n);
scanf("%c", &blank);
char grid[n][n+1];
for(int i = 0; i < n; i++) {
scanf("%s", grid[i]);
grid[i][n] = '\0';
}
scanf("%d", &m);
char word[m+1];
scanf("%s", &word);
for(int i = 0; i < n; i++) {
for(int j = 0;j < n; j++) {
if(grid[i][j] == word[id]) {
vis[i][j] = 1;
check(grid, i, j, id + 1, word, n, m);
vis[i][j] = 0;
}
}
}
printf("%d\n", count);
return 0;
}

Change this:
void check(char grid[][500], ......
to this:
void check(char grid[][5], ....... // that should be equal to N + 1 (5 in your case)
since your grid is of size N x N + 1. With the 500 as the dimension, you distorted the grid, and when trying to search into it recursively, you wouldn't traverse the grid that you would expect to traverse..
As you see this is not flexible, since N can vary. You cannot declare grid as global, since its dimensions are not fixed. Dynamic memory allocation should be used instead.
Change this:
scanf("%s", &word);
to this:
scanf("%s", word);
since word is an array of characters.
Complete example with Dynamic Memory Allocation:
#include <stdio.h>
#include <stdlib.h>
int vis[500][500], count;
char **get(int N, int M) { /* Allocate the array */
int i;
char **p;
p = malloc(N*sizeof(char *));
for(i = 0 ; i < N ; i++)
p[i] = malloc( M*sizeof(char) );
return p;
}
void free2Darray(char** p, int N) {
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
int adj(int a, int b, int c, int d) {
// Same as in your question
}
void check(char** grid, int i, int j, int id, char word[], int n, int m) {
if(id == m) {
count++;
printf("count = %d\n", count); // just to debug
}
else {
for(int p = 0; p < n; p++) {
for(int q = 0;q < 499; q++) {
//printf("p = %d, q = %d, id = %d, grid[p][q] = %c, word[id] = %c\n", p, q, id, grid[p][q], word[id]);
if((grid[p][q] == word[id]) && (adj(i, j, p, q)) && (vis[p][q] != 1)) {
vis[p][q] = 1;
check(grid, p, q, id + 1, word, n, m);
vis[p][q] = 0;
}
}
}
}
}
int main() {
int n, m, id = 0;
char blank;
scanf("%d", &n);
scanf("%c", &blank);
char** grid = get(n, n + 1);
for(int i = 0; i < n; i++) {
scanf("%s", grid[i]);
grid[i][n] = '\0';
}
scanf("%d", &m);
char word[m+1];
scanf("%s", word);
for(int i = 0; i < n; i++) {
for(int j = 0;j < n; j++) {
//printf("i = %d, j = %d, id = %d\n", i, j, id);
if(grid[i][j] == word[id]) {
vis[i][j] = 1;
check(grid, i, j, id + 1, word, n, m);
vis[i][j] = 0;
}
}
}
printf("%d\n", count);
free2Darray(grid, n);
return 0;
}
Output (for your 1st input):
count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10
10
PS: Not a problem, just a suggestion about readability: count is initialized to 0, because it's a global variable, but it's always best to explicitly initialize your variables, when it matters.

Related

Why does my program only work half the time?

I have an assignment to write a program for a natural number where its inverse is divisible by its number of digits. A natural number n ( n > 9) is entered from the keyboard. To find and print the largest natural number less than n that its inverse is divisible by its number of digits. If the entered number is not valid, print a corresponding message (Brojot ne e validen).
I have tried :
#include <stdio.h>
int main() {
int n,r,s=0,a=0;
int m;
scanf("%d",&n);
int t=n;
if(t<10)
{ printf("Brojot ne e validen");}
else {
for (int i = n - 1; i > 0; i--) {
while (n != 0) {
r = n % 10;
s = (s * 10) + r;
n = n / 10;
a++;
if (s % a == 0) {
m = i;
break;
}
}
}
printf("%d\n", m);
}
return 0;
}
And when my inputs is 50, it gives the correct answer which is 49, but when I try numbers like 100 or 17 it prints 98 instead of 89 and 16 instead of 7 respectively. I have been baffled by this for more than an hour now
check your logic.
you can check each value by
#include <stdio.h>
int main() {
int t,r,s=0,a=0;
int m;
scanf("%d",&t);
if(t<10)
{ printf("Brojot ne e validen");}
else {
for (int i = t - 1; i > 0; i--) {
while (t != 0) {
r = t % 10;
printf("%d \n", r);
s = (s * 10) + r;
printf("%d \n", s);
t = t / 10;
printf("%d \n", t);
a++;
if (s % a == 0) {
m = i;
break;
}
}
}
printf("%d\n", m);
}
return 0;
}

Recursive function to verify Matrix is Symmetric in C

I am just working on a recursive function to verify if a matrix is symmetric or not. The matrix must be square and I am considering max n = 20. I could develop the function:
int verifySymmetric(int m[20][20], int i, int j, int n) {
if (!((n == i) || (n == j))) {
if (m[i][j] != m[j][i]) {
return 0;
} else {
return (verifySymmetric(m, i + 1, j, n) && verifySymmetric(m, i, j + 1, n));
}
}
return 1;
}
Below is a code to run:
#include <stdio.h>
#include <stdlib.h>
int verifySymmetric(int m[20][20], int i, int j, int n) {
if (!((n == i) || (n == j))) {
if (m[i][j] != m[j][i]) {
return 0;
} else {
return (verifySymmetric(m, i + 1, j, n) && verifySymmetric(m, i, j + 1, n));
}
}
return 1;
}
int main() {
int n, r, c, m[20][20], t[20][20], flag, i, j;
i = j = 0;
printf("Enter matrix order >> ");
scanf("%d", &n);
printf("\nEnter the elements \n");
for (r = 0; r < n; r++) {
for (c = 0; c < n; c++) {
printf("m[%d][%d]: ", r + 1, c + 1);
scanf("%d", &m[r][c]);
}
}
for (r = 0; r < n; r++)
for (c = 0; c < n; c++)
t[c][r] = m[r][c];
flag = verifySymmetric(m, i, j, n);
if (flag == 1)
printf("Matrix is symmetric ");
if (flag == 0)
printf("Matrix is not symmetric ");
return 0;
}
My main concern is about the line
return (verifySymmetric(m, i + 1, j, n) && verifySymmetric(m, i, j + 1, n));
The program seem to work but I noticed that many m[row][column] is printed when I run the code. Something like this
Enter the elements
m[1][1]: m[1][2]: m[1][3]: m[1][4]: m[1][5]: m[1][6]: m[1][7]: m[1][8]: m[1][9]: m[1][10]: m[1]
[11]: m[1][12]: m[1][13]: m[1][14]: m[1][15]: m[1][16]: m[1][17]: m[1][18]: m[1][19]: m[1][20]:
m[1][21]: m[1][22]: m[1][23]: m[1][24]: m[1][25]: m[1][26]: m[1][27]: m[1][28]: m[1][29]: m[1]
[30]: m[1][31]: m[1][32]: m[1][33]: m[1][34]: m[1][35]: m[1][36]: m[1][37]: m[1][38]: m[1][39]:
m[1][40]: m[1][41]: m[1][42]: m[1][43]: m[1][44]: m[2][1]: m[2][2]: m[2][3]: m[2][4]: m[2][5]:
m[2][6]: m[2][7]: m[2][8]: m[2][9]: m[2][10]: m[2][11]: m[2][12]: m[2][13]: m[2][14]: m[2][15]:
m[2][16]: m[2][17]: m[2][18]: m[2][19]: m[2][20]: m[2][21]: m[2][22]: m[2][23]: m[2][24]:
What would be wrong with the function?
What would be another approach?
Edit
This is not a good approach, using recursion for a function like this, but I was curious about it and couldn't find an example in the internet. It is basically for learning purposes.
I am using Visual Studio Code and the strange behavior described above is when I click to Run Code two times. Running once, it runs as I expected, printing Enter matrix order >> , but once I click it for the second time without entering the matrix order, the misbehavior happens.
The code seems to work but it is very inefficient as the recursive approach will cause many redundant comparisons. The time complexity is O(n4) instead of O(n2)
You reason you get this misleading output is you prompt for each matrix value to stdout, but the input is read from a file and not echoed to stdout.
Here is a simpler non-recursive approach:
#include <stdio.h>
int verifySymmetric(int m[20][20], int n) {
for (int r = 0; r < n; r++) {
for (int c = 0; c < r; c++) {
if (m[r][c] != m[c][r])
return 0;
}
}
return 1;
}
int main() {
int n, m[20][20];
printf("Enter matrix order >> ");
if (scanf("%d", &n) != 1) {
printf("missing input\n");
return 1;
}
if (n < 1 || n > 20) {
printf("invalid dimension %d\n", n);
return 1;
}
printf("\nEnter the elements\n");
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++)
if (scanf("%d", &m[r][c]) != 1) {
printf("missing input\n");
return 1;
}
}
}
if (verifySymmetric(m, n)) {
printf("Matrix is symmetric\n");
else
printf("Matrix is not symmetric\n");
return 0;
}
If for some reason the implementation is required to be recursive, here is a modified version without redundant comparisons:
int verifySymmetric(int m[20][20], int i, int j, int n) {
if (j == n) {
return 1;
} else
if (i < j) {
return (m[i][j] == m[j][i]) && verifySymmetric(m, i + 1, j, n);
} else {
return verifySymmetric(m, 0, j + 1, n);
}
}

Count how often an int from an array appears in another array in C

I'm trying to solve an exercise that wants me to first create 2 arrays, sort them in ascending order and then count how many times a number from the first array appears in the second array. I'm almost finished. Everything seems to work perfectly fine except for one line that ruins the whole code. And I can't figure out why. I'm very new to C this is my very first exercise in this language.
Here's the code. I have commented the line that is not working:
#include <stdio.h>
void sort(int a[]) {
int i, j, l, t;
l = sizeof(a) / sizeof(a[0]);
for (i = 0; i < l + 1; i++) {
for (j = 0; j < (l - i); j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
void numberOfTimes(int a[], int b[]) {
int al = sizeof(a) / sizeof(a[0]);
int bl = sizeof(b) / sizeof(b[0]);
int i, p, c = 0;
for (i = 0; i <= al; i++) {
for (p = 0; i <= bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}
void main() {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int v, t;
printf("Type elements of A seperated by spaces. Do not enter duplicates (type 'end' to stop): ");
while (scanf("%d", &a[i]) == 1)
i++;
scanf("%*s");
i = 0;
printf("Type elements of B seperated by spaces(type 'end' to stop): ");
while (scanf("%d", &b[i]) == 1)
i++;
scanf("%*s");
sort(a);
sort(b);
numberOfTimes(a, b);
}
The idea is that the code will first sort both arrays and then print it out in the format (n, m). n is an int from array a and m is how many times it appears in array b.
For example you enter this:
a = {3, 2 ,1}
b = {1, 3, 2, 3, 3, 2, 1}
And the code does first sort:
a = {1, 2, 3}
b = {1, 1, 2, 2, 3, 3, 3}
And then prints out how many times a number from an array a appears in b:
(1, 2) (2, 2) (3, 3)
You cannot compute the array size from a pointer received as an argument: l = sizeof(a)/sizeof(a[0]); only works if a is an array, not a pointer.
You must pass the array sizes to functions sort and numberOfTimes. In your code, the array size is not what you need, but the number of elements actually parsed for each array. You must store these numbers specifically.
Note that your sorting code is incorrect, you should not adjust j's upper bound to avoid accessing array elements beyond the end. The same is true for the numberOfTimes function. The count c must be set to 0 for each new element of a that you search in b.
Note that your code does not take advantage of the fact that a and b are sorted.
Here is a corrected version:
#include <stdio.h>
void sort(int a[], int l) {
int i, j, t;
for (i = 0; i < l; i++) {
for (j = 0; j < l - i - 1; j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
void numberOfTimes(int a[], int al, int b[], int bl) {
int i, p, c;
for (i = 0; i < al; i++) {
c = 0;
for (p = 0; p < bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}
int main(void) {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int al, bl, v, t;
printf("Type elements of A separated by spaces. Do not enter duplicates (type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &a[i]) != 1)
break;
}
scanf("%*s");
al = i;
printf("Type elements of B separated by spaces(type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &b[i]) != 1)
break;
}
scanf("%*s");
bl = i;
sort(a, al);
sort(b, bl);
numberOfTimes(a, al, b, bl);
return 0;
}

Generate all binary strings of length n with k bits set.(need to write on C)

Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:
n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101
** can't generate these permutations
Code:
#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");
}
}
return 0;
}
I have solved this problem earlier! please find my code below! I hope this will help you out.
#include<stdio.h>
int NumberOfBitsSet(int number)
{
int BitsSet = 0;
while(number != 0)
{
if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}
return BitsSet;
}
void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set
while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}
val = val >> 1;
}
}
int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);
min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}
return 0;
}
Your code is a mess ;)
Seriously: first rule when solving a task in code is to write clean code, use sensible variable naming etc.
For tasks like this one I would suggest using this.
Now to your sample code: it would not compile and it is hard to read what you are trying to do. Formatted and with some comments:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
The extensive use of printf when one are not sure of what is going on is a precious tool.
This is not a solution, (it is basically doing the same as your post, but split up), but a sample of something that might be easier to work with. I have also used a char array as C-string instead of integer array. Easier to work with in this situation.
If you want to use integer array I'd suggest you add a print_perm(int *perm, int width) helper function to get it out of the main code.
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}
If you want to list all of the permutations uniquely without doing "iterate and check", you can do something like this:
# Move peg x up m using s
# x is negative
# m is positive
def move(x, m, s):
for i in range(1, m+1):
s2 = list(s)
s2[x] = 0
s2[x - i] = 1
print(s2)
if x + 1 < 0:
move(x+1, i, s2)
# Print all unique permutations of
# n bits with k ones (and n-k zeros)
def uniqPerms(n, k):
s = [0 for _ in range(n-k)] + [1 for _ in range(k)]
print(s)
move(-k, n-k, s)
if __name__ == '__main__':
from sys import argv
uniqPerms(int(argv[1]), int(argv[2]))
The idea is that you inch the 1's up recursively, so that each movement produces a unique list (since a 1 is now somewhere none was before).
And you said it must be in C:
#include <stdio.h>
#include <stdlib.h>
enum { n = 8 };
struct string
{
char str[n + 1];
};
void move(int x, int m, string s)
{
for (int i = 0; i <= m; ++i)
{
string s2 = s;
s2.str[n + x] = '0';
s2.str[n + x - i] = '1';
printf("%s\n", s2.str);
if (x + 1 < 0)
move(x + 1, i, s2);
}
}
void uniqPerms(int k)
{
string s;
for (int i = 0; i < n - k; ++i)
s.str[i] = '0';
for (int i = n - k; i < n; ++i)
s.str[i] = '1';
s.str[n] = '\0';
printf("%s\n", s.str);
move(-k, n - k, s);
}
int main(int argc, char *argv[])
{
uniqPerms(atoi(argv[1]));
return 0;
}
try this
A[n-1]=0;
func(n-1);
A[n-1]=1;
func(n-1);
//Think simple people but please bear with me i love java
//Assume array A is globally defined
void Binary(int n)
{
if(n<1)
{
System.out.println(A);
}
else
{
A[n-1]=0;
Binary(n-1);
A[n-1]=1;
Binary(n-1);
}
}
here is the recursive solution
#include <iostream>
#include <vector>
using namespace std;
char v[4];
int count = 0;
void printString(){
int i;
for(i = 0; i < 4; i++){
cout << v[i] << " ";
}
cout <<count << endl;
}
void binary(int n){
if(n < 0){
if(count == 2)
printString();
}
else{
v[n] = '0';
binary(n - 1);
v[n] = '1';
count++;
binary(n-1);
count--;
}
}
int main(){
binary(3);
return 0;
}
#include<stdio.h>
int main(){
int n,k,i,j,a[50];
//lets suppose maximum size is 50
printf("Enter the value for n");
scanf("%d",&n);
printf("Enter the value for k");
scanf("%d",&k);
//create an initial bitstring of k 1's and n-k 0's;
for(i=0;i<n;i++){
if(k>0)
a[i]=1;
else
a[i]=0;
k--;
}
for(i=0;i<n;i++){
if(a[i]==1){
for(j=0;j<n;j++){
if(j!=i&&a[j]==0){
a[j]=1;a[i]=0;
for(k=0;k<n;k++){printf("%d\n",a[k]);}
a[i]=1; a[j]=0;
}}}}
return 0;
}
**If Complexity doesn't matter you can use the following code which are done in java. which will provide the desired output in o(2^n).Here I have find all the combination of 0 and 1 for the given n bits in array of size n.In case of K bit is set I have counted the number of 1 presented is equal to k using countBits() funtion.if so I have printed that array.
public class GenerateAllStringOfNBitsWithKBitsSet {
public static int a[] ={0,0,0,0,0};
static int k=3;
public static boolean countBits(){
int y=0;
for(int i=0;i<a.length;i++)
y += a[i] & 1 ;
if(y==k)
return true;
return false;
}
public static void gen(int n)
{
if(n<1)
{
if(countBits())
System.out.println(Arrays.toString(a));
}
else
{
a[n-1]=0;
gen(n-1);
a[n-1]=1;
gen(n-1);
}
}
public static void main(String[] args) {
GenerateAllStringOfNBitsWithKBitsSet.gen(a.length);
}
}

intersection and union of n-arrays in C

I have those functions which are making intersection/union but just of two arrays.
I need too improve them to work with n-arrays: arr = {{1,2,3},{1,5,6},...,{1,9}}.
The arrays are sorted , and their elements are unique among them.
Example (intersection):
Input: {{1,2,3,4},{2,5,4},{4,7,8}}
Output: {4}
arr1[],arr2 - arrays
m,n - length of the arrays
Intersection function:
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
printf(" %d ", arr2[j++]);
i++;
}
}
}
and union function:
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
printf(" %d ", arr1[i++]);
else if(arr2[j] < arr1[i])
printf(" %d ", arr2[j++]);
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}
union(a, b, c) = union(union(a, b), c), and the same goes for intersection(). I.e. you can decompose the union or intersection of n sets into n unions or intersections of 2 sets (as NuclearGhost points out in a comment on the question). What you need to do is change your current functions so that they build up a resulting set, instead of immediately printing the result. You can then make a separate function that prints a set.
For efficiency, you want to take the union or intersection of sets that are roughly of equal size. So a divide-and-conquer approach should work alright, assuming that all input sets are likely to be of roughly equal size.
void intersection(int arr1[], int arr2[], int m, int n, int *out)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
*out++ = arr2[j++];
i++;
}
}
}
void multi_intersection(int n, int **arrays, int *lengths, int *out) {
if (n == 2) {
intersection(arrays[0], arrays[1], lengths[0], lengths[1], out);
} else if (n == 1) {
memcpy(out, arrays[0], lengths[0] * sizeof (int));
} else {
/* Allocate buffers large enough */
int *buf[2];
int len[2] = { INT_MAX, INT_MAX };
int i;
for (i = 0; i < n; ++i) {
int which = i < n / 2;
if (lengths[i] < len[which]) len[which] = lengths[i];
}
buf[0] = malloc(len[0] * sizeof (int));
buf[1] = malloc(len[1] * sizeof (int));
/* Recurse to process child subproblems */
multi_intersection(n / 2, arrays, lengths, buf[0]);
multi_intersection(n - n / 2, arrays + n / 2, lengths + n / 2, buf[1]);
/* Combine child solutions */
intersection(buf[0], buf[1], len, out);
free(buf[0]);
free(buf[1]);
}
Similar code works for multi_union(), except that the buffer lengths need to be calculated differently: the result of a union could be as large as the sum of the sizes of the inputs, rather than the minimum size of the inputs. It could probably be rewritten to do less buffer allocation. Also the recursion could be rewritten to use iteration, the same way mergesort can be written to use iteration, but the current recursive approach uses only O(log n) additional stack space anyway.
presume the max value in arrays is less than K. N is the number of arrays
int Result[K] = {0};
intersection function
//input array1
int index = 0;
for(; index < arrary1len;index++)
{
Result[array1]++;
}
.....
for(index = 0; index < K; index++)
{
if(Result[index] == N)
printf("%d",index);
}

Resources