Print all binary numbers of length N - c

I've done this question on leetcode before but wanted to do it in C. Was wondering if anyone could let me know if there is a better way to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printBinaryLenthHelper(int currentLength, int maxLength, char accum[]) {
if (currentLength == maxLength) {
printf("%s\n", accum);
return;
}
accum[currentLength++] = '0';
printBinaryLenthHelper(currentLength, maxLength, accum);
accum[--currentLength] = '1';
printBinaryLenthHelper(++currentLength, maxLength, accum);
}
void printBinaryLength(int length) {
char accum[length + 1];
printBinaryLenthHelper(0, length, accum);
}
int main() {
printBinaryLength(20);
}

You can avoid recursion by simply iterating from 0 to 2^n -1. This range represents all the numbers with binary length n (assuming smaller numbers are padded with leading zeroes).
Code
#include <stdio.h>
void printBinary(int len) {
//This loop iterates from 0 to 2^len - 1
for(int i = 0; i < 1 << len; ++i) {
//This loop is to print the integer in its binary representation.
for(int j = len - 1; j >= 0; --j) {
// ((1<<j)&i) > 0 evaluates to 1 if the jth bit is set, 0 otherwise
printf("%d", ((1<<j)&i) > 0);
}
printf("\n");
}
}
int main(void) {
// your code goes here
printBinary(10);
return 0;
}
Output
0000000000
0000000001
0000000010
0000000011
0000000100
0000000101
0000000110
0000000111
0000001000
0000001001
0000001010
...
Tested here.
PS: If you do not understand what 1<<j and (1<<j)&j means, read about bitwise operators in C.

There is a problem in your function printBinaryLenthHelper: you do not null terminate the string before passing it to printf. It is also confusing to increment and decrement currentLength as a side effect, just pass the next value in the recursive call.
Here is a corrected version:
void printBinaryLenthHelper(int currentLength, int maxLength, char accum[]) {
if (currentLength == maxLength) {
accum[currentLength] = '\0';
printf("%s\n", accum);
return;
}
accum[currentLength] = '0';
printBinaryLenthHelper(currentLength + 1, maxLength, accum);
accum[currentLength] = '1';
printBinaryLenthHelper(currentLength + 1, maxLength, accum);
}
Note also that the name should be printBinaryLengthHelper.

Related

Long Long overflow

I have been working on a small program that converts strings into integers.
I started the program and I was first trying to save in an array but the program is not working.
Its iterating only once and there is no error.I tried it but I think the error is at when I convert the string by subtracting it by 48 in storing it in the array.You can see the code
Sorry this is an edited message tnow the program is working properly but when I give input -"-91283472332"(as per leetcode) I am getting a wrong answer
you can see for yourself -
#include <stdio.h>
int myAtoi(char *s)
{
int i = 0; // for iterating the character
int isNegative = 0; // for checking if the umber is negative
long long res = 0; // for result
while (s[i] != '\0')
{
printf("%d\n",res);
if (48 <= s[i] && s[i]<= 57)
{
res=(res*10)+(s[i]) - 48;
}
else if (s[i] == 45)
{
isNegative = 1;
}
else if (s[i] == ' ')
{
;
}
else
{
break;
}
i++;
}
if (isNegative)
{
res = res-(res*2);
}
printf("%d",res);
return res;
}
int main()
{
char a[] = "-91283472332";
myAtoi(a);
return 0;
}
Your solution is rather more complex than it needs to be.
We can use pointer arithmetic to iterate over the string, and include a condition for our for loop that automatically terminates at the end of the string or when the current character is no longer a digit.
The result can be built up by multiplying it by ten on each loop and adding the current digit's numeric value to it.
A negative sign can be accommodated by checking the first character. It's it's '-' we can set a flag negative to 1 for true and increment the str pointer past the first character. At the end of the function, we can determine whether to result -result or result based on that flag.
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int my_atoi(char *str) {
int result = 0;
int negative = 0;
if (*str == '-') {
negative = 1;
str++;
}
for (; *str && isdigit(*str); str++) {
result *= 10;
result += *str - '0';
}
return negative ? -result : result;
}
int main(void) {
char foo[] = "3456gfghd";
printf("%d\n", my_atoi(foo));
return 0;
}

