Function to swap two adjacent elements isn't working - c

When I try to move a legal tile (i.e one adjacent to the 'blank' tile 0), nothing happens. If the tile is illegal the program functions as it should. Here is the move function:
bool move(int tile)
{
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == tile)
{
// stops program from going out of bounds
if (j < d)
{
if (board[i][j + 1] == 0)
{
swap(board[i][j], board[i][j + 1]);
return true;
}
}
if (j > 0)
{
if (board[i][j - 1] == 0)
{
swap(board[i][j], board[i][j - 1]);
return true;
}
}
if (i > 0)
{
if (board[i - 1][j] == 0)
{
swap(board[i][j], board[i - 1][j]);
return true;
}
}
if (i < d)
{
if (board[i + 1][j] == 0)
{
swap(board[i][j], board[i + 1][j]);
return true;
}
}
}
}
}
return false;
}
and the swap function:
void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
What happens is the board remains looking the same with no changes made.

You need to use pointers to change the memory at board[i][j].
Try something like this
void swap(int *i, int *j)
{
int temp = *i;
*i = *j;
*j = temp;
}
and then in your calling code
swap(&board[i][j], &board[i][j - 1]);

Related

Heap-corruption when freeing allocated memory

I am writing small school project, and I got stuck with error that I can't fix. When I try to free allocated memory, I get this error:
Here is the code that involves my char pointer temp:
1. Allocation of memory and setting starting value:
char *temprijec(int rng, RIJEC *B, int *len) {
int i;
char *temp=(char*)calloc(*len + 1, sizeof(char));
*len = strlen((B + rng)->rijec);
for (i = 0; i < *len; i++) {
if (i == 0) {
temp[i] = (B + rng)->rijec[i];
}
else if (i == (*len)) {
temp[i] = '\0';
}
else {
temp[i] = '_';
}
}
return temp;
}
2. Working with char pointer temp:
void tijek_igre(char*temp,RIJEC *B,int rng,int len,int*br2pok,int *pokpogreska,int *pokbr,char*pokch) {
int i;
printf("\nPogodi slovo ili rijec!");
*pokch = _getch();
for (i = 0; (B + rng)->rijec[i] != '\0'; i++) {
if (*pokch == (B + rng)->rijec[i]) {
temp[i] = *pokch;
}
}
for (i = 0; (B + rng)->rijec[i] != '\0'; i++) {
if (*pokch != (B + rng)->rijec[i]) {
(*br2pok)++;
if (*br2pok == len) {
(*pokpogreska)++;
}
}
}
for (i = 0; temp[i] != '\0'; i++) {
if (temp[i] != '_') {
(*pokbr)++;
}
}
}
Everything is fine until I try to free it with free(temp);
I fixed the error by changing the way I am passing variables to function,structure instead of pointers and now it works idk why but it works :).Tnx everyone for help.
Changed code:
VARIJABLE temprijec(VARIJABLE V, RIJEC *B) {
int i;
V.len = strlen((B + V.rng)->rijec);
V.temp = (char*)calloc(V.len + 1, sizeof(char));
for (i = 0; i < V.len + 1; i++) {
if (i == 0) {
V.temp[i] = (B + V.rng)->rijec[i];
}
else if (i == (V.len)) {
V.temp[i] = '\0';
}
else {
V.temp[i] = '_';
}
}
return V;
}
and
VARIJABLE tijek_igre(RIJEC *B, VARIJABLE V) {
int i;
printf("\nPogodi slovo ili rijec!");
V.ch = _getch();
for (i = 0; (B + V.rng)->rijec[i] != '\0'; i++) {
if (V.ch == (B + V.rng)->rijec[i]) {
V.temp[i] = V.ch;
}
}
for (i = 0; (B + V.rng)->rijec[i] != '\0'; i++) {
if (V.ch != (B + V.rng)->rijec[i]) {
(V.pogresno_slovo)++;
if (V.pogresno_slovo == V.len) {
(V.pogreska)++;
}
}
}
for (i = 0; V.temp[i] != '\0'; i++) {
if (V.temp[i] != '_') {
(V.tocno_slovo)++;
}
}
return V;
}

Comparing sorting methods in C

