bitwise right shift affecting another short - c

I am using bitwise operators to shift the binary value of shorts within a linked list. The function is recursive and after an arbitrary number of occurrences, my right shift seems to affect the value of a short in the next link despite me not pointing to this link at all at this point of the function. Here is my code :
static void move_right(t_tetri *piece) {
int i;
i = 0;
piece->x_offset++;
while (i < piece->height) {
piece->shape[i] = piece->shape[i] >> 1;
i++;
}
}
int ft_solve(t_map *map, t_tetri *list) {
if (list == NULL) return (1);
while (list->y_offset + list->height <= map->size) {
while (list->x_offset + list->width <= map->size) {
if (put_tetri(map, list)) {
set_piece(map, list);
if (ft_solve(map, list->next)) return (1);
else unset_piece(map, list);
}
move_right(list);
}
reset_piece(list);
}
list->y_offset = 0;
return (0);
}
piece->shape is an array containing 4 short but I'm mostly concerned about the first of these here. In certain cases (not all) when I go through the move_right function the value of piece->next->shape[0] is shifted in the same way, which poses a big problem for the next recursion of ft_solve.
Would anyone have any idea?
I can post more of my code if necessary, I'm not really used to ask questions here so if you need more information I'm ready to add it.

Related

How do you make a menu interface that accepts double digit integers or characters in C?

