Binary Interpolation Search cannot find the number im looking for (C) - c

I have an assignment demanding I utilize the algorithm of Binary Interpolation Search in order to find a number and its position in an array, which I'm entering through the keyboard. Unfortunately, while I get no errors, the program returns nothing even though it asks me to enter a number! If you have any idea what might be going wrong it will be helpful!
Here is my code:
#include<stdio.h>
#include<math.h>
int bis(int Array[],int x)
{
int i;
int hitpos;
int left = 0;
int right = sizeof(Array);
int size = right - left + 1;
int next;
int a = x - Array[left];
int b = Array[right]-Array[left];
int c = right - left + 1;
int d = (int)(i*sqrt(size));
next = (size*a/b+1);
do
{
i=0;
size = right - left +1;
if(x >= Array[next])
{
do
{
i = i+1;
right = next + i*sqrt(size);
left = next + (i-1)*sqrt(size);
}
while(x > Array[next + d -1]);
}
else if(x < Array[next])
{
do
{
i = i+1;
right = next -(i-1)*sqrt(size);
left = next - i*sqrt(size);
next = left + (c*a/b);
}
while(x < Array[next - d + 1]);
}
else if(x = Array[next])
{
return next;
}
else
{
return -1;
}
}
while (x != Array[next]);
}
int main()
{
int Array[] = {1,8,10,14,31,55,56,78,87,101};
printf("Please provide a number for binary interpolation search\n");
int x;
scanf("%d", x);
int hit;
hit = bis(Array,x);
if (hit != -1)
{
printf("Element found at index %d", hit);
}
else
printf("Element not found.");
return 0;
}

Related

How can I have this grid wrap around on all sides?

