I need to write a program that iterates through all possible combinations for a base-2 (binary) vector. If the size of this vector is 3 you can do this with three nested loops, like this:
bool array[3];
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
{
array[0] = i;
array[1] = j;
array[2] = k;
}
}
}
But the problem is that in my application, the array size is variable and can basically be any number. If I'm looking to find all values of a 12-bit vector, I don't want to write 12 nested loops and so it is not maintainable to use the code above. Instead I have come up with the following solution:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define SIZE 12
int main(void)
{
bool array[SIZE];
for(int i = 0; i < SIZE; i++) array[i] = 1;
int max_num = pow(2, SIZE);
for(int i = 0; i < max_num; i++)
{
if(array[0] == 0) array[0]++;
else
{
array[0] = 0;
for(int j = 1; j < SIZE; j++)
{
if(array[j] == 1) array[j] = 0;
else
{
array[j] = 1;
break;
}
}
}
for(int j = 0; j < SIZE; j++)
{
printf("%d", array[j]);
if(j != SIZE - 1) printf(", ");
else printf("\n");
}
}
}
This still seems as a lot of code to me for such a relatively simple thing. My question is: is there a more efficient way to do this?
What you are doing with the array is effectively incrementing (adding one) to the number represented by the array.
Let's leave the incrementing to the compiler and use bits from the integer.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 12
int main(void)
{
bool array[SIZE];
int max_num = 1 << SIZE;
for(int i = 0; i < max_num; i++)
{
for(int j = 0; j < SIZE; j++)
{
array[j] = (i >> j) & 1;
}
for(int j = 0; j < SIZE; j++)
{
printf("%d", array[j]);
if(j != SIZE - 1) printf(", ");
else printf("\n");
}
}
}
As pointed out by others, it is essentially incrementing a binary number. However, in keeping with the spirit of the original code, I decided not to "cheat" by using native addition/increment operators to increment the vector, and came up with the following:
#include <stddef.h>
#include <stdbool.h>
bool first(size_t size, bool array[size])
{
size_t i;
for (i = 0; i < size; i++)
{
array[i] = 0;
}
return i > 0;
}
bool next(size_t size, bool array[size])
{
size_t i;
for (i = 0; i < size && array[i]; i++)
{
array[i] = 0;
}
if (i < size)
{
array[i] = 1;
return 1;
}
return 0;
}
#include <stdio.h>
int main(void)
{
enum { SIZE = 12 };
bool array[SIZE];
bool going;
for (going = first(SIZE, array); going; going = next(SIZE, array))
{
size_t i;
for (i = 0; i < SIZE - 1; i++)
{
printf("%d, ", array[i]);
}
printf("%d\n", array[i]);
}
return 0;
}
It could be adapted to work in other bases easily:
#include <stddef.h>
#include <stdbool.h>
bool first(size_t size, unsigned int array[size])
{
size_t i;
for (i = 0; i < size; i++)
{
array[i] = 0;
}
return i > 0;
}
bool next(size_t size, unsigned int array[size], unsigned int base)
{
size_t i;
for (i = 0; i < size && array[i] == base - 1; i++)
{
array[i] = 0;
}
if (i < size)
{
array[i]++;
return 1;
}
return 0;
}
#include <stdio.h>
int main(void)
{
enum { SIZE = 5 };
enum { BASE = 3 };
unsigned int array[SIZE];
bool going;
for (going = first(SIZE, array); going; going = next(SIZE, array, BASE))
{
size_t i;
for (i = 0; i < SIZE - 1; i++)
{
printf("%u, ", array[i]);
}
printf("%u\n", array[i]);
}
return 0;
}
Related
I want to create an array of 100 size, which its elements are unique random integers from 1 to 999999. My code doesn't give any error message or the output that I want. What is wrong with this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
#define EMPTY -1
int main() {
srand(time(NULL));
int list[999999], A[N], i;
for (i = 0; i < N; i++)
A[i] = EMPTY;
for (i = 0; i < 999999; i++) {
list[i] = i + 1;
}
for (i = 0; i < 999999; i++) {
int j = rand() % 999999;
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
for (i = 0; i < N; i++) {
A[i] = list[i];
}
for (i = 0; i < N; i++) {
printf("%i\n", A[i]);
}
}
The initial loop is useless, the method is very inefficient, but the output should meet the goal...
Yet there might be an issue with the list array: it is very large and defining it as a local variable with automatic storage cause a stack overflow, depending on your target system. Try defining is as:
static int list[999999];
Here is an alternative for N small compared to 1000000:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
int main() {
int A[N], i, j;
srand(time(NULL));
for (i = 0; i < N;) {
int n = 1 + rand() % 999999;
for (j = 0; j < i; j++) {
if (A[j] == n)
break;
}
if (i == j)
A[i++] = n;
}
for (i = 0; i < N; i++) {
printf("%i\n", A[i]);
}
return 0;
}
Insert in a vector B, from its beginning, the even numbers of vector A and, from its end, the
odd numbers of vector A (this item must be solved with only a single structure of
repetition);
i don't know the conditions i have tu put in do while loop
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int i, j, A[25], B[25], testeNumeroIgual = 0, aux;
srand(time(NULL));
i = 0;
do {
A[i] = rand() % 40;
testeNumeroIgual = 0;
for (j = 0; j < i; j++) {
if (A[j] == A[i]) {
testeNumeroIgual = 1;
}
}
if (testeNumeroIgual == 0)
i++;
} while(i < 25);
i = 0;
do {
if (A[i] % 2 == 0) {
B[i] = A[i];
}
else {
B[25 - i] = A[i];
}
i++;
} while(i < 25);
for (i = 0; i < 25; i++) {
printf("%d\n", B[i]);
}
return 0;
}
Generate the random number into a specific loop to isolate the algorithm.
Then use two indexes tail and head to put it on the right place.
Increase head and decrease tail when you insert.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SIZE 25
int main()
{
int i, A[SIZE], B[SIZE], tail, head ;
srand(time(NULL));
/* generate random number for A */
for (i = 0; i < SIZE; i++) {
A[i] = rand() % 40;
}
tail = SIZE - 1;
head = 0;
for (i = 0; i < SIZE; i++) {
if (A[i] % 2) {
B[tail--] = A[i];
} else {
B[head++] = A[i];
}
}
printf("A: \n");
for (i = 0; i < SIZE; i++) {
printf("%d %d\n",i, A[i]);
}
printf("\nB: \n");
for (i = 0; i < SIZE; i++) {
printf("%i %d\n", i, B[i]);
}
return 0;
}
How do I get to write to 2D pointers where I have pnumber[2%4][2%4] and how can I get pnumber with more than 3 ciphers to be displayed?
I'm making a program to write pascals triangle in C.
When the pointer pnumbers[i][j] have both i and j = 2 mod 4, except for when i and j = 2, then my program won't write to the address and give the error message:
pascals triangle: malloc.c:2406: sysmalloc: Assertion '{old_top == initial_top (av) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =7;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
/*
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
*/
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
When I avoid writing to these addresses and just print them out I get some seemingly random integer at these memory addresses.
Also when avoid these addresses and just print out so many rows that I get some spots with a higher integer with more than 3 siphers, it seems to overflow - and I don't see the logic behind it.
The result of running the second code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int factorial(int p) {
if (p>=1) {
return p*factorial(p-1);
}
else {
return 1;
}
}
int NchooseM(int n, int m) {
return factorial(n)/(factorial(n-m)*factorial(m));
}
int main() {
int n =20;
int x = n-2;
int i, j, k;
/*
printf("How many rows of Pascals triangle do you want to write?\n");
scanf("%d", &n);
*/
int **pnumbers;
pnumbers = (int **) malloc(n *sizeof(int *));
/* Allocate memory for storing the individual elements in a row */
for (i = 0; i < n; i++) {
pnumbers[i] = (int *) malloc(i * sizeof(int));
}
pnumbers[0][1] = 1;
/* Calculating the value of pnumbers[k][l] */
for (i = 0; i < n; i++) {
/*
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
*/
if (!(i % 4 == 2 && i != 2))
for (j = 0; j <= i; j++) {
pnumbers[i][j] = NchooseM(i,j);
} else if (i > 2) {
for (j = 0; j <= i-1; j++) {
pnumbers[i][j] = NchooseM(i,j);
}
}
}
/* Writing out the triangle */
for (i = 0; i < n; i++) {
for (k = 0; k <= x; k++){
printf(" ");
}
for (j = 0; j <= i; j++) {
printf("%d ", pnumbers[i][j]);
}
x = x-1;
printf("\n");
}
for (i = 0; i < n; i++) {
free(pnumbers[i]);
}
free(pnumbers);
return 0;
}
But row number 13 is still quite messed up.
Code is experiencing int overflow and thus undefined behavior (UB).
With 32-bit int and int factorial(int p), p > 12 oveflows the int range.
Code could use a wider integer type (long long works up to p==20), but improvements can be made at NchooseM() to avoid overflow for higher values.
Something like the below. Works up to int n = 30;
int NchooseM(int n, int m) {
// return factorial(n)/(factorial(n-m)*factorial(m));
int nm = 1;
int den = 1;
for (int i = m+1; i <= n; i++) {
assert(INT_MAX/i >= nm);
nm *= i;
assert(nm % den == 0);
nm /= den++;
}
return nm;
}
Tried unsigned long long and works up to int n = 62;
Edit: Another bug:
I "fixed" by initializing all to 1, yet I suspect something remains amiss in /* Calculating the value of pnumbers[k][l] */ for (i = 0; i < n; i++) { code.
pnumbers[i] = malloc((i + 1) * sizeof pnumbers[i][0]);
for (int j = 0; j < i + 1; j++) {
pnumbers[i][j] = 1;
}
Aside: rather than pnumbers[i] = (int *) malloc((i+1) * sizeof(int));, consider below with no unneeded cast nor trying to match the right type.
pnumbers[i] = malloc(sizeof pnumbers[i][0] * (i+1));
Given two arrays: int nums[N] and int *ptrs[N] (N is a constant number).
I have to initialize the first array with some numbers. After that, i have to initialize the second array, so every element of the second array points to the element with the same index of the first array. (ptrs[0] points to nums[0],...).
Now i have to write a function with "ptrs" as argument that modifies the pointers in such a way that the first element of the second array points to the smallest number in the first array,..)
It's not allowed to change the "nums-array", i can only change the "ptrs-array".
This is my code i already have, but when i run it, the "nums-array" changes too.
What do i do wrong?
#include <stdio.h>
#define N 6
void sort(int *ptrs);
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int(*ptrs)[N];
int i;
ptrs = nums;
sort(ptrs);
for (i = 0; i < N; i++)
printf("nummer is: %d en %d\n", (*ptrs)[i], nums[i]);
return 0;
}
void sort(int *ptrs)
{
int i, j, tmp;
for (i = 0; i < N; i++)
for (j = i + 1; j < N; j++)
if ((ptrs)[i] > (ptrs)[j])
{
tmp = (ptrs)[i];
(ptrs)[i] = (ptrs)[j];
(ptrs)[j] = tmp;
}
}
Fix for the first part:
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int *ptrs[N]; // fix
int i;
for(i = 0; i < N; i++) // fix
ptr[i] = nums+i; // fix (or ptr[i] = &nums[i])
I found the solution, thanks for helping guys!
#include <stdio.h>
#define N 6
void sort(int ptrs[], int nums[]);
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int i,j,*p, *ptrs[N];
for (i = 0; i < N; i++) {
ptrs[i] = &nums[i];
}
sort(ptrs, nums);
return 0;
}
void sort(int *ptrs[], int nums[])
{
int i, j, tmp, p[N];
for (i = 0; i < N; i++)
p[i] = *ptrs[i];
for(j = 0; j < N; j++)
for (i = 0; i <= N; i++)
if (p[i] > p[i+1])
{
tmp = (ptrs)[i];
(ptrs)[i] = (ptrs)[i+1];
(ptrs)[i+1] = tmp;
for (i = 0; i < N; i++)
p[i] = *ptrs[i];
}
for (i = 0; i < N; i++)
printf("nummer is: %d en %d\n", *ptrs[i], nums[i]);
return;
}
What my program does is that it takes an array of numbers that were read in from a file and sorts them with the selection sort and bubble sort methods. When it's sorted via the bubble sort method, the array lists one number twice in a row. It's also always the second number that gets copied. I checked to see if for whatever reason the number was actually getting passed to the new array twice, but it isn't. I also tried a different input file, same thing happens in the same place.This also cuts off the last number in the list. I don't see anything obvious in my code that's causing that to happen.
The list that the program calls is as follows:
10
50
78
83
92
100
0
4
72
3
19
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int findMin(int arr[], int start, int size);
void printArr(int arr[], int size);
void selectionSort(int arr[], int size);
void bubbleSort(int arr[], int size);
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Syntax Error: ./<exec> <infile>\n");
exit(1);
}
FILE *ifp = NULL;
ifp = fopen(argv[1], "r");
if(ifp == NULL)
{
printf("Could not open %s for reading\n", argv[1]);
exit(1);
}
int counter;
int j = 0;
fscanf(ifp, "%d", &counter);
int array[counter];
int arrB[counter];
for(j = 0; j < counter; ++j)
{
fscanf(ifp, "%d", &array[j]);
}
for(j = 0; j < counter; j++)
{
arrB[j] = array[j];
}
int size = sizeof(array) / sizeof(int);
printf("Before: ");
printArr(array, size);
selectionSort(array, size);
bubbleSort(arrB, size);
fclose(ifp);
return 0;
}
int findMin(int arr[], int start, int size)
{
int i = 0;
int minLoc = start;
int minVal = arr[minLoc];
for ( i = start + 1; i < size; ++i)
{
if (arr[i] < minVal)
{
minVal = arr[i];
minLoc = i;
}
}
return minLoc;
}
void printArr(int arr[], int size)
{
int i = 0;
for(i = 0; i < size; ++i)
printf("%3d ", arr[i]);
printf("\n");
}
void selectionSort(int arr[], int size)
{
int i = 0;
int minLoc = 0;
int tmp = 0;
for(i = 0; i < size; ++i)
{
minLoc = findMin(arr, i, size);
tmp = arr[i];
arr[i] = arr[minLoc];
arr[minLoc] = tmp;
}
printf("** Selection Sort **\n After: ");
printArr(arr, size);
}
void bubbleSort(int arr[], int size)
{
int i = 0;
int j = 0;
int tmp = 0;
for(j = 0; j < size; j++)
{
for(i = 0; i < size; ++i)
{
if(arr[i] > arr[i+1])
{
tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
}
}
printf("** Bubble Sort **\n After: ");
printArr(arr, size);
}
bubbleSort() accesses outside array bounds. Thus undefined behavior (UB).
for(j = 0; j < size; j++) {
for(i = 0; i < size; ++i) {
if(arr[i] > arr[i+1]) { // Here code access outside bounds when i = size - 1
... Code swaps arr[i], arr[i+1];
}
}
}
Instead
for(j = 0; j < size; j++) {
for(i = 1; i < size; ++i) {
if(arr[i-1] > arr[i]) {
... Code swaps arr[i-1], arr[i];
}
}
}