I was fumbling with this program for the last couple of hours and I can't seem to find a way to get this program to work. I started out with a switch statement style menu but then I had an issue where the menu would fall through and exit and I couldn't figure that out so I just switched my code over to an if else based menu. The idea behind the program is as follows:
Write and test a C program that implements a stack based integer-based calculator. The program accepts input until q is entered. However my difficulties lie in getting the menu to accept numbers larger than 10.
I have every single function working properly in my program except when I enter a two digit integer it will store both digits individually. I know that this is because I have the menu setup to read and work with chars, but I wasn't able to figure out how to get an array of chars to work. I've never programmed in C before so the idea of dynamic memory allocation alludes me as I'm not entirely sure when it is necessary. Here is the source code I have for the program so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define SIZE 6
int stack[SIZE]; //stack size
int top = 0; //top of stack
void pop();
void clear();
void display();
void top_element();
void add();
void multiply();
void subtract();
void division();
void power();
int main()
{
char input;
int flag = 1;
while(flag == 1)
{
printf(": ");
scanf(" %c",&input);
if(isdigit(input))
{
if(top < SIZE)
{
stack[top] = input - '0';
top++;
}
else
printf("Error: stack overflow\n");
}
else if(input=='p')
pop();
else if(input=='c')
clear();
else if(input=='d')
display();
else if(input=='=')
top_element();
else if(input=='+')
add();
else if(input=='*')
multiply();
else if(input=='-')
subtract();
else if(input=='/')
division();
else if(input=='^')
power();
else if(input=='q')
flag = 0;
else
printf("Error: invalid command\n");
}
printf("Goodbye!\n");
return 0;
}
void pop()
{
if(top==0)
printf("Error: stack is empty\n");
else
top--;
}
void clear()
{
top=0;
}
void display()
{
int i;
if(top == 0)
printf("Error: stack is empty\n");
else
{
for(i = top - 1; i >= 0; i--)
printf("%d\n",stack[i] );
}
}
void top_element()
{
printf("%d\n",stack[top-1] );
}
void add()
{
if(top<2)
printf("Error: not enough operands for the requested operation\n");
else
{
int ans=stack[top-1]+stack[top-2];
stack[top-2]=ans;
top--;
}
}
void multiply()
{
int ans=stack[top-1]*stack[top-2];
stack[top-2]=ans;
top--;
}
void subtract()
{
if(top < 2)
printf("Error: not enough operands for the requested operation\n");
else
{
int ans = (stack[top-2] - stack[top-1]);
stack[top-2]=ans;
top--;
}
}
void division()
{
if(top < 2)
printf("Error: not enough operands for the requested operation\n");
else
{
if(stack[top-1]==0)
printf("Error: attempt to divide by 0\n");
else
{
int ans = (stack[top-2]/stack[top-1]);
stack[top-2]=ans;
top--;
}
}
}
void power()
{
if(top < 2)
printf("Error: not enough operands for the requested operation\n");
else
{
int ans = pow(stack[top - 2], stack[top - 1]);
stack[top - 2] = ans;
top--;
}
}
I have a few things to note and don't want to turn this into a TLDR so I'll try to keep each issue to separate paragraphs. You can take this all with a grain of salt; it is just advice, after all.
The format directive you're looking for is %2[0123456789]. Pass a pointer to a location suitably sized to store three characters (i.e. char something[3]; the third byte for the null character) and check the return value. This directive needs to go in a call to scanf on its lonesome, or you'll likely have an aneurysm debugging an issue related to empty fields later on, so the "green light" return value indicating your program is successfully processing good input is that scanf("%2[0123456789]", ptr_into_array_of_char) will return 1. Any other return value means amber or red lights happened. Mind you, I'm interpreting your specs (which are incomplete) quite strictly here... in reality I'd just use %d and be happy that my users are halving their chances of developing arthritis by entering 1 instead of 01 (and you're also less likely to have aneurysms when not dealing with %[).
Our compilers usually issue error messages and abort compilation when we make some syntax error, but this requirement goes against that grain: "The program accepts input until q is entered." I hope your full spec explains what should happen when the user deviates from the expectations. I suppose you could issue an error, clear the stack, read to end of line and just operate as though the program restarted... something like scanf("%*[^\n]"); getchar(); puts("Error message here"); top = 0;? We typically use some key combination like CTRL+d (on Linux) or CTRL+Z (on Windows) to close stdin thus denoting termination of input.
"the idea of dynamic memory allocation alludes me" and so you'll be thankful to know that you probably shouldn't use dynamic memory allocation here, unless you want your stack to grow beyond the hardcoded 6 slots that you've set, perhaps...
I assume the title for this question is mixed up in the confusion; you're not designing a menu, but instead implementing a grammar. Look how gccs "menu" is designed for inspiration here. If you're ever tempted to design a menu around stdin, stop; perhaps what you really want is a GUI to point and click because that's not how Unix tends to work.
Declaring void fubar(void); followed by void fubar() { /* SNIP */ } is undefined behaviour due to some technical historical artefacts, and the same goes for int main()... This is why you might be best to choose a book which teaches C specifically, written by somebody reputable, to learn C. There are lots of subtle nuances that can trap you.
On the note of function prototypes and so forth, consider that a stack is a generic data structure. As an alternative thought experiment, consider what a pain strcpy would be to use if it only operated on arrays declared with file scope. It follows logically that all of its external data requirements should come from its arguments, rather than from a variable i.e. stack declared with file scope.
We're taught to use memory somewhat cautiously, and it seems to me as though using a variable solely as a controlling expression like this contravenes those lessons. Where constructs such as break, continue and goto exist, a cleaner alternative without variable declarations (and thus an extra free register to use for something else) is possible.
The problem is not in scanf() this time but in the way you parse the input.
It is not wrong to parse the input character by character, to the contrary it make things much easier, at least in almost all of the cases. But parsing character by character means also that you parse every positive number larger than nine also character by character or better digit by digit--you have to build the complete number out of the single digits. You parse from "the left to the right", so just multiply by ten and add the digit. Rinse and repeat until you have no digits left and put the result on the stack.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define SIZE 6
/* you should look up what "static" means and when and how to use */
static int stack[SIZE]; //stack size
static int top = 0; //top of stack
/*
* You need to expicitely add "void" to the argumet list.
* It defaults to "int" otherwise.
* Please do yourself a favor and switch all warnings on.
*/
void pop(void);
void clear(void);
void display(void);
void top_element(void);
void add(void);
void multiply(void);
void subtract(void);
void division(void);
void power(void);
/* Most checks and balances omitted! */
int main(void)
{
/* "int" to make things easier */
int input;
int flag = 1, anumber;
while (flag == 1) {
printf(": ");
/* get a(n ASCII) character */
input = fgetc(stdin);
if (isdigit(input)) {
anumber = 0;
/*
* We have a digit. Parse input for more digits until
* no further digits appear and add all digits to "anumber".
* We assume a decimal representation here.
*/
/* TODO: check for overflow! */
for (;;) {
anumber *= 10;
anumber += input - '0';
input = fgetc(stdin);
if (!isdigit(input)) {
break;
}
}
/* Push number on the stack */
if (top < SIZE) {
stack[top] = anumber;
top++;
} else {
printf("Error: stack overflow\n");
}
}
/* "input" from fgetc() is an integer, we can use a switch */
switch (input) {
case 'p':
pop();
break;
case 'c':
clear();
break;
case 'd':
display();
break;
case '=':
top_element();
break;
case '+':
add();
break;
case '^':
power();
break;
case 'q':
flag = 0;
break;
default:
printf("Error: invalid command\n");
break;
}
}
printf("Goodbye!\n");
return 0;
}
void pop(void)
{
if (top == 0)
printf("Error: stack is empty\n");
else
top--;
}
void clear(void)
{
top = 0;
}
void display(void)
{
int i;
if (top == 0)
printf("Error: stack is empty\n");
else {
for (i = top - 1; i >= 0; i--)
printf("%d\n", stack[i]);
}
}
void top_element(void)
{
printf("%d\n", stack[top - 1]);
}
void add(void)
{
if (top < 2)
printf("Error: not enough operands for the requested operation\n");
else {
int ans = stack[top - 1] + stack[top - 2];
stack[top - 2] = ans;
top--;
}
}
/* Using pow() from math.h is not a good idea beause it uses floating point */
/* TODO check for overflows! */
static int integer_pow(int x, int n)
{
int r;
r = 1;
while (n != 0) {
if (n & 1) {
r *= x;
}
x *= x;
n >>= 1;
}
return r;
}
void power(void)
{
if (top < 2)
printf("Error: not enough operands for the requested operation\n");
else {
int ans = integer_pow(stack[top - 2], stack[top - 1]);
stack[top - 2] = ans;
top--;
}
}
Test:
$ ./stackbcalc
: 123+23=
Error: not enough operands for the requested operation
: 23
: Error: invalid command
: q
Goodbye!
Does not work. Why? The function add() expects two operands on the stack. You need to put the + also on the stack (it is an integer) and once you are at the end with = you can evaluate the stack. You might need to learn something about infix/postfix/prefix notation to succesfully do so.
Hint: I would also ignore whitespace (space and tab, maybe even return) in the switch.

How can i generate a binary code table of a huffman tree?

I want to implement an function which gives me a binary code for each char in a huffman tree.
To implement the function i tried traversing the table by using a recursive function. However i don't know how to fill the result the binary code for each char so that the function returns an array of struct with all the chars and binary codes
I hope someone can point me in the right direction.
Thanks ahead!
Ok, let's see a possible solution:
#include <stdint.h>
typedef struct code {
size_t code_length;
uint32_t code;
} code;
void compute_code_table(tree_t node, code *t, code c)
{
if (node->left == NULL)
t[node->letter] = c;
else {
c.code_length++;
c.code <<= 1;
compute_code_table(node->left, t, c);
c.code += 1;
compute_code_table(node->right, t, c);
}
}
void code_print(code *c)
{
size_t n = c->code_length;
while (n --> 0)
putchar('0' + ((c->code >> n) & 1));
}
int main(void)
{
tree_t root = fixed_tree();
code table[256] = { 0 };
code c = { 0 };
compute_code_table(root, table, c);
for (size_t i = 0; i < 256; ++i) {
if (table[i].code_length) {
printf("%c\t", i);
code_print(table + i);
printf("\n");
}
}
}
Basically the idea is to have a table which is filled at every leaf. While doing the recursion we pass the current node, the table and the current code. If we are at a leaf we just store the code in the table, otherwise we need to perform the recursion: increase the code length, add a 0 in the least significant bit and do the left branch, then change that 0 to a 1 and do the right branch.
I would start by making compute_code_table recursive, this allows you to easily traverse the tree.
Secondly, it helps for every task or assignment to search online for some sources which explain (in pseudo-code or not) how to do your specific task. In this case, this yields the following explanation:
To generate a huffman code you traverse the tree to the value you
want, outputing a 0 every time you take a lefthand branch, and a 1
every time you take a righthand branch. (normally you traverse the
tree backwards from the code you want and build the binary huffman
encoding string backwards as well, since the first bit must start from
the top).
siggraph.org
In C, this could be implemented as such:
int compute_code_table_for_node(tree_t tree, node_t target_node, node_t current_node, int code_table) {
// Check for target
if ( current_node == target_node ) {
// Found target
return code_table;
}
// Check if end-node
if ( current_node->left == NULL && current_node->right == NULL ) {
// Is an end node
return -1;
}
// Try left
int left = compute_code_table_for_node(tree, target_node, current_node->left, code_table << 1 + 0);
// Try right
int right = compute_code_table_for_node(tree, target_node, current_node->right, code_table << 1 + 1);
// Find which path was taken
if ( left == -1 ) {
// Left path didn't find it, so it must be the right path:
return code_table << 1 + 1;
} else {
// Left path found it
return code_table << 1 + 0;
}
}
Then you only have to call compute_code_table_for_node(tree, node, tree->head, 0) for every node in the tree.
This piece of code won't work for your specific case, so you will have to rewrite it.

Trying to recursively binary search strings in c

I need to use a binary search to recursively find a target string. The function should return a -1 if it is not found and a positive integer if found but it always returns -1. thanks for the help!
int start = 0;
int search;
search = binary_search(strings, target, start, size-1);
if(search == -1)
{
printf("Not in the dataset!");
}
if(search != -1)
{
printf("%s is in the dataset", target);
}
int binary_search(char **strings, char *target, int start_idx, int end_idx)
{
if(end_idx < start_idx)
{
return -1;
}
int middle = ((start_idx + end_idx)/2);
int i;
i = strcmp(target, strings[middle]);
if(i == 0)
{
return middle;
}
if(i < 0)
{
return binary_search(strings, target, start_idx, middle-1);
}
else
{
return binary_search(strings, target, middle+1, end_idx);
}
}
input data:
aden
caden
david
erik
john
mark
matt
mycah
phil
susan
Although binary search is notoriously hard to get right, I don't see any errors in your algorithm as shown. You can still fail (-1) due to various causes that can not be determined based on the information provided.
1) Your source strings list is not actually sorted correctly -- strcmp() uses ASCII comparison, not dictionary comparison, i.e., your source string must be ASCII sorted for bsearch to be valid.
2) Your source strings are not well-formed NUL terminated C strings.
3) The target string does not have an exact match in the source string list. i.e., searching for "bill" will not match "Bill" or "billiard"
Just a note, a recursive bsearch is slower than and uses more memory than a non-recursive solution