I have an assignment where I need to let the user create the height and width of a grid. Then be able to place "ships" onto that grid at any x and y coordinates. Then you can place a storm on a certain section of that grid to then prompt and see if a storm is overlapped with a ship. I have done that successfully but I can't get the storm to wrap around the grid. For example if the grid is 20x20 and I put a storm that starts on the 20th spot over it should shift to the 1 position on the left side of the grid. Here is that code I have a diagram of what it looks like. (Note there is no physical grid getting printed to the terminal)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ship {
// Declaring variables
char shipName[21];
int x, y, w, h;
char direction;
struct ship *next;
} Ship;
//Declaring head of linked list
Ship *head = NULL;
void newShip(int x, int y, char direction, char *shipName) {
//Adding ships to linked list
Ship *new_ship = (Ship *)malloc(sizeof(Ship));
strcpy(new_ship->shipName, shipName);
new_ship->x = x;
new_ship->y = y;
new_ship->direction = direction;
new_ship->next = head;
head = new_ship;
}
void shipMovement(int time, int w, int h) {
//Moving ships
Ship *current = head;
while (current != NULL) {
if (current->direction = 'U') {
current->y = (current->y + time) % h;
}
else if (current->direction = 'D') {
current->y = (current->y - time + h) % h;
}
else if (current->direction = 'L') {
current->x = (current->x - time + w) % w;
}
else if (current->direction = 'R') {
current->x = (current->x + time) % w;
}
else {
printf("Invalid Direction!\n");
}
current = current->next;
}
}
void checkAffShips(int x, int y, int w, int h, char **affShips, int *numAffShips) {
//Checking if ships are affected by storm
Ship *current = head;
while (current != NULL) {
if (((current->x >= x) && (current->x < x + w)) && ((current->y >= y) && (current->y < y + h))) {
// add shipName to list of affected ships
affShips[*numAffShips] = (char *)malloc(sizeof(char) * 21);
strcpy(affShips[(*numAffShips)++], current->shipName);
}
current = current->next;
}
}
//Main Function------------------------------------------------------------------
int main() {
int w, h;
int stormWidth, stormHeight;
scanf("%d %d", &w, &h);
char userInput;
//Looping through commands
while (scanf(" %c", &userInput) != 4) {
if (userInput == '1') {
int x, y;
char direction[21], shipName[21];
scanf("%d %d %s %s", &x, &y, direction, shipName);
newShip(x, y, direction[0], shipName);
} else if (userInput == '2') {
int time;
scanf("%d", &time);
shipMovement(time, w, h);
} else if (userInput == '3') {
int x, y, w, h;
scanf("%d %d %d %d", &x, &y, &w, &h);
char *affShips[1000];
int numAffShips = 0;
checkAffShips(x, y, w, h, affShips, &numAffShips);
printf("%d\n", numAffShips);
for (int i = 0; i < numAffShips; i++) {
printf("%s\n", affShips[i]);
free(affShips[i]);
}
} else if (userInput == '4') {
break;
}
else {
printf("Invalid Input!\n");
}
}
return 0;
}
Here is the documentation:
(https://i.stack.imgur.com/K28We.png)
I've tried a bunch of different stuff so maybe I just didn't do something right in my attempts but I'm sure someone can help figure this out.
Your test for the affected ships is wrong. In your example, if you have a storm of size 2 in the bottom right corner (19, 19), a ship in the top left corner (0, 0) isn't caught, because 0 is not in the range [19, 21).
One way to fix this is to move the point you want to test into the "extended range" if it lies below the starting point of the storm. (The "extended range" is the range that does not wrap and so extends to two times the width of the board.)
So to test whether a one-dimensional point lies in a cyclic range, you could use a function like this:
int in_cyclic_range(int n, int lower, int width, int wrap)
{
if (n < lower) n += wrap;
return (n < lower + width);
}
If you now test n in the whole range from [0, 20) on the storm at 19 of width 2, with in_cyclic_range(n, 19, 2, 20), you will get hits at locations 19 and 0.
In order to test if a ship is affected by a storm, you need the storm position and dimensions, the ship position and the grid dimensions.
In your code, you use w, and h for the grid dimensions and a new set of variables w and h for the storm dimensions in the local scope of if (userInput == '3') { ... }. This is confusing and makes the grid dimensions inaccessible from this part of the code. You should use stormWidth and stormHeight for the storm dimensions and pass both these and the grid dimensions to the checkAffShips function.
The test in checkAffShips for the wrapped coordinate system is more complicated than what you wrote to take into account the wrapped parts of the storm area: as many as 3 extra rectangles.
Also note these issues:
using explicit names for the grid and storm dimensions would help avoid confusion.
the w and h fields in the Ship structure are unused.
reading strings with scanf should be protected by specifying the maximum number of characters to store into the destination array before the null terminator.
newShip should not use strcpy directly as the shipName argument could be longer than the destination array.
you should check the return value of scanf() to detect invalid or missing input.
if (current->direction = 'U') sets current->direction and evaluates to true. You should use == instead of =
the array of shipnames affShips should be allocated by checkAffShips.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ship {
char shipName[21];
int x, y;
char direction;
struct ship *next;
} Ship;
//Declaring head of linked list
Ship *head = NULL;
/* string copy function with size limitation */
void mystrcpy(char *dest, size_t size, const char *src) {
while (size > 1) {
*dest++ = *src++;
size--;
}
if (size > 0)
*dest = '\0';
}
void newShip(int x, int y, char direction, const char *shipName) {
//Adding ship to linked list
Ship *new_ship = (Ship *)malloc(sizeof(*new_ship));
if (new_ship) {
mystrcpy(new_ship->shipName, sizeof new_ship->shipName, shipName);
new_ship->x = x;
new_ship->y = y;
new_ship->direction = direction;
new_ship->next = head;
head = new_ship;
}
}
void shipMovement(int time, int w, int h) {
//Moving ships
for (Ship *current = head; current != NULL; current = current->next) {
if (current->direction == 'U') {
current->y = (current->y + time) % h;
} else
if (current->direction == 'D') {
current->y = (current->y + h - time % h) % h;
} else
if (current->direction == 'L') {
current->x = (current->x + w - time % w) % w;
} else
if (current->direction == 'R') {
current->x = (current->x + time) % w;
} else {
printf("%s: invalid Direction '%c'!\n",
current->shipName, current->direction);
}
}
}
char **checkAffShips(int stormX, int stormY, int stormWidth, int stormHeight,
int gridWidth, int gridHeight,
int *pnumAffShips)
{
char **affShips = NULL;
int numAffShips = 0;
for (Ship *current = head; current != NULL; current = current->next) {
int x = current->x;
int y = current->y;
//Checking if ship is affected by storm
if (((x >= stormX && x < stormX + stormWidth) ||
(stormX + stormWidth > gridWidth && x < (stormX + stormWidth) % gridWidth)) &&
((y >= stormY && y < stormY + stormHeight) ||
(stormY + stormHeight > gridHeight && y < (stormY + stormHeight) % gridHeight)))
{
// add shipName to list of affected ships
affShips = realloc(affShips, sizeof(*affShips) * (numAffShips + 1));
affShips[numAffShips++] = strdup(current->shipName);
}
}
*pnumAffShips = numAffShips;
return affShips;
}
//Main Function------------------------------------------------------------------
int main() {
int gridWidth, gridHeight;
if (scanf("%d %d", &gridWidth, &gridHeight) != 2)
return 1;
char userInput;
//Looping through commands
while (scanf(" %c", &userInput) == 1) {
if (userInput == '1') {
int x, y;
char direction[21], shipName[21];
if (scanf("%d %d %20s %20s", &x, &y, direction, shipName) != 4)
return 1;
newShip(x, y, direction[0], shipName);
} else
if (userInput == '2') {
int time;
if (scanf("%d", &time) != 1)
return 1;
shipMovement(time, gridWidth, gridHeight);
} else
if (userInput == '3') {
int x, y, stormWidth, stormHeight;
if (scanf("%d %d %d %d", &x, &y, &stormWidth, &stormHeight) != 4)
return 1;
char **affShips;
int numAffShips = 0;
affShips = checkAffShips(x, y, stormWidth, stormHeight,
gridWidth, gridHeight, &numAffShips);
printf("%d\n", numAffShips);
for (int i = 0; i < numAffShips; i++) {
printf("%s\n", affShips[i]);
free(affShips[i]);
}
free(affShips);
} else
if (userInput == '4') {
break;
} else {
printf("Invalid Input!\n");
}
}
return 0;
}

process exits prematurely C programming

there is a part where the program asks the user to enter Y or N and then loops beck when I choose N or else it will end the while loop and continue. when I choose the Y for the first time the program works fine but when I choose N and then Y after my program exits even if it does not encounter the return keyword from the main
and it exits with a garbage return value. It stops at system("cls");. Can anyone tell me what's wrong with this code. Note:
Statistician is an integer pointer type that I created with typedef. And, I've also declared the SIZE variable in the survey.h file
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "survey.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
SIZE = 10;
int c, count = 0, item = 0;
Statistician arr;
float mea, med;
arr = (int*)calloc(10, sizeof(int));
printf("Enter 10 answers\n");
while(count < SIZE) // this is the while loop that loops until Y is chosen by the user in the add function
{
while(item > 9 || item < 1)
{
scanf("%d", &item);
}
++count;
add(arr, &count, &SIZE, item);
item = 0;
}
system("cls");
mea = mean(arr, count);
med = median(arr, count);
printf("mean = %f\n", mea);
printf("median = %f\n", med);
return 0;
}
definition of add() function:
void add(Statistician answer, int *count, int *SIZE, int item)
{
int i, j, temp;
bool swapped;
char choice;
answer[*count - 1] = item;
for(i = 0; i < *count - 1; i++)
{
swapped = false;
for(j = 0; j < *count - i - 1; j++)
{
if(answer[j] > answer[j + 1])
{
temp = answer[j];
answer[j] = answer[j + 1];
answer[j + 1] = temp;
swapped = true;
}
}
if(swapped == false)
break;
}
if(*count == *SIZE)
{
printf("Array is full do you want to compute now?\n");
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
{
choice = toupper(getch());
}
if(toupper(choice) == 'Y') // returns without changing the value of SIZE thus ending the while loop at main
{
return;
}
else if(toupper(choice) == 'N') // adds 10 to SIZE thus continuing the while loop in main and returns
{
printf("add another 10 answers\n");
*SIZE += 10;
realloc(answer, *SIZE);
}
}
return;
}
There are probably other issues (I'm not going to look too closely), but you certainly need to fix:
while(item > 9 || item < 1)
{
scanf("%d", &item);
}
If scanf matches zero items, then that is an infinite loop, with scanf repeatedly returning 0, reading the same data and not changing item. You must always check the value returned by scanf.
This is a serious bug:
realloc(answer, *SIZE);
You don't save the return value so you have lost the allocated memory. Further, you forgot the object size.
In principle you should do
Statistician tmp = realloc(answer, *SIZE * sizeof(int));
if (tmp == NULL)
{
// Error handling
// or just
exit(1);
}
answer = tmp;
However, that doesn't fully help. The problem is that it will only change the value of answer inside the function but not the value of arr in main. In order to change the value of arr you'll have to pass the address of arr to the function. Similar to what you have done with SIZE. BTW: Why do you pass counter as a pointer? You never change it in the function, so it unnecessary to pass a pointer.
Also your current code doesn't initialize choice.
Change
printf("Array is full do you want to compute now?\n");
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
to
printf("Array is full do you want to compute now?\n");
choice = ' ';
while(toupper(choice) != 'N' && toupper(choice) != 'Y') // The part where the program ask for Y or N.
or better:
printf("Array is full do you want to compute now?\n");
do
{
choice = toupper(getch());
} while(toupper(choice) != 'N' && toupper(choice) != 'Y');
BTW:
Since you have choice = toupper(getch()); you don't need toupper(choice) != 'N'. Simply do choice != 'N'
All that said - why do you want to ask the question inside the function? Your code will be much simpler if you do it in main.
Something like:
int main(void) {
int SIZE = 10;
int c, count = 0, item = 0;
int* arr;
float mea, med;
arr = calloc(10, sizeof(int));
printf("Enter 10 answers\n");
while(count < SIZE)
{
while(item > 9 || item < 1)
{
if (scanf("%d", &item) != 1) exit(1);
}
++count;
add(arr, count, item);
item = 0;
if (count == SIZE)
{
printf("Array is full do you want to compute now?\n");
char choice;
do
{
choice = toupper(getch());
} while(choice != 'N' && choice != 'Y');
if(choice == 'N')
{
printf("add another 10 answers\n");
SIZE += 10;
int* tmp = realloc(arr, SIZE * sizeof *arr);
if (tmp == NULL) exit(1); // or error handling
arr = tmp;
}
}
}
system("cls");
mea = mean(arr, count);
med = median(arr, count);
printf("mean = %f\n", mea);
printf("median = %f\n", med);
return 0;
}
void add(int* answer, int count, int item)
{
int i, j, temp;
bool swapped;
answer[count - 1] = item;
for(i = 0; i < count - 1; i++)
{
swapped = false;
for(j = 0; j < count - i - 1; j++)
{
if(answer[j] > answer[j + 1])
{
temp = answer[j];
answer[j] = answer[j + 1];
answer[j + 1] = temp;
swapped = true;
}
}
if(swapped == false)
break;
}
return;
}

Find Lowest Character Using Binary Search Using C Language

Example TestData.txt
Aquos|5#10000
Chitato|10#9500
Chili|20#4000
Output I want(using Quick Sort) report (by subtotal):
A5-120-0|Aquos|5#10000=50000
C5-120-1|Chili|20#4000=80000
A7-504-0|Chitato|10#9500=95000
Total Price = 225000
[a] [b] - [c] - [d]
[a] Got From The Lowest Character in Name
[b] Got From The Length of Character (Take The Last Digit)
[c] Got From Factorial of The Name Length (Output First 3 Digits)
[d] Got From The Counter of The Same Number Of Factorial [c]
I already code it, but, I confused how to implement Binary Search to get The Lowest Character in Name.
Here is my Code (I confused On FindA Function):
#include <stdio.h>
#include <string.h>
#include<ctype.h>
struct sales{
char item[20];
int quantity, price,subtotal;
char a;
int b,c,d;
};
void quickSort(struct sales data[],int first, int last)
{
int pivot, i, j;
char tempItem[25];
int temp;
if(first < last){
i = first;
j = last;
pivot = first;
while(i<j)
{
while(data[i].subtotal <= data[pivot].subtotal && i<last)
{
i++;
}
while(data[j].subtotal > data[pivot].subtotal)
{
j--;
}
if(i<j)
{
temp = data[i].subtotal;
data[i].subtotal = data[j].subtotal;
data[j].subtotal = temp;
temp = data[i].quantity;
data[i].quantity = data[j].quantity;
data[j].quantity = temp;
temp = data[i].price;
data[i].price = data[j].price;
data[j].price = temp;
strcpy(tempItem,data[i].item);
strcpy(data[i].item,data[j].item);
strcpy(data[j].item,tempItem);
}
}
temp = data[pivot].subtotal;
data[pivot].subtotal = data[j].subtotal;
data[j].subtotal = temp;
temp = data[pivot].quantity;
data[pivot].quantity = data[j].quantity;
data[j].quantity = temp;
temp = data[pivot].price;
data[pivot].price = data[j].price;
data[j].price = temp;
strcpy(tempItem,data[pivot].item);
strcpy(data[pivot].item,data[j].item);
strcpy(data[j].item,tempItem);
quickSort(data,first,j-1);
quickSort(data,j+1,last);
}
}
char findA(char item[])
{
char lowest;
int i;
lowest = toupper(item[0]);
i=1;
while(item[i]!='\0')
{
if(toupper(item[i]) < lowest)
lowest = toupper(item[i]);
i++;
}
return lowest;
}
int findB(char item[])
{
int length;
length = strlen(item);
length = length%10;
return length;
}
int findC(int length)
{
int fact = 1,i;
for(i=1;i<=length;i++)
{
fact = fact * i;
}
char temp[10];
sprintf(temp,"%d",fact);
int hundreds = temp[0] - '0';
int tens = temp[1] - '0';
int ones = temp[2] - '0';
int num;
num = hundreds*100 + tens*10 + ones;
return num;
}
int findD(struct sales data[],int i)
{
int count,j,currentC;
count = 0;
j=0;
while(j<i)
{
if(data[i].c == data[j].c)
count++;
j++;
}
return count;
}
int main()
{
int count,i,j,n,total = 0;
FILE *input = fopen("TestData.txt","r");
struct sales data[100];
n = 0;
while(fscanf(input,"%[^|]|%d#%d\n", data[n].item,&data[n].quantity,&data[n].price) != EOF)
{
data[n].subtotal = data[n].quantity * data[n].price;
total = total + data[n].subtotal;
n++;
}
fclose(input);
quickSort(data,0,n-1);
for(i=0;i<n;i++)
{
data[i].a = findA(data[i].item);
data[i].b = findB(data[i].item);
data[i].c = findC(strlen(data[i].item));
data[i].d = findD(data,i);
printf("%c%d-%d-%d|%s|%d#%d=%d\n",data[i].a,data[i].b,data[i].c,data[i].d,data[i].item,data[i].quantity,data[i].price,data[i].subtotal);
}
printf("Total Price = %d\n",total);
return 0;
}
https://pastebin.com/fJQaFdqY

Two-Way Insertion Sort not sorting

This is supposed to be a Two-Way insertion sort, but it's not sorting. I'm also supposed to print out the number of assignments for sorting, but right now I just want it to sort.
A separate output array of size 2n+1 is set aside. Initially x[0] is placed into the middle element of the array n.
Continue inserting elements until you need to insert between a pair of elements in the array.
As before you need to make room for the new element by shifting elements. Unlike before,
you can choose to shift all smaller elements one step to the left or all larger elements one step
to the right since there is additional room on both sides of the array. The choice of which
shift to perform depends on which would require shifting the smallest amount of elements.
I can't find much on the internet about this sort except that no one uses it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d ", arr[j]);
printf("\n");
}
int main() {
FILE *in;
int size_arr = 0;
char ch;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Error!");
exit(1);
}
do {
ch = fgetc(in);
if (ch == '\n')
size_arr++;
} while (ch != EOF);
rewind(in);
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
int n = 0;
while (!feof(in)) {
fscanf(in, "%d", &arr[n]);
n++;
}
fclose(in);
for (n = 0; n < 2 * size_arr; n++) {
sort_arr[n] = 0;
}
sort_arr[size_arr] = arr[0];
for (n = 1; n < size_arr; n++) {
int index = size_arr;
if (arr[n] <= sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index >= 0) {
index--;
}
}
if (arr[n] > sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index < 2 * size_arr) {
index++;
}
}
if (sort_arr[index] == 0) {
sort_arr[index] = arr[n];
} else {
int next_R, next_L = index;
while (sort_arr[next_R] != 0 && next_R <= 2 * size_arr) {
next_R++;
}
while (sort_arr[next_L] != 0 && next_L >= 0) {
next_L--;
}
int R_move = next_R - index;
int L_move = index - next_L;
if (R_move > L_move) {
while (L_move <= index) {
sort_arr[L_move] = sort_arr[L_move + 1];
L_move++;
}
sort_arr[index] = arr[n];
} else {
while (R_move >= index) {
sort_arr[R_move] = sort_arr[R_move - 1];
R_move--;
}
sort_arr[index] = arr[n];
}
}
}
printArray(arr, size_arr);
return 0;
}
I'm not sure this solves all problems but it is a problem you must fix.
This code
int next_R, next_L = index;
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
has undefined behavior as next_R is uninitialized.
Maybe you want:
int next_R = index, next_L = index;
^^^^^
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
In any case you have to initialize next_R before using it.
I also find this line strange:
printArray(arr, size_arr);
^^^
Seems you are printing the original array instead of the sorted array.
May be you want:
printArray(sort_arr, size_arr);
^^^^^
There are some problems in your code:
when you scan the file in the first pass, you should count the number of integers instead of the number of characters.
when inserting, your loops are off by one: the tests should read while (L_move < index) and while (R_move >= index)
while (!feof(in)) is always wrong, you should instead write while (fscanf(in, "%d", &arr[n]) == 1) {...
you should probably allocate the arrays arr and sort_arr instead of defining them as VLAs with automatic storage to prevent undefined behavior on large input files.
you should use binary search into the sorted portion, otherwise your algorithm has a basic complexity of O(N2) that dwarfs the small gain obtained from the minimisation of the insertion phase.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
void print_array(const int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d%c", arr[j], " \n"[j == len - 1]);
}
int main(void) {
FILE *in;
int size_arr, n, start;
int value;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Cannot open input file %s\n", "data_a5.txt");
exit(1);
}
for (size_arr = 0; fscanf(in, "%d", &value) == 1; size_arr++)
continue;
rewind(in);
int *arr = calloc(2 * size_arr + 1, sizeof(*arr));
if (arr == NULL) {
printf("Cannot allocate memory for %d entries\n", size_arr);
exit(1);
}
start = size_arr;
for (n = 0; n < size_arr && fscanf(in, "%d", &value) == 1; n++) {
/* insert value into the sorted array */
int a, b;
for (a = start, b = start + n; a < b;) {
int mid = a + (b - a) / 2;
if (arr[mid] < value) {
a = mid + 1;
} else {
b = mid;
}
}
/* insert value at offset b */
if (b - start < start + n - b) {
/* shift left portion to the left */
for (int i = start--; i < b; i++) {
arr[i - 1] = arr[i];
}
b--;
} else {
/* shift right portion to the right */
for (int i = start + n + 1; --i > b;) {
arr[i] = arr[i - 1];
}
}
arr[b] = value;
}
fclose(in);
print_array(arr + start, n);
free(arr);
return 0;
}
like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len){
while(len--)
printf("%d ", *arr++);
printf("\n");
}
int main(void){
int size_arr = 10;
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
for(int i = 0; i < size_arr; ++i)
arr[i] = -50 + rand() % (100 + 1);
puts("before:");
printArray(arr, size_arr);
int left, right;
sort_arr[left = right = size_arr] = arr[0];
for (int n = 1; n < size_arr; ++n){
int v = arr[n];
if(v <= sort_arr[left]){
sort_arr[--left] = v;
} else if(v >= sort_arr[right]){
sort_arr[++right] = v;
} else {
int L = left, R = right, M, MV;
while(L <= R){
M = L + (R-L)/2;
MV = sort_arr[M];
if(MV < v)
L = M + 1;
else if(v < MV)
R = M - 1;
else
break;
}
//M: insert position
enum { LEFT, RIGHT } CHOICE;
if(v == MV){
int ML = M, MR = M;
while(sort_arr[ML-1] == sort_arr[ML])
--ML;
while(sort_arr[MR] == sort_arr[MR+1])
++MR;
if( ML-left >= right-MR){
M = MR+1;
CHOICE = RIGHT;
} else {
M = ML;
CHOICE = LEFT;
}
} else if(v > MV){
++M;
CHOICE = M-left+1 > right-M;// ? RIGHT : LEFT;
} else {
CHOICE = M-left-1 > right-M;// ? RIGHT : LEFT;
}
if(CHOICE == RIGHT){
memmove(sort_arr + M+1, sort_arr + M, (right-M+1)*sizeof(v));
sort_arr[M] = v;
++right;
} else {
memmove(sort_arr + left-1, sort_arr + left, (M-left)*sizeof(v));
sort_arr[M-1] = v;
--left;
}
}
}
puts("after:");
printArray(sort_arr + left, size_arr);
return 0;
}