How output a numbers with write() (only #include <unistd.h> allowed) [duplicate]

It is possible to convert integer to string in C without sprintf?
There's a nonstandard function:
char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation
Edit: it seems you want some algorithm to do this. Here's how in base-10:
#include <stdio.h>
#define STRINGIFY(x) #x
#define INTMIN_STR STRINGIFY(INT_MIN)
int main() {
int anInteger = -13765; // or whatever
if (anInteger == INT_MIN) { // handle corner case
puts(INTMIN_STR);
return 0;
}
int flag = 0;
char str[128] = { 0 }; // large enough for an int even on 64-bit
int i = 126;
if (anInteger < 0) {
flag = 1;
anInteger = -anInteger;
}
while (anInteger != 0) { 
str[i--] = (anInteger % 10) + '0';
anInteger /= 10;
}
if (flag) str[i--] = '-';
printf("The number was: %s\n", str + i + 1);
return 0;
}
Here's an example of how it might work. Given a buffer and a size, we'll keep dividing by 10 and fill the buffer with digits. We'll return -1 if there is not enough space in the buffer.
int
integer_to_string(char *buf, size_t bufsize, int n)
{
char *start;
// Handle negative numbers.
//
if (n < 0)
{
if (!bufsize)
return -1;
*buf++ = '-';
bufsize--;
}
// Remember the start of the string... This will come into play
// at the end.
//
start = buf;
do
{
// Handle the current digit.
//
int digit;
if (!bufsize)
return -1;
digit = n % 10;
if (digit < 0)
digit *= -1;
*buf++ = digit + '0';
bufsize--;
n /= 10;
} while (n);
// Terminate the string.
//
if (!bufsize)
return -1;
*buf = 0;
// We wrote the string backwards, i.e. with least significant digits first.
// Now reverse the string.
//
--buf;
while (start < buf)
{
char a = *start;
*start = *buf;
*buf = a;
++start;
--buf;
}
return 0;
}
Unfortunately none of the answers above can really work out in a clean way in a situation where you need to concoct a string of alphanumeric characters.There are really weird cases I've seen, especially in interviews and at work.
The only bad part of the code is that you need to know the bounds of the integer so you can allocate "string" properly.
In spite of C being hailed predictable, it can have weird behaviour in a large system if you get lost in the coding.
The solution below returns a string of the integer representation with a null terminating character. This does not rely on any outer functions and works on negative integers as well!!
#include <stdio.h>
#include <stdlib.h>
void IntegertoString(char * string, int number) {
if(number == 0) { string[0] = '0'; return; };
int divide = 0;
int modResult;
int length = 0;
int isNegative = 0;
int copyOfNumber;
int offset = 0;
copyOfNumber = number;
if( number < 0 ) {
isNegative = 1;
number = 0 - number;
length++;
}
while(copyOfNumber != 0)
{
length++;
copyOfNumber /= 10;
}
for(divide = 0; divide < length; divide++) {
modResult = number % 10;
number = number / 10;
string[length - (divide + 1)] = modResult + '0';
}
if(isNegative) {
string[0] = '-';
}
string[length] = '\0';
}
int main(void) {
char string[10];
int number = -131230;
IntegertoString(string, number);
printf("%s\n", string);
return 0;
}
You can use itoa where available. If it is not available on your platform, the following implementation may be of interest:
https://web.archive.org/web/20130722203238/https://www.student.cs.uwaterloo.ca/~cs350/common/os161-src-html/atoi_8c-source.html
Usage:
char *numberAsString = itoa(integerValue);
UPDATE
Based on the R..'s comments, it may be worth modifying an existing itoa implementation to accept a result buffer from the caller, rather than having itoa allocate and return a buffer.
Such an implementation should accept both a buffer and the length of the buffer, taking care not to write past the end of the caller-provided buffer.
int i = 24344; /*integer*/
char *str = itoa(i);
/*allocates required memory and
then converts integer to string and the address of first byte of memory is returned to str pointer.*/

Type casting failure in C program

As a C fresher, I am trying to write a recursive routine to convert a decimal number to the equivalent binary. However, the resultant string is not correct in the output. I think it has to be related to the Type casting from int to char. Not able to find a satisfactory solution. Can anyone help? Thanx in advance.
Code:
#include <stdio.h>
#include <conio.h>
int decimal, counter=0;
char* binary_string = (char*)calloc(65, sizeof(char));
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
*(binary_string + counter) = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
decimal_to_binary(number/2);
*(binary_string + counter) = temp;
counter++;
}
}
Should the casting store only the LSB of int in the char array each time?
Do not use global variables if not absolutely necessary. Changing the global variable in the function makes it very not universal.
#include <stdio.h>
char *tobin(char *buff, unsigned num)
{
if(num / 2) buff = tobin(buff, num / 2);
buff[0] = '0' + num % 2;
buff[1] = 0;
return buff + 1;
}
int main(void)
{
char buff[65];
unsigned num = 0xf1;
tobin(buff, num);
printf("%s\n", buff);
}
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int decimal, counter=0;
//char* binary_string = (char*)calloc(65, sizeof(char));
//C does not allow initialization of global variables with
//non constant values. Instead declare a static char array with 65 elements.
//Alternatively declare binary_string in the main function and allocate memory with calloc.
char binary_string[65];
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
//*(binary_string + counter) = '\0';
// This is more readable:
binary_string[counter] = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
//decimal_to_binary(number/2);
//you call decimal_to_binary again before increasing counter.
//That means every time you call decimal_to_binary, the value of count
//is 0 and you always write to the first character in the string.
//*(binary_string + counter) = temp;
//This is more readable
//binary_string[counter] = temp;
//But you are still setting the character at position counter to the literal value temp, which is either 0 or 1.
//if its 0, you are effectively writing a \0 (null character) which in C represents the end of a string.
//You want the *character* that represents the value of temp.
//in ASCII, the value for the *character* 0 is 0x30 and for 1 it is 0x31.
binary_string[counter] = 0x30 + temp;
counter++;
//Now after writing to the string and incrementing counter, you can call decimal_to_binary again
decimal_to_binary(number/2);
}
}
If you compile this, run the resulting executable and enter 16 as a number, you may expect to get 10000 as output. But you get00001. Why is that?
You are writing the binary digits to the string in the wrong order.
The first binary digit you calculate is the least significant bit, which you write to the first character in the string etc.
To fix that aswell, you can do:
void decimal_to_binary(int number){
if(number == 0){
return;
}
else{
int temp = number % 2;
counter++;
//Store the position of the current digit
int pos = counter;
//Don't write it to the string yet
decimal_to_binary(number/2);
//Now we know how many characters are needed and we can fill the string
//in reverse order. The first digit (where pos = 1) goes to the last character in the string (counter - pos). The second digit (where pos = 2) goes to the second last character in the string etc.
binary_string[counter - pos] = 0x30 + temp;
}
}
This is not the most efficient way, but it is closest to your original solution.
Also note that this breaks for negative numbers (consider decimal = -1, -1 % 2 = -1).