I have to compare these 3 sorting functions (bubble, insertion, and selection), in their worst, best, and the random possible way to sort an array (when talking about the idea of numbers of comparison).
I built and ran the program. The compiler is working, everything seems fine. The problem is that after the cmd window appears, nothing happens. The program is not returning anything (neither 0 (because of return 0) or writing sth in the file). How can I fix it?
#include <stdio.h>
#include <stdlib.h>
int b[11000];
int w[11000];
int r[11000];
int n;
int comp;
int attr;
FILE*f;
//CREAREA SIRURILOR
//best, worst, random
void sir(int n)
{ int i;
for(i=0; i<n; i++)
{
b[i] = i;
r[i] = rand() % n;
w[i] = n-i-1;
}
}
//INSERTION SORT
void insertion (int a[1000])
{
int j, i, index;
comp = 0;
attr = 0;
for (i = 0; i < n; i++)
{
index = a[i];
j = i;
attr+=1;
while ((j > 0) && (a[j-1] > index))
{ comp++;
a[j] = a[j-1];
j = j-1;
attr+=1;
}
while ((j > 0) || (a[j-1] > index))
{ comp++;
}
a[j] = index;
attr++;
}
fprintf(f,"\t%d\t", comp);
fprintf(f,"\t%d\t", attr);
fprintf(f,"\t%d\t", attr+comp);
}
//Selection Sort
void selection (int a[1000])
{
int j, i, min, temp;
comp = 0;
attr = 0;
for (i = 0; i < n-1; i++)
{
min = i;
for (j = i+1; j < n; j++){
comp++;
if (a[j] < a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
attr+=3;
}
fprintf(f,"\t%d\t", comp);
fprintf(f,"\t%d\t", attr);
fprintf(f,"\t%d\t", attr+comp);
}
//Bubble Sort
void bubblesort (int array[2000])
{
int sorted;
int swap,d;
int c;
comp = 0;
attr = 0;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0; d < n - c - 1; d++)
{
comp++;
if (array[d] > array[d + 1])
{
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
attr += 3;
}
}
}
fprintf(f,"\t %d\t", comp);
fprintf(f,"\t %d\t", attr);
fprintf(f,"\t%d\t", attr+comp);
}
void InsertionSort()
{
insertion(b);
insertion(r);
insertion(w);
}
void SelectionSort()
{
selection(b);
selection(r);
selection(w);
}
void BubbleSort()
{
bubblesort(b);
bubblesort(r);
bubblesort(w);
}
int main ()
{
f = fopen("iesire.txt","w+");
if(f == NULL)
{
printf("Error!");
exit(-1);
}
fprintf(f,"\n Bubble Sort\t\n");
fprintf(f,"\tBest\t\t\t\t\t\tAverage\t\t\t\t\t\tWorst\t\t\n");
fprintf(f,"\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\n");
for (n = 100; n<=10000; n+=500)
{
sir(n);
BubbleSort();
fprintf(f,"\n");
}
fprintf(f,"\n\n Selection Sort\t\n");
fprintf(f,"\tBest\t\t\t\t\t\tAverage\t\t\t\t\t\tWorst\t\t\n");
fprintf(f,"\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\n");
for (n = 100; n<=10000; n+=500)
{
sir(n);
InsertionSort();
fprintf(f,"\n");
}
fprintf(f,"\n\n Insertion Sort\t\n");
fprintf(f,"\tBest\t\t\t\t\t\tAverage\t\t\t\t\t\tWorst\t\t\n");
fprintf(f,"\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\t\tComparatii\t\tAtribuiri\t\tComp+Atr\n");
for (n = 100; n<=10000; n+=500)
{
sir(n);
SelectionSort();
fprintf(f,"\n");
}
fclose(f);
printf(" Result: 'iesire.txt'.");
return 0;
}

Find pset3 "\expected an exit code of 0, not 1"