C program palindrome game

I'm new in c programming and i'm trying to make a palindrome game. I've given the code below but there is some mistake I'm making and doesn't run can you please give me a hand. Thank you.
The point of the game is to give number to an array, then change with the keys a,d,x,w and try to make it palindrome.
If there is any error can u please give me some advice ?
This is pal.c
#include <stdio.h>
#include "visible.h"
//--------------------------------------------------
// is_pal
//--------------------------------------------------
void print_status(int a[], int* p, int num_mov);
int is_pal(int a[])
{
int b[6];
int i, j;
j = 0;
for (i = 5; i >= 0; i--)
{
b[j] = a[i];
j++;
}
for (i = 0; i <= 5; i++)
{
if (a[i] != b[i]) {
return 0;
}
}
return 1;
}
//--------------------------------------------------
// process_movement
//--------------------------------------------------
void process_movement(int a[], int* p, int num_mov, char c)
{
char d;
d=c;
if(d == 'd')
{
p = a+1;
num_mov++;
print_status(a,p,num_mov);
}
else if(d == 'a')
{
p = a-1;
num_mov++;
print_status(a,p,num_mov);
}
else if(d == 'x')
{
p = malloc(6*sizeof(int));
a = p-1;
num_mov++;
}
else if(d == 'w')
{
p = malloc(6*sizeof(int));
a = p+1;
num_mov++;
}
}
//--------------------------------------------------
// print_status
//--------------------------------------------------
void print_status(int a[], int* p, int num_mov)
{
printf("Number = ");
int i;
for( i = 0; i < 6; i++)
{
printf("%d ", a[i]);
}
printf("\n Number moves = ");
printf("%d", num_mov);
//printf("\n ","%s%", "Pointer is at position ");
printf("%d", *p);
printf("\n");
}
void user_game_palindrome(int pal_num)
{
int a[5];
int i,num_mov;
num_mov = 0;
i = 5;
while (pal_num != 0) {
a[i] = pal_num % 10;
pal_num = pal_num / 10;
i--;
}
int *p = a;
while (is_pal(a) == 1)
{
char c;
print_status(a,p,num_mov);
c = ask_for_command();
process_movement(a,p,num_mov,c);
}
}
This is ex1.c
#include "pal.h"
int main() {
int pal_num = 123342;
user_game_palindrome(pal_num);
return 0;
}
visible.c
#include "visible.h"
#include "conio.h"
//--------------------------------------------------
// gen_num
//--------------------------------------------------
int gen_num(int lb, int ub) {
int num = (rand() % (ub - lb)) + lb;
return num;
}
/* Note: Do not forget to include the following instruction at the beginning of your main() method:
srand(time(NULL));
*/
//--------------------------------------------------
// my_getchar
//--------------------------------------------------
char my_get_char() {
char my_char;
int b = 0;
char dummy_char;
my_char = getchar();
while (b == 0) {
dummy_char = getchar();
if (dummy_char == '\n')
b = 1;
}
return my_char;
}
this is the visible.c ( my teacher told me to include it)
Your conversion from int to array is wrong
for (i = 0; i < 4; i++) {
a[i] = pal_num%10;
pal_num = pal_num % 10;
}
Here, why would this loop end when i is 4. It should go till pal_num is 0. And pal_num = pal_num % 10; should be pal_num = pal_num / 10;
Try something like
i = 0;
while (pal_num != 0) {
a[i] = pal_num % 10;
pal_num = pal_num / 10;
i++;
}
NOTE: Be aware, that this would essentially reverse your int and store in the array.
There's a lot going wrong in your code and you still haven't fixed many things which have been pointed out by others.
as to remove the unnecessary creating of the array b, is_pal can be defined as:
int is_pal(int a[])
{
int i;
for (i = 0; i < 3; ++i)
{
if (a[5-i] != a[i])
return 0;
}
return 1;
}
process_movement doesn't have a case where d == 'w'
user_game_palindrome should have the while loop checking (is_pal(a) == 0)
And you should apply the changes that were suggested by #Haris

Resources