Count of similar characters without repetition, in two strings

I have written a C program to find out the number of similar characters between two strings. If a character is repeated again it shouldn't count it.
Like if you give an input of
everest
every
The output should be
3
Because the four letters "ever" are identical, but the repeated "e" does not increase the count.
For the input
apothecary
panther
the output should be 6, because of "apther", not counting the second "a".
My code seems like a bulk one for a short process. My code is
#include<stdio.h>
#include <stdlib.h>
int main()
{
char firstString[100], secondString[100], similarChar[100], uniqueChar[100] = {0};
fgets(firstString, 100, stdin);
fgets(secondString, 100, stdin);
int firstStringLength = strlen(firstString) - 1, secondStringLength = strlen(secondString) - 1, counter, counter1, count = 0, uniqueElem, uniqueCtr = 0;
for(counter = 0; counter < firstStringLength; counter++) {
for(counter1 = 0; counter1 < secondStringLength; counter1++) {
if(firstString[counter] == secondString[counter1]){
similarChar[count] = firstString[counter];
count++;
break;
}
}
}
for(counter = 0; counter < strlen(similarChar); counter++) {
uniqueElem = 0;
for(counter1 = 0; counter1 < counter; counter1++) {
if(similarChar[counter] == uniqueChar[counter1]) {
uniqueElem++;
}
}
if(uniqueElem == 0) {
uniqueChar[uniqueCtr++] = similarChar[counter];
}
}
if(strlen(uniqueChar) > 1) {
printf("%d\n", strlen(uniqueChar));
printf("%s", uniqueChar);
} else {
printf("%d",0);
}
}
Can someone please provide me some suggestions or code for shortening this function?
You should have 2 Arrays to keep a count of the number of occurrences of each aplhabet.
int arrayCount1[26],arrayCount2[26];
Loop through strings and store the occurrences.
Now for counting the similar number of characters use:
for( int i = 0 ; i < 26 ; i++ ){
similarCharacters = similarCharacters + min( arrayCount1[26], arrayCount2[26] )
}
There is a simple way to go. Take an array and map the ascii code as an index to that array. Say int arr[256]={0};
Now whatever character you see in string-1 mark 1 for that. arr[string[i]]=1; Marking what characters appeared in the first string.
Now again when looping through the characters of string-2 increase the value of arr[string2[i]]++ only if arr[i] is 1. Now we are tallying that yes this characters appeared here also.
Now check how many positions of the array contains 2. That is the answer.
int arr[256]={0};
for(counter = 0; counter < firstStringLength; counter++)
arr[firstString[counter]]=1;
for(counter = 0; counter < secondStringLength; counter++)
if(arr[secondString[counter]]==1)
arr[secondString[counter]]++;
int ans = 0;
for(int i = 0; i < 256; i++)
ans += (arr[i]==2);
Here is a simplified approach to achieve your goal. You should create an array to hold the characters that has been seen for the first time.
Then, you'll have to make two loops. The first is unconditional, while the second is conditional; That condition is dependent on a variable that you have to create, which checks weather the end of one of the strings has been reached.
Ofcourse, the checking for the end of the other string should be within the first unconditional loop. You can make use of the strchr() function to count the common characters without repetition:
#include <stdio.h>
#include <string.h>
int foo(const char *s1, const char *s2);
int main(void)
{
printf("count: %d\n", foo("everest", "every"));
printf("count: %d\n", foo("apothecary", "panther"));
printf("count: %d\n", foo("abacus", "abracadabra"));
return 0;
}
int foo(const char *s1, const char *s2)
{
int condition = 0;
int count = 0;
size_t n = 0;
char buf[256] = { 0 };
// part 1
while (s2[n])
{
if (strchr(s1, s2[n]) && !strchr(buf, s2[n]))
{
buf[count++] = s2[n];
}
if (!s1[n]) {
condition = 1;
}
n++;
}
// part 2
if (!condition ) {
while (s1[n]) {
if (strchr(s2, s1[n]) && !strchr(buf, s1[n]))
{
buf[count++] = s1[n];
}
n++;
}
}
return count;
}
NOTE: You should check for buffer overflow, and you should use a dynamic approach to reallocate memory accordingly, but this is a demo.