all mighty community of CS50ers on StackOverflow!
I have coded the sort and search functions of pset3, find, but I just don't get why I get this message. It is as if in the while loop the first if were never executed.
Any hints?
#include <cs50.h>
bool search(int value, int values[], int n)
{
if (n < 1)
{
return false;
}
else
{
int start = 0, end = (n-1);
while (end >= start)
{
int median = (end - start) / 2;
if (median == value)
{
return true;
}
else if (values[median] < value)
{
start = values[median + 1];
}
else
{
end = values[median - 1];
}
}
return false;
}
}
void sort(int values[], int n)
{
int temp;
for (int i = 0; i < n; i++)
{
int smallest_index = i;
for (int j = i + 1; j < n; j++)
{
if (values[i] > values[j])
smallest_index = j;
}
temp = values[smallest_index];
values[smallest_index] = values[i];
values[i] = temp;
}
}
Click Here to See Error Message from Check50

how to detect a diagonal number of X's

i'm an trying to write a program that will call a function win if there is n number of X's or O's in a row. I am have difficulty with the diagonal win that slopes upwards. can any offer any advice on what I should change? Thanks in advance. It calls an infinite loop instead of returning true.
bool left_diag_win(char **board, int num_rows, int num_cols) {
int i;
if (board[0][0] == '*') {
return false;
}
for (i = 1; i < num_rows; ++i) {
if (board[i][i] != board[0][0]) {
return false;
}
}
return true;
}
bool right_diag_win(char **board, int num_rows, int num_cols) {
int i;
if (board[0][num_cols - 1] == '*') {
return false;
}
for (i = 1; i < num_rows; ++i) {
if (board[i][num_cols - i - 1] != board[0][num_cols - 1]) {
return false;
}
}
return true;
}
You code seems correct, but you probably have a problem elsewhere. Here is an example where it behaves as expected:
#include <stdbool.h>
#include <stdio.h>
bool left_diag_win(char **board, int num_rows, int num_cols) {
if (board[0][0] == '*') {
return false;
}
for (int i = 1; i < num_rows; ++i) {
if (board[i][i] != board[0][0]) {
return false;
}
}
return true;
}
bool right_diag_win(char **board, int num_rows, int num_cols) {
if (board[0][num_cols - 1] == '*') {
return false;
}
for (int i = 1; i < num_rows; ++i) {
if (board[i][num_cols - i - 1] != board[0][num_cols - 1]) {
return false;
}
}
return true;
}
int main(void) {
char *matrix1[] = { "X****", "*X***", "**X**", "***X*", "****X" };
char *matrix2[] = { "****X", "***X*", "**X**", "*X***", "X****" };
printf("matrix:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", matrix1[i]);
}
printf("left-diagonal: %d\n", left_diag_win(matrix1, 5, 5));
printf("right-diagonal: %d\n\n", right_diag_win(matrix1, 5, 5));
printf("matrix:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", matrix2[i]);
}
printf("left-diagonal: %d\n", left_diag_win(matrix2, 5, 5));
printf("right-diagonal: %d\n\n", right_diag_win(matrix2, 5, 5));
return 0;
}
Output:
matrix:
X****
*X***
**X**
***X*
****X
left-diagonal: 1
right-diagonal: 0
matrix:
****X
***X*
**X**
*X***
X****
left-diagonal: 0
right-diagonal: 1

Having issues with pointers

