I am new to C and wondering why I am not getting any kind of output. I am trying to get my program to convert a hexadecimal number to binary.
#include <stdio.h>
#include <stdlib.h>
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size) {
int hex_size = input_array_size;
int binary_array_size = 4 * hex_size;
int *binary_array = (int*) malloc(binary_array_size * sizeof(int));
int hex_index, binary_index;
for (hex_index = 0; hex_index < hex_size; hex_index++) {
int hex_num = hex_array[hex_index];
binary_index = hex_index * 4;
int bit_count;
for (bit_count = 3; bit_count <= 0; bit_count--) {
binary_array[binary_index + bit_count] = hex_num % 2;
hex_num = hex_num / 2;
}
hex_index++;
}
*return_array_size = binary_array_size;
return binary_array;
}
int main() {
char baseString[11];
int count = 0;
int i, j;
int original, wanted;
int size;
printf("Welcome to use this number base converter program.\n");
printf("Please input the original base: ");
scanf("%d", &original);
printf("Please input a base-%d number with more more than 10 digits: ",
original);
scanf("%s", baseString);
while (baseString[count] != '\0')
count++;
int *baseNumber = (int*) malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
baseNumber[i] =
baseString[i] <= '9' ? baseString[i] - '0' : baseString[i] - 'A' + 10;
}
int* result_array;
printf("Please input the target base: ");
scanf("%d", &wanted); //doesn't read anything past this point
printf("Target base: %d", wanted);
if (original == 16) {
if (wanted == 2) {
result_array = hex2binary(baseNumber, count, size);
for (j = 0; j < size; j++) {
printf("Result: %d", result_array[j]);
}
}
}
}
I know it can't be something to difficult, but I can't seem to figure out why it isn't even producing some kind of output.
This line
result_array = hex2binary(baseNumber, count, size);
is incorrect because this function needs a pointer argument
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size)
So it should be called like this
result_array = hex2binary(baseNumber, count, &size); // note the &
Then the subsequent loop
for (j = 0; j < size; j++)
will no longer be using the uninitialised variable size.
Related
The program is supposed to ask for length and number of binary arrays and then stores them and converts them all into decimal and prints the decimal part. The logic seems fine to me but it isn't working for some reason and gives weird outputs. Here's the code:
#include <stdio.h>
int main() {
int n, decimal_num = 0, base = 1, rem;
printf ("Enter the length and number of binary strings: ");
scanf(" %i", &n);
int str[n], deci[n];
for (int i = 0; i<n; i++) {
printf("Enter string %i: ", i + 1);
scanf(" %i", &str[i]);
}
for (int i = 0; i < n; i++) {
while (str[i] > 0) {
rem = str[i] % 10;
decimal_num = decimal_num + rem * base;
str[i] = str[i] / 10;
base = base * 2;
}
deci[i]= decimal_num;
decimal_num= 0;
}
for (int i = 0; i < n; i++) {
printf("%i\n", deci[i]);
}
}
There are a few issues I see with this program. First off creating arrays the way you did will give errors with most compilers. This is fixed by dynamically allocating the arrays by including stdlib.h and using malloc
int *str, *deci;
str = malloc(n * sizeof(int));
deci = malloc(n * sizeof(int));
This also means you would need to free this memory at the end at the end of your program.
free(str);
free(deci);
The second issue is in the second loop calculating the base 10 values. This is most likely what is causing the incorrect output. The issue is caused by not resetting the base variable after each iteration of the loop. This is causing the program to interpret the binary numbers at much larger than they actually are. This can be fixed by setting the base variable back to one in the same place you are setting decimal_num to zero
Another issue which doesn't affect functionality is the naming of your variables. More specifically the variable str which doesn't store a string. You should rename this to something more descriptive e.g. binary_nums. I would also recommend renaming deci for the same reason.
Additionally I was also getting issues with the scanf call using %i in the first loop so I changed it to %d which fixed the issue for me.
The fixed program looks like this
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, decimal_num = 0, base = 1, rem;
int *binary_nums, *base10_nums;
printf("Enter the length and number of binary strings: ");
scanf(" %d", &n);
binary_nums = malloc(n * sizeof(int));
base10_nums = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
printf("Enter string %i: ", i + 1);
scanf(" %d", &binary_nums[i]);
}
for (int i = 0; i < n; i++) {
while (binary_nums[i] > 0) {
rem = binary_nums[i] % 10;
decimal_num = decimal_num + rem * base;
binary_nums[i] = binary_nums[i] / 10;
base = base * 2;
}
base10_nums[i] = decimal_num;
decimal_num = 0;
base = 1;
}
for (int i = 0; i < n; i++) {
printf("%i\n", base10_nums[i]);
}
free(binary_nums);
free(base10_nums);
}
unsigned conv(const char *binaryString)
{
unsigned result = 0;
while(binaryString && *binaryString)
{
if(*binaryString == '\n') break;
result *= 2;
result += *binaryString++ == '1';
}
return result;
}
int main(void)
{
int size, number;
scanf("%u", &size);
scanf("%u", &number);
/* check return value of scanf */
char strings[number][size+1];
for(int n = 0; n < number; )
{
fgets(strings[n], size, stdin);
/* add error checks */
if(strings[n++][0] == '\n') n--;
}
for(int n = 0; n < number; n++)
{
printf("%u (0x%x) == %s", conv(strings[n]), conv(strings[n]), strings[n]);
}
}
I was trying to write a function that checks if an array has consecutive numbers (not necessarily in order), return 0 if not and 1 if yes.
For example:
24, 21, 22, 23
The return value would be 1.
22,22,22
Would return 0.
The problem is that it return 1 for something like:
22,22,22
I could really use the help looking into it.
This is the main function (no need to check it or anything, it's fine):
#include <stdio.h>
#include <stdlib.h>
/* Function declarations */
void Ex1();
void Ex2();
void Ex3();
void Ex4();
void Ex5();
/* Declarations of other functions */
int f3(int *, int);
/* ------------------------------- */
//
int main() {
int select = 0, i, all_Ex_in_loop = 0;
printf("Run menu once or cyclically?\n"
"(Once - enter 0, cyclically - enter other number) ");
if (scanf_s("%d", &all_Ex_in_loop) == 1)
do {
for (i = 1; i <= 5; i++)
printf("Ex%d--->%d\n", i, i);
printf("EXIT-->0\n");
do {
select = 0;
printf("please select 0-5 : ");
scanf_s("%d", &select);
} while ((select < 0) || (select > 5));
switch (select) {
case 1: Ex1(); break;
case 2: Ex2(); break;
case 3: Ex3(); break;
case 4: Ex4(); break;
case 5: Ex5(); break;
}
} while (all_Ex_in_loop && select);
return 0;
}
and this is the function (UPDATED):
void Ex3() {
int n, i, res;
printf("Enter the size of the Array: ");
scanf_s("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
if (!arr) {
printf("ERROR - not enough memory.");
exit(1);
}
printf("Enter an Array >>> ");
for (i = 0; i < n; i++)
scanf_s("%d", &arr[i]);
res = f3(arr, n);
printf("res = %d\n", res);
free(arr);
}
int f3(int *arr, int size) {
int i, min = arr[0], max = arr[0];
for (i = 1; i < size; i++) {
if (arr[i] < min)
min = arr[i];
if (arr[i] > max)
max = arr[i];
}
int *CounterArray = (int *)calloc(max + 1, sizeof(int));
if (!CounterArray) {
printf("ERROR - not enough memory.");
exit(1);
}
for (i = 0; i < size; i++) {
CounterArray[arr[i]]++;
}
for (i = min; i <= max; i++)
if (CounterArray[i] == 0)
return 0;
free(CounterArray);
return 1;
}
There are multiple problems in your code:
in function f3() you allocate an array of max + 1 integers. This would be a problem is all numbers in the array are negative. You should instead check that max - min + 1 is exactly the size of the array and allocate size elements.
you reject the array if and only if an element in the range has a 0 count. You should instead check that all elements have a 1 count. This explains why the function fails for 22,22,22.
Here is a modified version:
int f3(const int *arr, int size) {
int result = 1;
if (size <= 0)
return 1;
int i, min = arr[0], max = arr[0];
for (i = 1; i < size; i++) {
if (min > arr[i])
min = arr[i];
if (max < arr[i])
max = arr[i];
}
if (max - min + 1 != size)
return 0;
unsigned char *CounterArray = calloc(size, sizeof(*CounterArray));
if (!CounterArray) {
printf("ERROR - not enough memory.");
exit(1);
}
for (i = 0; i < size; i++) {
// increment the count of this element
if (CounterArray[arr[i] - min]++) {
// if the count was already non zero, the test fails.
result = 0;
break;
}
}
free(CounterArray);
return result;
}
You return zero under the condition that
if (CounterArray[i] == 0)
but in your test case of 22,22,22 you have min and max both equal 22 and CounterArray[22] equal 3, not 0.
You need to re-think the condition...
I tackled the problem by first figuring out the length of two given numbers and aligning the one with less digits (if one exists) into a new array so that the ones, tens, hundreds etc. align with the bigger number's ones, tens, hundreds, etc.
Then I wanted to save the sum of each two aligned elements (with a mod of 10) into a new array while checking if the sum of digits is greater than 10 - just the basic sum stuff. Now the problem occurs with adding two elements into the aplusb integer and I've tried fixing it with writing
int aplusb = (lengthA[max-i]-'0') +(temp[max-i]-'0');
but it doesn't work. I'm stuck and I don't know what to do. Please help.
The whole code:
#include <stdio.h>
#include <math.h>
int main(){
char a[10000];
char b[10000];
scanf("%s %s", &a, &b);
char sum[10000];
int lengthA = 0;
int lengthB = 0;
int i = 0;
while(a[i]){
i++;
} lengthA = i;
i = 0;
while(b[i]){
i++;
} lengthB = i;
char temp[10000];
int aplusb;
int carry = 0;
int max = lengthA;
int difference = abs(lengthA - lengthB);
if(lengthA>lengthB){
for(i=0; i<lengthA; i++){
temp[i+difference]=b[i];
}
for(i=0; i<=max; i++){
aplusb = lengthA[max-i]+temp[max-i]; //<-- this is the problematic line
if(carry = 1) aplusb++;
if(aplusb>9){
carry = 1;
aplusb%=10;
}
sum[i]=aplusb;
}
}
for(i=0; i<=max; i++){
printf("%c", sum[i]);
}
/*
if(lengthB>lengthA){
max = lengthB;
for(i=0; i<lengthB; i++){
temp[i+difference]=a[i];
}
}*/
return 0;
}
Doing operations and storing on very large numbers is very akin to doing operations and storing polynomials, i.e. with x = 10. a0 + a1.10 + a2.10^2 ... + an.10^n.
There are many polynomial libraries on the Internet, where you could find inspiration. All operations on your very large numbers can be expressed in terms of polynomials. This means that by using base 2^8, or even base 2^63, instead of base 10 to internally store your large numbers you would greatly improve performance.
You must also normalize your coefficients after operations to keep them positive. Operations may result in a negative coefficient, That can easily be fixed, as it is very similar to borrowing after a subtraction, this means coefficients must be larger than your base by 1bit.
To convert back to base 10, you'd need to solve r (your result) for v (your value), such as r(10)=v(2^63). This has only one solution, if you enforce the positive coefficients rule.
[note] After thinking about it some more: the rule on positive coefficients may only be necessary for printing, after all.
Example: adding. no memory error checking
int addPolys(signed char** result, int na, const signed char* a, int nb, const signed char* b)
{
int i, nr, nmin, carry, *r;
nr = max(na, nb) + 1;
nmin = min(na, nb);
r = malloc(sizeof(signed char) * (na + nb + 1));
if (nb < na)
{
nr = nb;
}
for (i = 0; i < nmin; ++i)
{
r[i] = a[i] + b[i];
}
for (; i < na; ++i)
{
r[i] = a[i];
}
for (; i < nb; ++i)
{
r[i] = b[i];
}
r[nr - 1] = 0;
// carry - should really be a proc of its own, unoptimized
carry = 0;
for (i = 0; i < nr; ++i)
{
r[i] += carry;
if (r[i] > 10)
{
carry = r[i] / 10;
r[i] %= 10;
}
else if (r[i] < 0)
{
carry = (r[i] / 10) - 1;
r[i] -= (carry * 10);
}
else
carry = 0;
}
// 'remove' leading zeroes
for (i = nr - 1; i > 0; --i)
{
if (r[i] != 0) break;
}
++i;
*result = r;
if (i != nr)
{
*result = realloc(i * sizeof(signed char));
}
return i; // return number of digits (0 being 1 digit long)
}
That code is working now for any two positive numbers with up to ten thousand digits:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(){
char chara[10000];
char charb[10000];
scanf("%s %s", &chara, &charb);
int lengthA = strlen(chara);
int lengthB = strlen(charb);
int max = lengthA;
if(lengthB>lengthA) max=lengthB;
int dif = abs(lengthA - lengthB);
//ustvari int tabele
int a[max];
int b[max];
int sum[max+1];
// nastavi nule
int i;
for(i=0; i<max; i++){
a[i] = 0;
b[i] = 0;
sum[i] = 0;
} sum[max] = 0;
//prekopiraj stevila iz char v int tabele &obrni vrstni red
for(i=0; i<lengthA; i++){
a[i] = chara[lengthA-i-1]-'0';
}
for(i=0; i<lengthB; i++){
b[i] = charb[lengthB-i-1]-'0';
}
int vsota;
int prenos = 0;
for(i=0; i<max; i++){
vsota = a[i]+b[i] + prenos;
if(vsota>=10) prenos = 1;
else if (vsota<10) prenos = 0;
sum[i]=vsota%10;
}
if(prenos==1){
sum[max] = 1;
for(i = max; i>=0; i--){
printf("%d", sum[i]);
}
} else {
for(i = max-1; i>=0; i--){
printf("%d", sum[i]);
}
}
return 0;
}
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.
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);
}
}