I think this is C. but trying to figure out why my bubble sort isn't working. I was following an existing example so perhaps my integration with this code isn't right but not too sure.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("%s <student-id>\n", argv[0]);
exit(0);
}
int i;
int size = 10000;
int seed = atoi(argv[1]);
srand(seed % 4);
int *int_array = malloc(sizeof(int)*size);
for (i = 0; i < size; i++)
{
int_array[i] = rand();
}
// This part
int j;
for (i = 0; i < size; i += 1) {
for (j = i - 1; j >= 0 && int_array[j] > int_array[j + 1]; j+= 1) {
swap(int_array,j);
}
}
int failed = 0;
for (i = 0; i < size; i++)
{
if (int_array[i] < int_array[i+1])
{
failed = 1;
break;
}
}
free(int_array);
return 0;
}
This is my code for bubble sort:
for (int i = 0; i < size; i += 1)
{
for (j = i + 1; j < size; j+= 1)
{
//this for starts from i+1 because I want to compare element int_array[i] whith the rest of the array. Each time this for starts, int_array is sorted from 0 to i-1
if(int_array[i] > int_array[j]) swap(int_array[i], int_array[j]);
}
}
Related
how would I input a 2D array in C, filled with dots?
Here is the code I have written so far, but I still don't see an output of a 2D array with dots.
#include <stdio.h>
#include <stdlib.h>
#define PLAYER_NONE 0
#define PLAYER 1
#define PLAYER_CPU 2
int i; // Global Variable for column and row
int j; // Global Variable for column and row
char playerBoard[8][8]; //Global Variable
char cpuBoard[8][8]; // Global Variable
//Initialise the main parts of the board
void initialise_board(void)
{
for (int i = 0; i < 8; i++) { //iterate the rows
for (int j = 0; j < 8; j++) {
cpuBoard[i][j] = '.';
}
}
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
playerBoard[i][j] = '.';
}
}
}
int main(int argc, char *argv[])
{
initialise_board();
while (!check_win()) {
display_board();
get_move(turn);
turn = (turn == 1) ? 2 : 1;
return 0;
}
//Display battleship board when a turn is played
void display_board()
{
printf("\n");
for (char i = 'A'; i < 'H' + 1; i++) {
printf("%c", i);
}
printf("\n");
for (i = 1; i < 8 + 1; i++) {
printf("%d",i);
for (j = 0; j < 8; j++) {
}
printf("\n");
}
printf("===");
printf("\n");
}
Any help would be much appreciated, Thank you very much
Sometimes, while troubleshooting a seemingly impossible problem, it is a good idea to remove all distractions from the code:
Run a simplified main() function:
int main(int argc, char *argv[])
{
initialise_board();
//while (!check_win()) {
display_board();
// get_move(turn);
// turn = (turn == 1) ? 2 : 1;
return 0;
}
And you will see some output, which you can then debug to adjust as needed.
However, As you point out in your comments, you are not seeing output. If you look closely, you will discover that is because you are never including cpuBoard or playerBoard in a printf statement, such as:
printf("%c", cpuBoard[i][j]);
The following will not finish this for you, but will get you started:
void display_board(void)
{
//printf("\n");//removed for illustration
//for (char i = 'A'; i < 'H' + 1; i++) {
// printf("%c", i);
//}
printf("\n");
for (i = 1; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
printf("%c", cpuBoard[i][j]); //illustrates printout of populated array cpuboard.
}
printf("\n");
}
printf("===");
printf("\n");
}
Your code looks fine. Check for the opening and closing brackets and add following statement in initializeboard() function :
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
printf("%c",playerBoard[i][j]);
}
}
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));
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;
}
I have implemented a Counting Sort in an assignment given to us by a teacher but sometimes it doesn't work for large arrays.
Here is the code:
void countingSort(int *t, int n) {
int min = findMin(t, n);
int max = findMax(t, n);
int range = max - min + 1;
int *count, *output;
int i;
count = (int *)malloc(range * sizeof(int));
output = (int *)malloc(n * sizeof(int));
for (i = 0; i < range; i++) {
count[i] = 0;
}
for (i = 0; i < n; i++) {
count[t[i] - min]++;
}
for (i = 1; i < range; i++) {
count[i] += count[i - 1];
}
for (i = n - 1; i >= 0; i--) {
output[count[t[i] - min] - 1] = t[i];
count[t[i] - min]--;
}
for (i = 0; i < n; i++) {
t[i] = output[i];
}
}
What's wrong with my code?
Your code seems to work for small values of range, but might fail if min and max are too far apart, causing the computation of range to overflow the range of int and malloc() to fail.
You should check for overflow in range and check memory allocation success. Note too that calloc() is more appropriate than malloc() for the count array. Finally, you must free the allocated arrays.
Here is a modified version:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int findMax(const int *t, int n) {
int max = INT_MIN;
while (n-- > 0) {
if (max < *t) max = *t;
t++;
}
return max;
}
int findMin(const int *t, int n) {
int min = INT_MAX;
while (n-- > 0) {
if (min > *t) min = *t;
t++;
}
return min;
}
int countingSort(int *t, int n) {
int min, max, range, i;
int *count, *output;
if (n <= 0)
return 0;
min = findMin(t, n);
max = findMax(t, n);
if (min < 0 && max >= 0 && (unsigned)max + (unsigned)(-min) >= INT_MAX) {
fprintf(stderr, "countingSort: value range too large: %d..%d\n", min, max);
return -1;
}
range = max - min + 1;
if ((count = (int *)calloc(range, sizeof(int))) == NULL) {
fprintf(stderr, "countingSort: cannot allocate %d element count array\n", range);
return -1;
}
if ((output = (int *)malloc(n * sizeof(int))) == NULL) {
fprintf(stderr, "countingSort: cannot allocate %d element output array\n", n);
free(count);
return -1;
}
for (i = 0; i < n; i++) {
count[t[i] - min]++;
}
for (i = 1; i < range; i++) {
count[i] += count[i - 1];
}
for (i = n; i-- > 0;) {
output[count[t[i] - min] - 1] = t[i];
count[t[i] - min]--;
}
for (i = 0; i < n; i++) {
t[i] = output[i];
}
free(count);
free(output);
return 0;
}
You can avoid the cumbersome and potentially inefficient downward loop by replacing the second and third for loops with this:
/* compute the first index for each value */
int index = 0;
for (i = 0; i < range; i++) {
incr = count[i];
count[i] = index;
index += incr;
}
/* copy each value at the corresponding index and update it */
for (i = 0; i < n; i++) {
output[count[t[i] - min]++] = t[i];
}
my output values
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define W 160
#define H 105
struct dungeons {
int x;
int y;
int width;
int height;
};
void randomNumberGenerator(int seed);
void makeGameBoard(int gameBoard[W][H]);
void makeDungeonRooms(struct dungeons d[10]);
void printGame(int gameBoard[W][H]);
int main(int argc, char *argv[]) {
int gameBoard[W][H];
//int gameBoard[160][105] = {2};
struct dungeons d[10];
makeGameBoard(gameBoard);
makeDungeonRooms(d);
printGame(gameBoard);
return 0;
}
void randomNumberGenerator(int seed) {
srand(seed);
}
void makeGameBoard(int gameBoard[160][105]) {
int i;
int j;
for (j = 0; j < 105; j++) {
for (i = 0; i < 160; i++) {
gameBoard[i][j] = 2;
//gameBoard[i][j] = 2;
/*
if (j == 0) {
gameBoard[i][j] = 2;
} else
if (j == 104) {
gameBoard[i][j] = 2;
} else
if (i == 0) {
gameBoard[i][j] = 2;
} else
if (i == 159) {
gameBoard[i][j] = 2;
} else {
gameBoard[i][j] = 4;
}
*/
}
}
gameBoard[0][1] = 2;
gameBoard[0][0] = 2;
gameBoard[159][0] = 3;
}
void makeDungeonRooms(struct dungeons d[10]) {
int i;
for (i = 0; i < W; i++) {
d[i].x = 0;
d[i].y = 0;
d[i].width = 0;
d[i].height = 0;
}
}
void printGame(int g[W][H]) {
int i;
int j;
for (i = 0; i < W; i++) {
for (j = 0; j < H; j++) {
printf("%d", g[i][j]);
/*
if (g[i][j] == 2) {
printf("|");
} else
if (g[i][j] == 1) {
printf("X");
} else {
printf(" ");
}
*/
}
printf("\n");
}
}
I'm making a grid. But the first 5 rows and half of the 6th row, when printed output the value 0. I'm setting everything to 2 in the for loop, and even after when I try to manually change the value, it still doesn't. The last one [159][0] works but nothing in the first 5 rows and half of the 6th seem to work. They stay 0. Why?
The problem is here:
void makeDungeonRooms(struct dungeons d [10]){
int i;
for(i = 0; i< W; i++){
d[i].x = 0;
d[i].y = 0;
d[i].width = 0;
d[i].height = 0;
}
}
where #define W 160. Accessing array out of bound can trigger undefined behavior. It can trigger a segmentation fault, it can remain unnoticed for a long time or alter the output of the program in very strange ways. Here, zeroing the dungeons also partly zeroed the gameBoard. Keep it that way: your game is going to be hilarious!