Function that searches for difference between members of an array

I need to write a function that will return true if it has found a difference between members of an array.
My code is:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
I have to implement it with pointers.
The code above does not work(logically).
Can anybody help?
UPDATE:
I have changed my code to the following:
int func1(int *str)
{
int i,temp=0;
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
What is the problem with the new code?
This looks like homework to me, so I don't want to spoil the fun but one thing about C I'd like to mention: having a pointer to some array doesn't tell you anything about the size of the array. So your function will need to take a pointer and a second size_t argument (or maybe a pointer to the last element of the array).
Your function only takes in a single array pointer, that seems like one too few for a comparison.
You must add an argument that specifies the lengths of the arrays, or implement some kind of "policy" that e.g. terminates the arrays using a specific value.
You should also look into using the standard memcmp() function.
I don't understand the question (It's unclear what you're trying to achieve)...
As others have already said, there's no boundary checking on your array, which is wrong...
Here's some other feedback on your code:
// func1 - consider giving functions a meaningful name, it helps people to
// understand what the function is supposed to be doing....
// In this instance, it might have been helpful to identify what the expected
// return values / inputs of the function are...
int func1(int *str)
{
int i;
// Start a counter at 0, loop (adding 1) while
// the current value of the counter is less than, the value held in the
// array so, {1,2,3,4,0,7} Would terminate on the 0
// This: {1,20,7,14,0,7} Would also terminate on the 0
// This seems wrong, but again, it's unclear what you're trying to do here.
for(i=0;i<*(str+i);i++) {
// If the current element of the array
// is the same as the next element of the array
if(*(str+i) == *(str+i+1))
{
// return 1 - two numbers next to each other in the
// array are the same?
return 1;
}
}
// Either: The array contained a digit less than the counter,
// Or: It didn't contain two numbers that were the same next to each other.
// This seems a bit wrong?!?
return 0;
}
Your question could be improved (to get a more useful answer), if you showed what inputs you were expecting to return what return values.
Based on this 'I will need to write a function that will return true if its found diffrence between members of array.'
In pseudo code, it seems like you would want:
// Loop, checking we don't overflow. No point checking the last element as
// there's nothing after it to check...
for (count = 0 to arraysize -1) {
// If the current element != the next element, we've found a difference?!?
if(arrayElement[count] != arrayElement[count+1) {
return true
}
}
return false
UPDATE:
In your new code...
// You're still assuming the size of 'str'
int func1(int *str)
{
int i,temp=0;
// Loop while i < 9, i.e. 9 times.
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
// Maybe it should be (temp == 10-1), but I don't know where the
// 10 comes from...
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
This:
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
if( temp == 10 )
{
return 1;
}
}
Could be:
// return 0 (FALSE) on first difference
if(*(str+i) != *(str+i+1))
{
return 0;
}
If you changed the return 0 at the end of your function to return 1

How to sort a stack using only Push, Pop, Top, IsEmpty, IsFull?

Given a stack S, need to sort the stack using only Push, Pop, Top, IsEmpty, IsFull.
Looking for most simple solution.
Edited: Removed in place condition. Can't use another stack or queue.
For this problem, can we consider using system stack? Make several recursive calls.
public static void sort(Stack<Integer> s) {
if (!s.isEmpty()) {
Integer t = s.pop();
sort(s);
insert(t, s);
}
}
private static void insert(Integer x, Stack<Integer> s) {
if (s.isEmpty()) {
s.push(x);
return;
}
if (x < s.peek()) {
Integer t = s.pop();
insert(x, s);
s.push(t);
} else {
s.push(x);
}
}
It can be done...
Ok: sorted, ahem, "in-place" with only the listed ops, didn't need Top() or IsFull() or another stack or data structure other than the call frames. (Presumably the whole point of the homework problem was to require a recursive solution.)
Ruby
#a = [3, 2, 1, 6, 5, 4]
class Array
def empty?
return size == 0
end
end
def sort e
if #a.empty?
#a.push e
return
end
t = #a.pop
if e > t
#a.push(t).push(e)
return
end
sort e
#a.push t
end
def resort
return if #a.empty?
t = #a.pop
resort
sort t
end
p ['first ', #a]
resort
p ['final ', #a]
techInterview Discussion - Sorting on Stack
More pseudo than anything, but there is code examples and possible solution.
Its not possible.
That happens because you cant iterate through the stack, because it has to be in place (you could if you would use extra memory). So if you cant iterate through the stack you cant even compare two elements of the stack. A sort without comparing would need extra memory, so that cant be used either.
Also im sure its not homework, because i dont think a teacher would give you a problem that cant be solved.
If you really have to do it only with stacks, just use 1-2 extra temporary stacks (i think 2 are needed, but not 100% sure) and do it.
You can't. You can't reorder the contents of a stack without removing elements, by definition. Also push and pop aren't in-place operations, so basically you're asking to sort a stack with Top, IsEmpty and IsFull. IsEmpty = !IsFull. So you're asking to sort a stack with Top and IsEmpty.
What temporary data structures can you use?
With push and pop, and no temporary storage for n elements, accessing data near the bottom of the stack would be impossible without storing the rest -somewhere-.
If top (equiv to {x=pop();push(x);return x}) was replaced with shift, it would be perfectly doable - the stack would change into fifo (shift+push; pop would fall into disuse) and it would allow for an easy bubblesort on currently available elements.
To bad you couldn't have two other stacks, then you could have played the Towers of Hanoi in O(n) space.
//A java version
public static void sort(Stack<Integer> s){
if(s.size() > 0){
int tmp = s.pop();
sort(s);
sortFromBottom(s, tmp);
}
}
private static void sortFromBottom(Stack<Integer> s, Integer value){
if(s.size() == 0){
s.add(value);
}else{
int tmpValue = s.peek();
if(tmpValue < value){
s.pop();
sortFromBottom(s, value);
s.push(tmpValue);
}else{
s.push(value);
}
}
}
Bubble Sort and Insert Sort in Java
https://github.com/BruceZu/sawdust/blob/82ef4729ee9d2de50fdceab2c8976d00f2fd3ba0/dataStructuresAndAlgorithms/src/main/java/stack/SortStack.java
/**
* Sort the stack using only Stack API, without using other data structure
* Ascending from bottom to top
*/
public class SortStack<T extends Comparable<T>> {
int sorted;
/**
* Just Bubble Sort.
*/
private void bubble(Stack<T> s, T max) {
if (s.empty() || s.size() == sorted) {
s.push(max);
sorted++;
return; // note return
}
T currentTop = s.pop();
if (max.compareTo(currentTop) < 0) {
T tmp = max;
max = currentTop;
currentTop = tmp;
}
bubble(s, max);
s.push(currentTop);
}
public Stack<T> sortAscending(Stack<T> s) {
sorted = 0;
if (s == null || s.size() <= 1) {
return s;
}
while (sorted != s.size()) {
bubble(s, s.pop());
}
return s;
}
/**
* Just Insert Sort.
*/
private void insertSort(Stack<T> s) {
if (s.empty()) {
return;
}
T currentTop = s.pop();
insertSort(s);
insert(s, currentTop);
}
private void insert(Stack<T> s, T insert) {
if (s.isEmpty() || insert.compareTo(s.peek()) <= 0) {
s.push(insert);
return;
}
T current = s.pop();
insert(s, insert);
s.push(current);
}
public Stack<T> sortAscendingByInsertSort(Stack<T> s) {
if (s == null || s.size() <= 1) {
return s;
}
insertSort(s);
return s;
}
}
Sorting a stack without extra space is quite not a possibility .
At least not coming to my sane mind .
We can surely use the recursion stack as extra space over here .
The below approach might be helful .
My approach is O(N**2) . Over here I am iterating over stack N times, every time fixing the ith element in the stack .
Firstly fixed the bottom element by popping out N elements and pushing min_element and in
Second try fixed the 2nd element from bottom by popping out N-1 elements and pushing min_element except the one pushed before this
And so on .
Refer to the code below for more details .
stack<int> stk;
int sort_util(stack<int> &stk,int n,int mn)
{
if(n==0)
{
stk.push(mn);
return mn;
}
int vl = stk.top();
stk.pop();
int fmin = sort_util(stk,n-1,min(mn,vl));
if(fmin==vl)
return INT_MAX;
else
stk.push(vl);
return fmin;
}
void sort_stack(stack<int> &stk)
{
for(int i=stk.size();i>1;i--)
sort_util(stk,i,stk.top());
}

Resources