I'm fairly new to programming and i'm having problem with pointers. My code below works with the exception for that my counts doesn't follow with my article number when i sort it. I probably need pointers to get this working but I don't know how.
Can anyone help me?
void printMenu(void)
{
printf("\nMENU:\n");
printf("(D)isplay the menu\n");
printf("(G)enerate inventory\n");
printf("(P)rint inventory\n");
printf("(L)inear search article\n");
printf("(B)inary search article\n");
printf("(I)nsertion sort inventory\n");
printf("B(u)bble sort inventory\n");
printf("(M)erge sort inventory\n");
printf("(Q)uit program\n");
}
void generateInventory(article inventory[], int noOfArticles,
int minArticleNumber, int maxArticleNumber, int maxNoOfArticles)
{
int i, j;
int idCount[] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
for (i = 0; i < noOfArticles; i++)
{
inventory[i].id = rand() % (maxArticleNumber - minArticleNumber + 1) +
minArticleNumber;
idCount[inventory[i].id - 1] = idCount[inventory[i].id - 1] + 1;
for (j = 0; j <= i; ++j)
{
if (idCount[inventory[i].id - 1] > 1)
{
inventory[i].id = rand() % (maxArticleNumber + minArticleNumber);
}
}
inventory[i].counts = rand() % maxNoOfArticles;
}
}
void printInventory(const article inventory[], int noOfArticles)
{
int i;
printf("\nINVENTORY\n");
printf("%7s %8s\n", "Article", "Count");
for (i = 0; i < noOfArticles; i++)
{
printf("%7d %8d\n", inventory[i].id, inventory[i].counts);
}
}
int getArticleId()
{
int id;
printf("\nGive article id: ");
scanf("%d", &id);
return id;
}
void printSearchResult(const article inventory[], int index)
{
if (index == -1)
{
printf("\nArticle not found\n");
}
else
{
printf("\nArticle id: %d\n", inventory[index].id);
printf("Article counts: %d\n", inventory[index].counts);
}
}
int linearSearchInventory(const article inventory[], int noOfArticles, int id)
{
int i = 0;
int index = -1;
while (index == -1 && i < noOfArticles)
{
if (id == inventory[i].id)
{
index = i;
}
i++;
}
}
int binarySearchInventory(const article inventory[], int noOfArticles, int id)
{
int index = -1;
int left = 0;
int right = noOfArticles - 1;
int middle;
while (index == -1 && left <= right)
{
middle = (left + right) / 2;
if (id == inventory[middle].id)
{
index = middle;
}
else if (id < inventory[middle].id)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return index;
}
void insertionSortInventory(article inventory[], int noOfArticles)
{
int i, j;
int next;
for (i = 1; i < noOfArticles; i++)
{
next = inventory[i].id;
j = i - 1;
while (j >= 0 && next < inventory[j].id)
{
inventory[j + 1].id = inventory[j].id;
j = j - 1;
}
inventory[j + 1].id = next;
}
}
void bubbleSortInventory(article inventory[], int noOfArticles)
{
int c, d, t;
for (c = 0; c < (noOfArticles - 1); c++)
{
for (d = 0; d < noOfArticles - c - 1; d++)
{
if (inventory[d].id > inventory[d + 1].id)
{
t = inventory[d].id;
inventory[d].id = inventory[d + 1].id;
inventory[d + 1].id = t;
}
}
}
}
void mergeSortInventory(article inventory[], int noOfArticles)
{
int temp[noOfArticles / 2];
int nLeft, nRight;
int i, iLeft, iRight;
if (noOfArticles > 1)
{
nLeft = noOfArticles / 2;
nRight = (int) ceil((double) noOfArticles / 2);
mergeSortInventory(inventory, nLeft);
mergeSortInventory(&inventory[noOfArticles / 2], nRight);
for (i = 0; i < nLeft; i++)
{
temp[i] = inventory[i].id;
}
i = 0;
iLeft = 0;
iRight = 0;
while (iLeft < nLeft && iRight < nRight)
{
if (temp[iLeft] < inventory[noOfArticles / 2 + iRight].id)
{
inventory[i].id = temp[iLeft];
iLeft = iLeft + 1;
}
else
{
inventory[i].id = inventory[noOfArticles / 2 + iRight].id;
iRight = iRight + 1;
}
i = i + 1;
}
while (iLeft < nLeft)
{
inventory[i].id = temp[iLeft];
i = i + 1;
iLeft = iLeft + 1;
}
}
}
If I'm correct in what you're asking, you want to keep the idCount array relational to the inventory array. I assume, since you're using article as a type that you've either typedef'd a variable to be an article, which would be pointless, or more likely you've built a struct of type article, then made an array of those structs, and called the array inventory.
If this is the case, then the most likely method of keeping them relational is to just include the count in the article struct.
There are methods of making the arrays relational without doing that, but they're pointless, because a simple four-line struct would do the trick, even if that struct was a wrapper around a different struct, or a header for another struct.
When sorting your records, you only assign the id member of your struct:
inventory[foo].id = inventory[bar].id;
You should assign the complete struct:
inventory[foo] = inventory[bar];
Just remember that temporaries must be of type article an not int so they allso can be assigne a complete struct and not only an id value

Resources