How can i generate 4 bit binary combination using recursion in C for 0,1?

For this array, trying something like this:
void rollover(int val,int count) {
if(count==0) {
return;
}
printf("%d ",val);
count--;
rollover(val,count);
}
int main() {
int arr[]={0,1};
for(int i=0;i<=1;i++) {
rollover(arr[i],4);
}
printf("\n");
return 0;
}
Expected output using recursion method:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Can't understand how to write that rec function. I have spent several hours to solve it.
Can someone assist to write that function?
I am/was trying to do something like G_G posted below.
How can i write such recursion function?
Do i have to use one for loop to call that recursion function or two for loop with recursion or should i call the recursion function twice? For example:
void rollover(int val,int count) {
if(count==0) {
return;
}
printf("%d ",val);
count--;
rollover(val,count);
//.. do something if necessary ..
rollover(val,count);
//.. do something if necessary ..
}
Simplest solution : binary conversion, no recursion
for(int i = 0; i < 16: ++i) {
printf("%u%u%u%u", i/8%2, i/4%2, i/2%2, i%2);
}
See MOHAMED's answer for a recursive version of this loop
Binary recursion used by the following solutions
_ 000
_ 00 _/
/ \_ 001
0 _ 010
\_ 01 _/
\_ 011
_ 100
_ 10 _/
/ \_ 101
1 _ 110
\_ 11 _/
\_ 111
Recursive solution using char* buffer, no binary conversion
void char_buffer_rec(char number[4], int n) {
if(n > 0) {
number[4-n] = '0';
char_buffer_rec(number, n - 1);
number[4-n] = '1';
char_buffer_rec(number, n - 1);
}
else {
printf("%s\n", number);
}
}
usage :
char number[5] = {0};
char_buffer_rec(number, 4);
Recursive solution using only int, no buffer, no binary conversion
void int_ten_rec(int number, int tenpower) {
if(tenpower > 0) {
int_ten_rec(number, tenpower/10);
int_ten_rec(number + tenpower, tenpower/10);
}
else {
printf("%04u\n", number);
}
}
usage :
int_ten_rec(0, 1000);
Another version of this solution replacing tenpower width bitwidth, replacing the printf width with a variable padding depending on the length variable. length could be defined as a new parameter, a program constant, etc.
void int_rec(int number, int bitwidth) {
static int length = bitwidth;
int i, n;
if(bitwidth > 0) {
int_rec(number, bitwidth-1);
/* n := 10^(bitwidth-2) */
for(i=0,n=1;i<bitwidth-1;++i,n*=10);
int_rec(number + n, bitwidth-1);
}
else {
/* i := number of digit in 'number' */
for(i=1,n=number;n>=10;++i,n/=10);
/* print (length-i) zeros */
for(n=i; n<length; ++n) printf("0");
printf("%u\n", number);
}
}
usage :
int_rec(0, 4);
Tree Solution, recursive using char* buffer, no binary conversion
struct Node {
int val;
struct Node *left, *right;
};
void build_tree(struct Node* tree, int n) {
if(n > 0) {
tree->left = (Node*)malloc(sizeof(Node));
tree->right= (Node*)malloc(sizeof(Node));
tree->left->val = 0;
build_tree(tree->left, n - 1);
tree->right->val = 1;
build_tree(tree->right, n - 1);
}
else {
tree->left = tree->right = NULL;
}
}
void print_tree(struct Node* tree, char* buffer, int index) {
if(tree->left != NULL && tree->right != NULL) {
sprintf(buffer+index, "%u", tree->val);
print_tree(tree->left, buffer, index+1);
sprintf(buffer+index, "%u", tree->val);
print_tree(tree->right, buffer, index+1);
}
else {
printf("%s%u\n", buffer, tree->val);
}
}
usage :
char buffer[5] = {0};
Node* tree = (Node*)malloc(sizeof(Node));
tree->val = 0;
build_tree(tree, 4);
print_tree(tree, buffer, 0);
But this would print an additional 0 at the begining of each line, to avoid this, build two smaller trees :
Node* tree0 = (Node*)malloc(sizeof(Node));
Node* tree1 = (Node*)malloc(sizeof(Node));
tree0->val = 0;
tree1->val = 1;
build_tree(tree0, 3);
build_tree(tree1, 3);
print_tree(tree0, buffer, 0);
print_tree(tree1, buffer, 0);
Recursive solution using int* array
#define MAX_LENGTH 32
int number[MAX_LENGTH];
void int_buffer_rec(int n, int length) {
if(n > 0) {
number[length - n] = 0;
int_buffer_rec(n - 1, length);
number[length - n] = 1;
int_buffer_rec(n - 1, length);
}
else {
for(int i = 0; i < length; ++i) {
printf("%u", number[i]);
}
printf("\n");
}
}
usage :
int_buffer_rec(4, 4);
the recursion could be done with +1
void f(unsigned int x)
{
printf("%u%u%u%u\n",
(x>>3)&0x1,
(x>>2)&0x1,
(x>>1)&0x1,
x&0x1);
if(x==0xF) return;
else f(x+1);
}
int main(void)
{
f(0);
}
Execution:
$ ./test
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
just traverse DFS a binary tree of depth 4, going left is 0, going right is 1.
tr(int dep, int val)
{
if(dep == 4)
{
printf("\n");
}
else
{
printf("%d", val);
tr(dep+1, 0); // going left
tr(dep+1, 1); // going right
}
return;
}
int main()
{
tr(0,0);
}
I tried to limit my solution using to the same arguments but I would definitively add an extra argument to know the initial value of count.
void rec(int val, int count) {
if (count <= 1) {
int i;
int f = 0;
for (i = sizeof(int) * 8; i >= 0; i--) {
f |= (val >> i) & 1;
if (f) {
printf("%d", (val >> i) & 1);
}
}
printf("\n");
} else {
rec(val * 2, count - 1);
rec(val * 2 + 1, count - 1);
}
}
Output:
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
In order to add the leading 0, I added an argument :
#include <stdio.h>
void rec2(int val, int count, int b) {
if (count <= 1) {
int i;
for (i = b - 1; i >= 0; i--) {
printf("%d", (val >> i) & 1);
}
printf("\n");
} else {
rec2(val * 2, count - 1, b);
rec2(val * 2 + 1, count - 1, b);
}
}
void rec(int val, int count) {
rec2(val, count, count);
}
int main() {
rec(0, 4);
rec(1, 4);
return 0;
}
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
Let us start by designing the prototype of the recursive function. Hopefully, it'll make sense from there. Take a look at a non-recursive version of this code, and you'll need the same variables. You don't need to pass any of them as arguments, but I'd prefer to pass them all, and make the solution as flexible and modular as possible. Consider the return value, too. That should probably indicate some sort of success, in order to mimic consistency with the C standard library.
int count_r(char *destination, /* The storage for the function to store *
* the 0s and 1s as we count. */
size_t length, /* The number of digits in the number. */
char *digit); /* The set of digits */
Now let us focus on designing the first iteration. Like in primary school, we start by defining our count_r to iterate only single digits at a time. Once we can prove that it knows how to count from 0 to 9, we introduce it to double digits... but for now, one step at a time.
Let us assume destination is initialised to contain length bytes of digits[0], prior to the first call. This initialisation is done by the caller, and the caller would presumably output that pre-initialised array before calling. The first iteration should modify only one byte: The one indicated by length, and then return to the caller.
int count_r(char *destination, size_t length, char *digit) {
/* The position of the right-most digit is before the '\0' in destination, *
* so we need to decrement length */
length--;
/* Find the digit at the very end of destination, within our "digit" parameter */
char *d = strchr(digit, destination[length]);
/* d[1] points to the next digit (or '\0') */
destination[length] = d[1];
return 0;
}
The caller then presumably prints the array, and calls count_r again with the same buffer to increment the counter. This works with different bases, and by reversing the digit string we can decrement instead of incrementing. However, as we'll soon see, it fails after it reaches the highest number it can count to: 'F' in the example below.
int main(void) {
char num[] = "0";
do {
puts(num);
} while (count_r(num, strlen(num), "0123456789ABCDEF") == 0);
}
When the time comes for counting higher, d[1] will be '\0' as it will have iterated beyond the set of digits and into the null terminator for the string. Let us consider adding code to handle our second iteration.
A bit of code is needed to set destination[length] back to the first digit and recursively move left onto the next digit. This occurs when d[1] == '\0', so we can write an if (...) { ... } branch to handle that.
There is a problem when length is passed in as 0, which we would discover after implementing the change mentioned just now. Here is where the function should return 1 to indicating that counting has finished, because it has moved as far left as possible and reached the highest number possible.
void count_r(char *destination, size_t length, char *digit) {
/* The position of the right-most digit is before the '\0' in destination, *
* so we need to decrement length */
if (length-- == 0) { return 1; }
/* Find the digit at the very end of destination, within our "digit" parameter */
char *d = strchr(digit, destination[length]);
/* d[1] points to the next digit (or '\0') */
if (d[1] == '\0') {
/* Set destination[length] to the first digit */
destination[length] = digit[0];
/* Recurse onto the next digit. We've already decremented length */
return count_r(destination, length, digit);
}
destination[length] = d[1];
return 0;
}
After adding a few assertions (eg. assert(strlen(digit) > 1);) and writing some testcases, we might then decide that this function is ready for production. I hope I was able to help. :)
Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C and C++ , this takes the form of a function that calls itself.
#include<iostream>
#include<cstdio>
using namespace std;
void rec(int val)
{
if(val<16)
{
printf("%u%u%u%u", val>>3, (val&4)>>2, (val&2)>>1, val&1);
printf("\n");
rec(++val); //calling val+1 here
}
return;
}
int main()
{
rec(0); //calling recursion for 0
}
This gives you exact output you want..!
If you don't want to use bit shift operators ..
#include<iostream>
#include<cstdio>
using namespace std;
void rec(int val)
{
if(val<16)
{
for(int b=val,a=8,i=0;i<4;b%=a,a/=2,i++)
printf("%u",(b/a));
printf("\n");
rec(++val);// calling val+1 here
}
return;
}
int main()
{
rec(0);//calling recursion for 0
}
This problem can be generalized to obtain binary combination of any length by using recursion. For example, if you want to get all binary combinations of length=4, just call printBinaryCombination("????", 0) (i.e. four ?s need to replaced with 0 or 1).
The corresponding code is as follows:
void printBinaryCombination(string str, int current)
{
int length = str.length();
if (length == 0)
return;
if (current == length)
printf("%s\n", str.c_str());
else
{
if (str[current] == '?')
{
str[current] = '0';
printBinaryCombination(str, current+1);
str[current] = '1';
printBinaryCombination(str, current+1);
// change back for next time
str[current] = '?';
}
else
printBinaryCombination(str, current+1);
}
}
EDIT: Actually, the above function is also powerful to handle all binary combinations that contains random number of ?s, each of which can be 0 or 1. For example, if you call printBinaryCombination("1??0", 0), it will print:
1000
1010
1100
1110
To generate n bit combination you asked for(you asked for n=4)
general recursive implementation for any n would be:
Main function:
vector<string> ve,ve1;
int main(int argc, char const *argv[])
{
/* code */
int n;
cin>>n;
generate("0",n,true);
generate("1",n,false);
for(int i=0;i<ve.size();i++){
cout<<ve[i]<<endl;
}
for(int i=0;i<ve1.size();i++){
cout<<ve1[i]<<endl;
}
return 0;
}
Generate function which recursively generates the binary strings:
void generate(string s,int n,bool b){
if(n==1){
if(b==true){
ve.push_back(s);
}
else{
ve1.push_back(s);
}
return;
}else{
generate(s+"0",n-1,b);
generate(s+"1",n-1,b);
}
}
Hope this helps..
SOLN 1: a more generalized answer(compilable under c90, c99). booleans being output as int.
Limitations :
1) uses math library.(its heavier so).
#include<stdio.h>
#include<math.h>
#define MAXBITS 4
//#define MAXVALUES (((int)pow(2,maxb))-1)
const int MAXVALUES = (((int)pow(2,maxb))-1) //if this gives warning then use #define version.
void bin(int val,int total)
{
int i = 0;
if(val <= MAXVALUES) //can write pow(2,total-1)-1 but anyways..
{
for(i =0 ; i < total;i++)
{
printf("%d",!!(val&(int)pow(2,total-i-1)));
}
printf("\n");
}
else return;
bin(val+1,total);
}
int main()
{
setbuf(stdout,NULL);
bin(0,MAXBITS);//4 bits
return 0;
}
Soln 2 :This can be done by char printing. no shift operator.
limitation(s) :
1) it can print(correctly) only upto 15(dec) or 0x0F(hex) values.
2) a total of
(5 * sizeof(char) * total) + (( total + 2) * (sizeof(int) + sizeof(int))) created on stack(so wasteful).
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXVALUES 15
#define MAXBITS 4
void bin(int val,int total) //#prototype void bin(int val);remove redundant total.
{
char *s = malloc(sizeof(char)*(total+1)); //cant declare variable array(atleast pre c99)
int i = 0;
if(val <= MAXVALUES )
{
for(i =0 ; i < total;i++)
{
s[total - i-1] = !!(val&(int)pow(2,i)) + '0';
}
s[total] = '\0';
printf("%s\n",s);
}
else return;
bin(val+1,total);
}
int main()
{
bin(0,MAXBITS);//4 bits
return 0;
}
This general purpose c++ code works for any number of bits. just change const int num to any number of bits you want to generate binary code of...
const int num=3;
string code="";
void GenerateBinaryCode(string str,unsigned int n){
if(n==0){
cout<<str<<endl;
}
else{
str[num-n]='0';
GenerateBinaryCode(str, n-1);
str[num-n]='1';
GenerateBinaryCode(str, n-1);
}
}
int main(){
for(int i=0; i<num; i++)
code+="x";
GenerateBinaryCode(code,num);
}
Here's a recursive implementation in C using only an int 2D array (no strings, chars or bitshifting) for arbitrary bit lengths.
static void btable(int* a, int i, int n, int k, size_t len) {
if (k >= len)
return;
for (int j = (i+n)/2; j < n; j++)
*(a+j*len+k) = 1;
btable(a,i,(i+n)/2,k+1,len);
btable(a,(i+n)/2,n,k+1,len);
}
Then you can call the function with
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void) {
int n = 4;
int (*a)[n] = malloc(sizeof(int[(int)pow(2,n)][n]));
btable(*a,0,pow(2,n),0,n);
for (int i = 0; i < pow(2,n); i++) { // verify output
for (int j = 0; j < n; j++)
printf("%d",a[i][j]);
printf("\n");
}
return 0;
}
Before to present the final solution, I'll show two functions that we can use for our goal.
The main idea of the next function is to add the elements of the l1 list to each list that is contained in l2. For example:
l1 = [0]
l2 = [ [1,1] , [1,0] ]
then
f1(l1,l2) = [ [0,1,1] ,[0,1,0]]
def f1(l1:List[Int],l2:List[List[Int]]): List[List[Int]] = l2.map{ r=> l1:::r}
The first parameter is a list that contains a list of integers that will be added to each list of numbers contained in the l2 list. For example:
l1 = [ [0] , [1]]
l2 = [ [1,0], [1,1] ]
f(l1,l2) = [ [0,1,0],[0,1,1], [1,1,0],[1,1,1] ]
def f(l1:List[List[Int]],l2:List[List[Int]]): List[List[Int]] = l1.map{ r=> f1(r,l2)} flatten
Now, that we have the auxiliary methods, we create the function that will solve the requirement
/**
n : The max number of digits that the binary number can contain
*/
def binaryNumbers(n:Int):List[List[Int]] = n match {
case 1 => List(List(0),List(1))
case _ => f( List(List(0),List(1)) , binaryNumbers(n-1) )
}
Example: binaryNumbers(2) = List( List(0,0), List(0,1), List(1,0), List(1,1) )

Resources