I need to iterate over an array of n elements (dynamic size thus), for example 4, as if it were a binary number, starting with all zeros ({0,0,0,0}). Every time this needs to increment as if it is binary, {0,0,0,0} -> {0,0,0,1} -> {0,0,1,0} -> {0,0,1,1} -> {0,1,0,0}, etc...
I have trouble generating an algorithm that does so with array values, I thought about using recursion but cannot find the method to do so other than hard-coding in ifs. I suppose I could generate an n-digit number and then apply any algorithm discussed in this post, but that would be inelegant; the OP asked to print n-digit numbers while I need to work with arrays.
It would be great if someone could point me in the right direction.
Context:
int n;
scans("%d", &n);
int *arr = calloc(n, sizeof(int));
Algorithm:
Start at the rightmost element.
If it's a zero, then set it to one and exit
It must be a one; set it to zero
If you are at the left-most element, then exit.
You aren't already at the left-most element; move left one element and repeat.
I'm sorry, I'm not in a position to provide a code sample.
Algorithm:
Start at the rightmost element.
If it's a zero, then set it to one and exit
It must be a one; set it to zero
If you are at the left-most element, then exit.
You aren't already at the left-most element; move left one element and repeat.
Here's Hymie's algorithm, I'll try making a code out of it :
#include <stdlib.h>
#include <stdio.h>
int my_algo(int *arr, int size) {
for (int i = size - 1; i >= 0; i--) { // Start at the rightmost element
if (arr[i] == 0) { // If it's a zero, then set it to one and exit
arr[i] = 1;
return 1;
} else if (arr[i] == 1) { // If it's a one, set it to zero and continue
arr[i] = 0;
}
}
return 0; // stop the algo if you're at the left-most element
}
int main() {
int n;
scanf("%d", &n);
int *arr = calloc(n, sizeof(int));
do {
for (int i = 0; i < n; i++) {
putchar(arr[i] + '0');
}
putchar('\n');
} while (my_algo(arr, n));
return (0);
}
This algorithm is dynamic and work with scanf.
Here's the result for 4 :
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
What you seem to want to do is implement binary addition (or more precisely a binary counter), which is anyway implemented in the CPU's digital circuit using logic gates. It can be done using combination of logical operations (nand and xor to be exact).
But the most elegant approach according to my sense of elegance would be to use the CPU's innate ability to increment numbers and write a function to decompose a number to a bit array:
void generate_bit_array(unsigned int value, uint8_t *bit_array, unsigned int bit_count) {
for (unsigned int i=0; i<bit_count; i++) {
bit_array[i] = value >> (bit_count - i - 1) & 0x01;
}
}
int main(int argc, void **argv) {
unsigned int i;
uint8_t my_array[4];
/* Iterate and regenerate array's content */
for (i=0; i<4; i++) {
generate_bit_array(i, my_array, 4);
/* Do something */
}
return 0;
}
You can do:
#include <stdio.h>
#include <stdlib.h>
void gen_bit_array(int *numarr, int n, int arr_size) {
if(n > 0) {
numarr[arr_size-n] = 0;
gen_bit_array(numarr, n-1, arr_size);
numarr[arr_size-n] = 1;
gen_bit_array(numarr, n-1, arr_size);
} else {
int i;
for(i=0; i<arr_size; i++)
printf("%d", numarr[i]);
printf ("\n");
}
}
int main() {
int n,i;
printf ("Enter array size:\n");
scanf("%d", &n);
int *numarr = calloc(n, sizeof(int));
if (numarr == NULL)
return -1;
gen_bit_array(numarr, n, n);
return 0;
}
Output:
Enter array size:
2
00
01
10
11
Enter array size:
4
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
If I have understood you correctly then what you need is something like the following
#include <stdio.h>
#define N 4
void next_value( unsigned int a[], size_t n )
{
unsigned int overflow = 1;
for ( size_t i = n; i != 0 && overflow; i-- )
{
overflow = ( a[i-1] ^= overflow ) == 0;
}
}
int empty( const unsigned int a[], size_t n )
{
while ( n && a[n-1] == 0 ) --n;
return n == 0;
}
int main(void)
{
unsigned int a[N] = { 0 };
do
{
for ( size_t i = 0; i < N; i++ ) printf( "%i ", a[i] );
putchar( '\n' );
next_value( a, N );
} while ( !empty( a, N ) );
return 0;
}
The program output is
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
Or you can write the function that evaluates a next value such a way that if the next value is equal to 0 then the function returns 0.
For example
#include <stdio.h>
#include <stdlib.h>
int next_value( unsigned int a[], size_t n )
{
unsigned int overflow = 1;
for ( ; n != 0 && overflow; n-- )
{
overflow = ( a[n-1] ^= overflow ) == 0;
}
return overflow == 0;
}
int main(void)
{
size_t n;
printf( "Enter the length of the binary number: " );
if ( scanf( "%zu", &n ) != 1 ) n = 0;
unsigned int *a = calloc( n, sizeof( unsigned int ) );
do
{
for ( size_t i = 0; i < n; i++ ) printf( "%i ", a[i] );
putchar( '\n' );
} while ( next_value( a, n ) );
free( a );
return 0;
}
The program output might look like
Enter the length of the binary number: 3
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
No need for an algorithm, you could build a function,
Here is a process which could be a good idea if the array is of a fixed size :
Build a function which take your array
Create a local integrer for this function
Set the bits value of the integrer to the cells value of the array
Increment the integrer
Set the array values to match each bits of the integrer
All this process can be done using shifts (>> <<) and masks (& 255 for example).
Related
I have an array called int arr[10] = {1,2,3,4,5}
From my understanding the rest of the array is filled with 0's.
My questions is if its a fixed array length how can I put the first index behind the last index that is not a 0. For example
I believe the 0 is not shown in real printf but I am including it for illustration purposes
for (int i = 0 ; i < 10 ; i++)
{
print("%i" , arr[i]);
}
The output
1 2 3 4 5 0 0 0 0 0
If i move the first index to the back of the 5 like so
for (int i = -1 ; i < 10 ; i++)
{
arr[i] = arr[i + 1];
print("%i" , arr[i]);
}
Will the output put the 1 behind the 5 or at the back of the whole array?
2 3 4 5 1 0 0 0 0 0
or because there is 0s then
2 3 4 5 0 0 0 0 0 1
If my question is unclear please tell me and I will try explain it.
The output
1 2 3 4 5 0 0 0 0 0
No, the actual output is
1234500000
Your code has undefined behavior. The first iteration of the loop (with i = -1) tries to assign to arr[-1], which does not exist:
arr[i] = arr[i + 1];
Similarly, the last iteration (with i = 9) tries to read from arr[10], which also does not exist.
I'm not sure why you think your code will move the first element back.
From my understanding the rest of the array is filled with 0's
You are right.:)
If i move the first index to the back of the 5 like so
for (int i = -1 ; i < 10 ; i++)
{
arr[i] = arr[i + 1];
print("%i" , arr[i]);
}
then you will get undefined behavior because the indices -1 and 10 are not valid indices.
It seems what you are trying to do is the following
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { N = 10 };
int a[N] = { 1, 2, 3, 4, 5 };
size_t pos = 0;
while ( pos < N && a[pos] != 0 ) ++pos;
if ( pos != N && !( pos < 3 ) )
{
int tmp = a[0];
pos -= 2;
memmove( a, a + 1, pos * sizeof( int ) );
a[pos] = tmp;
}
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
return 0;
}
The program output is
2 3 4 1 5 0 0 0 0 0
Lets say combinationlength=4.
My logic is create the array {0,0,0,0} add 1 to the last element until first element gets the value 1.Until then if with the addition of 1 the array[3] ends up in a 2 result then make it 0 and then traverse the array(reversed) given a counter variable and every first non 1 element make it 0 while making all elements before the value that first non 1 equal to 0.This is for 8 repetitions.How close am i?Can someone help me finish this?
Also this doesnt run for some reason.Nothing gets printed and ends after 2 seconds.
I just noticed i am skipping a step but anyways.
I want in every iteration to have an array like the sequence.And not added printf("0"); and shortcuts like that.
void print(int combinationlength){
int i,j,count;
int a=combinationlength-1;
int c=combinationlength-1;
int b;
int array[4]={0};
while(array[0]!=1){
array[a]++;
if(array[a]==2){
array[a]=0;
for(b=a;b<=c-1;b--){
if(array[b]==0)
array[b]=1;
}
c--;
}
for(count=0;count<combinationlength;count++){
printf("%d",array[count]);
}
printf("\n");
}
return 0;
}
UPDATED:(also updated my explanation above this ^^ block of code)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i,j,count;
int a=4-1;
int c=4-1;
int b;
int array[4]={0};
while(array[0]!=1){
array[a]++;
if(array[a]==2){
array[a]=0;
for(b=a-1;b>c-1;b--){
if(array[b]==0) array[b]=1;
else array[b]=0;
}
c--;
}
for(count=0;count<4;count++){
printf("%d",array[count]);
}
printf("\n");
}
return 0;
}
The hardcoded number 4 is supposed to be the input variable.
So, I'm still not entirely sure I understand what you want. If I understood correctly, you want every combination of bits (i.e. zeros and ones) of a certain length. Doing the additions manually in an array feels very wasteful, so lets instead use what the CPU already has to offer - integer addition.
An example program, printing all the combinations of a certain length would look something like this:
#include <stdio.h>
void print(int len){
for (unsigned long sortOfAnArray = 0; sortOfAnArray < (1U << len); sortOfAnArray++) {
for (int i = len - 1; i >= 0; i--) {
printf("%lu", (sortOfAnArray >> i) & 1);
}
printf("\n");
}
}
int main(void) {
print(5);
return 0;
}
To explain the steps, sortOfAnArray is our integer, stored in binary, we add 1 to it on every iteration so that we get the different combinations.
In order to print it, we have to access elements individually, we do this with a combination of a bitshift and logical and (sortOfAnArray >> i) & 1. So, we shift the bits in the array by i to the right, and check if it has a 1 on the first position, in other words, we checked if sortOfAnArray[i]==1 (if this was an array).
We use unsigned due to the standard and long in case you want up to 64 bits available (although long long would be even safer there).
EDIT
To further explain how we extract a bit from the integer.
Assume we have the integer
`unsigned long long foo = 27`
if we look at the bit representation of that, we get 00...011011, where the total number of bits is 64, but there's just a lot of zeros, hence the dots. Now, say we want to know the value of the 1st bit from the right. We can find that out by using the logical and operation
`foo & 1`
This will apply the logical and to every pair of bits at the same position in the two integers (foo and 1), in this case this will give us 1:
foo -- 00...011011
1 -- 00...000001
foo & 1 -- 00...000001
If foo had 0 as the rightmost bit, the result would instead be 0, so this essentially allows us to read whether the first bit is set to 0 or 1.
How do we generalise this to the other bits?
We have two options, we can either move the bit in the 1 (1 << n shifts the 1 bit n moves to the left), if we use the logical and then, we will get 0 if foo has a 0 in the n-th position or some nonzero value (2^n) if it has a 1.
The other option is to instead shift the bits of foo to the right, the upside of doing this is if foo had a 1 in the n-th position, the result will now be 1 rather than 2^n, whereas if it was 0 the result is still 0. Other than that the two approaches are equivalent.
This is how we come up with the final solution, that is, to access the n-th element (0-based counting) as follows:
(foo >> n) & 1
we move the bits of foo to the right by n and look if the first bit is set to 0 or 1. Essentially, the integer is storing 64 bits (we don't need to use all of them, of course) the same way we would do that in an array, but the approach is much more efficient. Among other things, we don't need to implement our own addition for the array, as you had attempted initially.
Your problem statement is confusing:
if with the addition of 1 the array[3] ends up in a 2 result then make it 0 and then traverse the array(reversed) given a counter variable and every first non 1 element make it 0 while making all elements before the value that first non 1 equal to 0.
This basically means you want the first 0 element to remain 0 while making all elements before that first 0 set to 0.
As a consequence, the array contents would alternate between { 0, 0, 0, 0 } and { 0, 0, 0, 1 }, which is probably not the intent.
Let's assume your problem is to simulate a base-2 counter with 4 binary digits and you count from 0 to 8. Your code is a bit too complicated (pun intended ;-). You should simplify and use fewer index variables:
#include <stdio.h>
int main() {
int i;
int array[4] = { 0 };
while (array[0] != 1) {
for (i = 0; i < 4; i++) {
printf("%d ", array[i]);
}
printf("\n");
for (i = 4; i-- > 0; ) {
array[i] += 1;
if (array[i] == 2) {
array[i] = 0;
} else {
break;
}
}
}
return 0;
}
Output:
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
Note how you can write a for loop that counts down from the length of the array, enumerating all valid index values while using the exact length of the array and using a test i-- > 0 that is correct for both signed and unsigned types. This trick is sometimes referred to as the downto operator, not a real operator but one can make it look like one as i --> 0.
EDIT: to print the complete set of binary combinations, keep looping until i is -1:
#include <stdio.h>
int main() {
int i;
int array[4] = { 0 };
for (;;) {
for (i = 0; i < 4; i++) {
printf("%d ", array[i]);
}
printf("\n");
for (i = 4; i-- > 0; ) {
array[i] += 1;
if (array[i] == 2) {
array[i] = 0;
} else {
break;
}
}
if (i < 0) {
/* the array is too small, all combinations exhausted */
break;
}
}
return 0;
}
An integer already consists (most of the time) of 4 bytes = 32 bits. You can use a simple integer instead of an array.
However printing an integer in binary format is a bit tricky, I used the answer of this question to do it.
#include <stdio.h>
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
int main(void) {
int a = 0;
int limit = 4;
while( (a & (1 << limit)) == 0)
{
printf("0b"BYTE_TO_BINARY_PATTERN"\n", BYTE_TO_BINARY(a));
a++;
}
return 0;
}
Output:
0b00000000
0b00000001
0b00000010
0b00000011
0b00000100
0b00000101
0b00000110
0b00000111
0b00001000
0b00001001
0b00001010
0b00001011
0b00001100
0b00001101
0b00001110
0b00001111
Little explanation:
In the while loop I use a so called bit mask. (1 << limit) results in a binary 1 at the position limit, so in this case it would be 0b00010000. With the binary & I check if a has that bit, if yes the while loop ends.
Whenever I have to do something involving iteration over combinations, I automatically think of Grey Codes / reverse binary coding. Below is my own implementation (it uses a different formula than the wiki, but still covers all the values). Note they won't be in order, but it does cover all combinations 0->2^n-1 and it is very fast since it only needs to change one value each time.
#include <stdio.h>
int main(int argc, char** argv) {
unsigned int length = 4;
unsigned int array[4] = {0, 0, 0, 0};
int i, j;
for (i = 0; i < 1 << length; i++) {
array[__builtin_ctz(i)] ^= 1;
printf("Array Values: ");
for (j = 0; j < length; j++) {
printf("%d ", array[j]);
}
printf("\n");
}
return 0;
}
Output:
Array Values: 0 0 0 0
Array Values: 1 0 0 0
Array Values: 1 1 0 0
Array Values: 0 1 0 0
Array Values: 0 1 1 0
Array Values: 1 1 1 0
Array Values: 1 0 1 0
Array Values: 0 0 1 0
Array Values: 0 0 1 1
Array Values: 1 0 1 1
Array Values: 1 1 1 1
Array Values: 0 1 1 1
Array Values: 0 1 0 1
Array Values: 1 1 0 1
Array Values: 1 0 0 1
Array Values: 0 0 0 1
Note I use the __builtin_ctz() method to count trailing zeros quickly. I don't know if its implemented on any other compilers, but GCC supports it.
I have some dificulties in creating the following array. My task is to fill using recursion a 2D array with all the possible combinations of 0 and 1 taken m times in lexical order. Mathematically speaking there are 2 ^ m combinations.My program just fills the first 3 rows of the array with the same order 0 1 0 1 and then just prints for the rest of the rows 0 0 0 0.
Example
m=4
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
This is my code so far and I appreciate if someone could correct it and explain me what I am doing wrong as I can't spot the mistake myself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void combine(int** arrTF,int m,int n,int row,int col){
if(m==0){
if(row<pow(2,m)){
row++;
combine(arrTF,n,n,row,0);
}else{
return;
}
}else{
arrTF[row][col]=0;
col++;
combine(arrTF,m-1,n,row,col);
arrTF[row][col]=1;
col++;
combine(arrTF,m-1,n,row,col);
}
}
int main(int argc, char *argv[]) {
int m
scanf("%d",&m);
int** arrTF;
arrTF = safeMalloc(pow(2,m)*sizeof(int *));
for (int r=0; r < pow(2,m); r++) {
arrTF[r] = safeMalloc(m*sizeof(int));
}
for(int i=0;i<pow(2,m);i++){
for(int j=0;j<m;j++){
arrTF[i][j]=0;
}
}
combine(arrTF,m,m,0,0);
for(int i=0;i<pow(2,m);i++){
for(int j=0;j<m;j++){
printf("%d ",arrTF[i][j]);
}
printf("\n");
}
return 0;
}
You want all the possible (2^m) combinations of 0's and 1's taken m times in lexical order and you are using a 2D array to store the result.
Things would be very easy if you just want to print all the possible combination of 0's and 1's instead of storing it in 2D array and printing array later.
Storing a combination of 0's and 1's to 2D array is a little bit tricky as every combination is one element of your 2D array.
You want to generate the combination of 0's and 1's in accordance with the recursive algorithm.
So, let's say, at some stage if your algorithm generates the combination 0010 which is stored in an element in 2D array.
And the next combination would be 0011 which the recursive algorithm will generate just by changing the last number from 0 to 1 in the last combination (0010).
So, that means everytime when a combination is generated, you need to copy that combination to its successive location in 2D array.
For e.g. if 0010 is stored at index 2 in 2D array before the algorithm starts computing the next combination, we need to do two things:
Copy the elements of index 2 to index 3
Increase the row number so that last combination will be intact
(Say, this is 2D array)
|0|0|0|0| index 0
|0|0|0|1| index 1
|0|0|1|0| index 2 ---> copy this to its successive location (i.e. at index 3)
|0|0|1|1| index 3 ---> Last combination (index 2) and the last digit is changed from 0 to 1
.....
.....
.....
This we need to do for after every combination generated.
Now, I hope you got where you are making the mistake.
Few practice good to follow:
If you want to allocate memory as well as initialized it with 0, use calloc instead of malloc.
Any math function you are calling again and again for the same input, it's better to call it once and store the result in a variable and use that result where ever required.
Do not include any header file which is not required in your program.
Once done, make sure to free the dynamically allocated memory in your program.
I have made the corrections in your program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void *safeMalloc(size_t n, size_t size) {
void *p = calloc(n, size);
if (p == NULL) {
printf("Error: calloc(%zu) failed. Out of memory!\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void deallocate(int ** ptr, int row) {
for(int i = 0; i<row; i++)
free(ptr[i]);
free(ptr);
}
void combine(int **arrTF, int m, int max_col, int max_row) {
static int row;
if(m==0){
int i;
if (row<(max_row - 1))
{
for(i=0; i<max_col; i++)
arrTF[row+1][i] = arrTF[row][i];
}
row++;
return;
} else {
arrTF[row][max_col-m] = 0;
combine(arrTF, m-1, max_col, max_row);
arrTF[row][max_col-m] = 1;
combine(arrTF, m-1, max_col, max_row);
}
}
int main(int argc, char *argv[]) {
int** arrTF;
int m, max_row;
printf ("Enter number: \n");
scanf("%d", &m);
max_row = pow(2, m);
arrTF = safeMalloc(max_row, sizeof(int *));
for (int r=0; r<max_row; r++) {
arrTF[r] = safeMalloc(m, sizeof(int));
}
combine(arrTF, m, m, max_row);
for(int i=0; i<max_row; i++) {
for(int j=0; j<m; j++) {
printf("%d ", arrTF[i][j]);
}
printf("\n");
}
deallocate(arrTF, max_row);
return 0;
}
Output:
$ ./a.out
Enter number:
2
0 0
0 1
1 0
1 1
$ ./a.out
4
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
Hope this helps.
I need to write a function that accepts the length of series(0 and 1) and the user writes the series. The function tells the place of the longest same sun-series.
Example:
The function gets length = 12, and the user writes: 1 0 0 1 1 1 1 0 0 0 1 1
The answer for this one is 4 because the longest combination (four consecutive 1's) starts at 4th place.
Another example:
The length is: 12 and the user inputs : 1 0 0 0 1 1 0 1 1 1 0 0
The answer for this one is 2 (three consecutive 0's starting at position 2—if there are multiple sub-series with same length it returns the first one).
This is what I tried to do:
int sameNumbers(int seriaLength)
{
int i;
int place=0;
int num1, num2;
int sameCount;
int maxSameCount = 0;
printf("Please enter the seria: \n");
scanf("%d",&num1);
for(i = 1; i < seriaLength; i++)
{
scanf("%d",&num2);
while(num1 == num2)
{
sameCount++;
}
if(sameCount > maxSameCount)
{
maxSameCount = sameCount;
place = i;
}
scanf("%d",&num1);
}
return place;
}
Edit:
I need to do this without arrays.
Thanks!!
This seems to do what you want. To understand the logic, see the comments in the code.
#include <stdio.h>
int sameNumbers(int seriaLength)
{
int i, num, previousNum, length = 0, maxLength = 0, start = 0, startOfLongest = 0;
printf( "Please enter the series: " );
for( i = 0; i < seriaLength; i++ )
{
scanf( "%d", &num );
if( i > 0 && num == previousNum ) length++;
else { length = 1; start = i; } // if the number is not the same as the previous number, record the start of a new sequence here
if( length > maxLength ) { maxLength = length; startOfLongest = start; } // if we've broken (not equalled) the previous record for longest sequence, record where it happened
previousNum = num;
}
return startOfLongest + 1; // add 1 because the OP seems to want the resulting index to be 1-based
}
int main( int argc, const char * argv[] )
{
printf( "%d\n", sameNumbers( 12 ) );
return 0;
}
this program is "calculating" all subsets of the array source. I need to store the resulting values in another 2D filed named polje. If I just use the printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); the code works fine but something fails when it is trying to copy everything into the resulting field. I suppose I am dogin something wrong in the indexing of the array polje.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int f;
int i,j;
int source[2][3] = {{0,3,5},{3,4,2}};
int currentSubset = 3;
int polje[8][3];
for(i=0;i<8;i++){
for(j=0;j<3;j++){
polje[i][j]=0;
}}
int tmp;
while(currentSubset)
{
tmp = currentSubset;
for( i = 0; i<3; i++)
{
if (tmp & 1)
{
printf("%d %d %d ", source[i][0], source[i][1], source[i][2]); //writes out everything I want
polje[currentSubset][0]=source[i][0];
polje[currentSubset][1]=source[i][1];
polje[currentSubset][2]=source[i][2];
}
tmp >>= 1;
}
printf("\n");
currentSubset--;
}
for(i=0;i<8;i++){
for(j=0;j<3;j++){
printf("%d ", polje[i][j]);
}printf("\n");}
return (EXIT_SUCCESS);
}
The output field should be:
0 3 5
3 4 2
3 4 2
0 0 0
0 3 5
0 0 0
0 0 0
0 0 0
But instead it is:
0 3 5
3 4 2
3 4 2
0 0 0
*0 0 0*
0 0 0
0 0 0
0 0 0
tmp is a bit mask with only two bits, so the inner loop should be for ( i = 0; i < 2; i++ ).
Also the correct index into the polje array is polje[currentSubset * 2 + i][0] since each subset in polje takes two spaces and i is either 0 or 1.
I think you just have a logic error. Your loop's skeleton is:
currentSubset = 3;
while ( currentSubset )
{
// ...
polje[currentSubset][...] = ...;
// ...
currentSubset--;
}
So you never write to any rows except the first three.