Multiplying pointer address - c

So basically bst in this case is a float pointer (I am using it for an array implementation of a binary search tree). I need to insert elements, left node = 2i, right node = 2i+1, so bst=bst*2 means I am trying to change the pointer of the current index of the array. It doesn't work. How do I make it work? Addition of pointers is allowed yet not multiplicatoin. Why?!
For more information, see my whole program.

Multiplication on pointers isn't allowed because there's no use for it. If you have a variable that's located at, say, address 0x4f2c18e9 — that's a pointer value — there's no reason to expect that address 0x9e5831d2 (that's 0x4f2c18e9 * 2) is a valid place to store data.

the bst + 1 means "the next float after this float", the compiler knows bst is a float, so it knows how many distance should move to get the next element.
But what is a "Multiply to pointer"? does it has a meaning?
If you means the two times far from the beginning of an array, then it's a index concept. As an array index, like arr[i * 2 + 1], it first calculate the i * 2 + 1 which means the distance, then apply it to the [] operator.
So, if you want to do something like this, you should first calculate the distance from this element to the beginning, then do your multiplying, then add it back in the final. An sample code is as follow:
BStree bst, h;
......
size_t i = bst - h;
BStree pLeftNode = bst + i * 2;

What you're doing is using recursion to keep the base on the bottom of the stack and pushing on the next location using your BStree. You just pass on the next location using a simple test:
void bstree_insert(BStree bst, float key){
long int ibst = (int)bst;
ibst *= 2;
float * nbst = (float *)ibst;
if(*bst == -1)
*bst = key;
else if(*bst == key)
;
else if(*bst > key)
bstree_insert(nbst+1, key);
else if(*bst < key)
bstree_insert(nbst+2, key);
return;
}
From the way you've described it, this is what you want.
HOWEVER!
I don't think your instructor would want you messing with memory like this. It's not something any level of programmer should be doing unless you want your computer to turn into a transformer, change into Optimus Prime, and kick your tush into next year.
So...I would suggest that you go back and carefully re-read the instructions for your problem.

Related

find nth element from the last in a list using recursion

we can solve this problem in, say C, using a static variable, like in the snippet below (like the function found in this page).
static int i = 0;
if(head == NULL)
return;
getNthFromLast(head->next, n);
if(++i == n)
{THIS IS THE NTH ELEM FROM LAST
DO STUFF WITH IT.
}
I'm trying to see if I can solve this using a tail call recursion,
and NO static variables/global variables.
I'm trying to learn Haskell was wondering how to implement this in a purely functional way, with out using Haskell's length and
!! something like x !! ((length x) - K).
So started by asking, how we can do it in C, with recursion and NO static/global variables, just to get some idea.
Any suggestions/pointers would be appreciated.
Thanks.
The linked page explains how to solve the problem with a two-finger solution; it's a bit surprising that they don't simply write the recursive version, which would be simple and clear. (In my experience, you don't succeed at interviews by providing tricky and obscure code when there is a simple and clear version which is equally efficient. But I suppose there are interviewers who value obscure code.)
So, the two-finger solution is based on the observation that if we have two pointers into the list (the two fingers), and they are always n elements apart because we always advance them in tandem, then when the leading finger reaches the end of the list, the trailing finger will point at the element we want. That's an easy tail recursion:
Node* tandem_advance(Node* leading, Node* trailing) {
return leading ? tandem_advance(leading->next, trailing->next)
: trailing;
}
For the initial case, we need the leading finger to be N elements from the beginning of the list. Another simple tail recursion:
Node* advance_n(Node* head, int n) {
return n ? advance_n(head->next, n - 1)
: head;
}
Then we just need to put the two together:
Node* nth_from_end(Node* head, int n) {
return tandem_advance(advance_n(head, n + 1), head);
}
(We initially advance by n+1 so that the 0th node from the end will be the last node. I didn't check the desired semantics; it might be that n would be correct instead.)
In Haskell, the two-finger solution seems to be the obvious way. This version will go wrong in various ways if the requested element isn't present. I'll leave it as an exercise for you to fix that (hint: write versions of drop and last that return Maybe values, and then string the computations together with >>=). Note that this takes the last element of the list to be 0th from the end.
nthFromLast :: Int -> [a] -> a
nthFromLast n xs = last $ zipWith const xs (drop n xs)
If you want to do some of the recursion by hand, which No_signal indicates gives better performance,
-- The a and b types are different to make it clear
-- which list we get the value from.
lzc :: [a] -> [b] -> a
lzc [] _ = error "Empty list"
lzc (x : _xs) [] = x
lzc (_x : xs) (_y : ys) = lzc xs ys
nthFromLast n xs = lzc xs (drop n xs)
We don't bother writing out drop by hand because the rather simple-minded version in the library is about the best possible. Unlike either the first solution in this answer or the "reverse, then index" approach, the implementation using lzc only needs to allocate a constant amount of memory.
I assume your code is missing
getNthFromLast(list *node_ptr, int n) {
right at the top. (!!)
Your recursive version keeps track of node_ptrs in its call stack frames, so it is essentially non tail-recursive. Moreover, it continues to unwind the stack (go back up the stack of call frames), while incrementing the i and still checking its equality to n, even after it had found its goal nth node from the last; so it is not efficient.
That would be an iterative version, indeed encodable as tail-recursive, that does things on the way forward, and so can stop immediately after reaching its target. For that, we open up the n-length gap from the start, not after the end is reached. Instead of counting backwards as your recursive version does, we count forward. This is the same two-pointers approach already mentioned here.
In pseudocode,
end = head;
repeat n: (end = end->next);
return tailrec(head,end)->payload;
where
tailrec(p,q) {
if(NULL==q): return p;
else: tailrec(p->next, q->next);
}
This is 1-based, assuming n <= length(head). Haskell code is already given in another answer.
This technique is known as tail recursion modulo cons, or here, modulo payload-access.
nthFromLast lst n = reverse lst !! n
Because Haskell is lazy, this should be sufficiently efficient
If you don't want to use !!, you'll have to redefine it yourself, but this is silly.
The typical iterative strategy uses two pointers and runs one to n - 1 before starting to move the other.
With recursion, we can instead use the stack to count back up from the end of the list by adding a third argument. And to keep the usage clean, we can make a static helper function (in this sense it means only visible within compilation unit, a totally different concept to a static variable with function scope).
static node *nth_last_helper(node* curr, unsigned int n, unsigned int *f) {
node *t;
if (!curr) {
*f = 1;
return NULL;
}
t = nth_last_helper(curr->next, n, f);
if (n == (*f)++) return curr;
return t;
}
node* nth_last(node* curr, unsigned int n) {
unsigned int finder = 0;
return nth_last_helper(curr, n, &finder);
}
Alternatively we could actually do the counting without the extra parameter, but I think this is less clear.
static node *nth_last_helper(node* curr, unsigned int *n) {
node *t;
if (!curr) return NULL;
t = nth_last_helper(curr->next, n);
if (t) return t;
if (1 == (*n)--) return curr;
return NULL;
}
node* nth_last(node* curr, unsigned int n) {
return nth_last_helper(curr, &n);
}
Note that I have used unsigned integers to avoid choosing semantics for the "negative nth last" value in a list.
However, neither of these are tail recursive. To achieve that, you can more directly convert the iterative solution into a recursive one, as in rici's answer.

How can I get a boolean out of a reiteration

I made this binary search using reiteration, however, when I get the answer (boolean), I seem to stumble in my way out of the reiteration and cant get the correct answer out of the function.
Can anybody help? Please comment on the code.
// binary search
bool
search(int value, int array[], int n)
{
// the array has more than 1 item
if (n > 1)
{
int m = (n/2);
// compares the middle point to the value
if (value == array [m])
return true;
// if the value given is lower than the middle point of the array
if (value < array [m])
{
int *new_array = malloc (m * sizeof(int));
// creating a new array with the lower half of the original one
memcpy(new_array, array, m * sizeof(int));
// recalling the function
search (value, new_array, m);
}
// if the value given is greater than the middle point of the array
else
{
int *new_array = malloc (m * sizeof(int));
// creating a new array with the upper half of the original one
memcpy(new_array, array + (m + 1), (m * sizeof(int)));
// recalling the function
search (value, new_array, m);
}
}
else if (n==1)
{
// comparing the one item array with the value
if (array[0] == value)
return true;
else
return false;
}
if (true)
return true;
else
return false;
}
You need to return the value of recursive searches.
return search (value, new_array, m);
Otherwise when you call search you are just throwing away the answer
You should return search(...);, and not only invoke the search() method - otherwise the return value is not bubbled up.
In addition, note that this algorithm is O(n) (linear in the size of the array) and is leaking memory and very inefficient, since you copy half of the array in each iteration.
Actually, It probably makes the algorithm much slower then the naive linear search for an element.
A good binary search does not need to copy half of the array - it just "looks" at half of it. It can be achieved by sending array+m as the array (for the higher half), and only decreasing n is enough for the lower half.
As mentioned by amint copying the array completely defeats the purpose of doing a binary search. Second, I believe you mean recursion, not reiteration.
Things to think about: Instead of copying the array, think about how you could achieve the same result by passing in a set of indexes to the array (like beginning and end).
As to your actual question, how to return the boolean value through the recursion. The thing about returning values out of a recursive function is that each iteration has to pass along the value. You can think of it like a chain of responsibility delegation. The first call is like the head of the company. He doesn't do all of the work, so he delegates it to his assistant but he does one piece of the work first. Then the assistant has an assistant etc. Turtles all the way down ;)
In order to get a value back though, each person in the chain has to give it back to the person before them. Going back to programming, this means that every time you recursively call search, you need to return that value.
Lastly, once you have those things in order you need to get your base case better defined. I assume that's what you're trying to do with
if (true)
return true;
else
return false;
However, as pointed out by H2CO3, this doesn't make much sense. In fact, your previous if statement if (n == 1) ... should make sure that the code after that is never executed.

Should Binary Heap be a binary tree or linked list?

I have an assignment to implement a binary heap. However, I'm not sure whether I should implement the binary heap as a binary tree data structure or a simple double linked list.
If I should implement as a binary tree, how should I keep track of the last element of the tree in order to insert a new element? In linked list that would be much easier.
So, does binary heap have to be a binary tree? If yes, how to track the last element?
Note: In my assignment there is a statement like this:
But you will implement the binary heap not as an array, but
as a tree.
To be more clear this is my node:
struct Word{
char * word;
int count;
struct Word * parent;
struct Word * left_child;
struct Word * right_child;
}
Solution taken from the question.
by #Yunus Eren Güzel
SOLVED:
After five hours of study I have found a way to implement heap as a pointer based tree.
The insertion algorithm is :
insert
node = create_a_node
parent = get_the_last_parent
node->parent = parent
if parent->left==NULL
parent->left=node
else
parent->right=node
end insert
get_last_parent parent,&height
height++
if parent->left==NULL || parent->right==NULL
return parent;
else
int left_height=0,right_height=0;
left = get_last_parent(parent->left,&left_height)
right = get_last_parent(parent->right,&right_height)
if left_height == right_height
height += right_height
return right
else if left_height > right_height
height += left_height
return left
end get_last_parent
A binary heap is, by definition, a binary tree. One way of implementing this in C is to store the tree elements in an array where the array index corresponds to the tree element (numbering the root node 0, its left child 1, its right child 2, and so on). You can then just store the size of the heap (initialized to 0 upon creation and incremented whenever an element is added) and use that to find the next open location.
For basic data structures questions like this, Wikipedia is your friend.
You should implement it as a tree. It will be easy and interesting. Heap has only property that any node has value less than or equal to its parent, if it is a max heap.
In array implementation we impose some more conditions.
If you need help about specific function implementation then you can ask it.
You need to travel down to add new node
call it with root, value to be inserted
insert(node, x){
if(node->value >= x)
//insert
if(node->left == 0)
node->left = new Node(x);
else if(node->right == 0)
node->right = new Node(x);
else if(node->left->value >= x)
insert(node->left, x);
else if(node->right->value >= x)
insert(node->right, x);
else
//insert between node and its any one child
insertBW(node, node->left, x);
else //if x is less than node value
//insert between node and its parent
insertBW(node->parent, node, x)
}
insertBW(p, c) is a function which insets a node containing value x between p and c
(I didn't tested this code please check for errors)
insertBW(Node* p, Node* c, T x)
{
Node* newnode = new Node(x);
newNode.x = x;
if(p == 0) //if node c is root
{
newnode.left = Tree.root.left;
Tree.root = newnode;
}
else
{
newnode.parent = p;
newnode.child = c;
if(p.left == c)
{
p.left = newnode;
}
else p.right = newnode;
}
}
This to me really seems to be a homework question & it seems you have not done any R&D on your own before asking (sorry for bit harsh words):)
In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if B is a child node of A, then key(A) ≥ key(B).
I think your teacher wants you to implement a priority queue data structure and that's where you are talking about both a Linked List and Heap together in the same question. Priority Queue can be implemented as a Heap or a Linked List where in to extract elements based on priority either you have to maintain elements sorted in case of linked list where say a maximum or minimum element goes at the front based upon whether you are implementing a max heap or a min heap OR priority queue can be implemented simply as a heap data structure.
Coming to the last point where you say "But you will implement the binary heap not as an array, but as a tree.", seems to be very irrelevant. Please do check again as to what is required or reproduce the exact question that has been asked in your assignment.
To put it simply, regarding your first question - no. A heap can be anything (array, linked list, tree, and when one must improvise a family of fluffy kittens). Note the definition of a heap: If "B" is a child of "A" then val(A) >= val(B) (or, in case of a min-heap, val(A) <= val(B)).
It's most common to refer to it as a tree (and also implement it as such) because it's easy to think of it as a tree. Also, the time-complexity & performance are good.
Regarding your second question, you gave no information, so as far as I know a solution that searches every node is as good as any other...
For any better answer, more information is required (what limitations do you have, what operations should you support, etc...)
A binary heap can be anything i.e. array, linked list, tree, etc. We just have to keep the right algorithm on how can you can access the data. For example, if you want to make it to the left child you can do this by 2N + 1(For starting index 0) where N is the parent index or the right child by 2N + 2. For the last element, you can initialise the heap with a variable count and increment it by 1 every time you insert a new element, this way you can keep track of the last element (Same for delete, just some modification has to be made on the collection).

find element in the middle of a stack

I was asked this question in an interview.The problem was i would be given a stack and have to find the element in the middle position of the stack."top" index is not available (so that you don't pop() top/2 times and return the answer).Assume that you will reach the bottom of the stack when pop() returns -1.Don't use any additional data structure.
Eg:
stack index
-----
2 nth element
3
99
.
1 n/2 th element
.
-1 bottom of the stack(0th index)
Answer: 1 (I didn't mean the median.Find the element in middle position)
Is recursion the only way?
Thanks,
psy
Walk through the stack, calculate the depth and on the way back return the appropriate element.
int middle(stack* s, int n, int* depth) {
if (stack_empty(s)) {
*depth = n;
return 0; //return something, doesn't matter..
}
int val = stack_pop(s);
int res = middle(s, n+1, depth);
stack_push(s, val);
if (n == *depth/2)
return val;
return res;
}
int depth;
middle(&stack, 0, &depth);
Note: yes, recursion is the only way. Not knowing the depth of the stack means you have to store those values somewhere.
Recursion is never the only way ;)
However, recursion provides you with an implied additional stack (i.e. function parameters and local variables), and it does appear that you need some additional storage to store traversed elements, in that case it appears that recursion may be the only way given that constraint.
"... Don't use any additional data structure. ..."
Then the task is unsolvable, because you need some place where to store the popped-out data. You need another stack for recursion, which is also a data structure. It doesn't make sense to prohibit any data structure and allow recursion.
Here is one solution: Take two pointers, advance one of them two steps at a time (fast), the other one only one step at a time (slow). If the fast one reaches the bottom return the slow pointer which points to the middle index. No recursion required.
int * slow = stack;
int * fast = stack;
while(1) {
if(STACK_BOTTOM(fast)) return slow;
fast--;
if(STACK_BOTTOM(fast)) return slow;
slow--;
fast--;
}
Recursion seems to be the only way. If you try to use the fast and slow pointer concept during popping, you will need to store the values somewhere and that violates the requirement of no additional data structure.
This question is tagged with c, so for the c programming language I agree that recursion is the only way. However, if first class anonymous functions are supported, you can solve it without recursion. Some pseudo code (using Haskell's lambda syntax):
n = 0
f = \x -> 0 # constant function that always returns 0
while (not stack_empty) do
x = pop
n = n+1
f = \a -> if (a == n) then x else f(a)
middle = f(n/2) # middle of stack
# stack is empty, rebuilt it up to middle if required
for x in (n .. n/2) do push(f(x))
Please note: during the while loop, there's no (recursive) call of f. f(a) in the else branch is just used to construct a new(!) function, which is called f again.
Assumed the stack has 3 elements 10, 20, 30 (from bottom to top) this basically constructs the lambda
(\a -> if a==1
then 30
else (\b -> if b==2
then 20
else (\c -> if c==3
then 10
else (\d -> 0)(c)
)
(b)
)
(a)
)
or a little bit more readable
f(x) = if x==1 then 30 else (if x==2 then 20 else (if x==3 then 10 else 0))

C get mode from list of integers

I need to write a program to find the mode. Or the most occurrence of an integer or integers.
So,
1,2,3,4,1,10,4,23,12,4,1 would have mode of 1 and 4.
I'm not really sure what kind of algorithm i should use. I'm having a hard time trying to think of something that would work.
I was thinking of a frequency table of some sort maybe where i could go through array and then go through and create a linked list maybe. If the linked doesn't contain that value add it to the linked, if it does then add 1 to the value.
So if i had the same thing from above. loop through
1,2,3,4,1,10,4,23,12,4,1
Then list is empty so add node with number = 1 and value = 1.
2 doesnt exist so add node with number = 2 and value = 1 and so on.
Get to the 1 and 1 already exists so value = 2 now.
I would have to loop through the array and then loop through linked list everytime to find that value.
Once i am done then go through the linked list and create a new linked list that will hold the modes. So i set the head to the first element which is 1. Then i go through the linked list that contains the occurences and compare the values. If the occurences of the current node is > the current highest then i set the head to this node. If its = to the highest then i add the node to the mode linked list.
Once i am done i loop through the mode list and print the values.
Not sure if this would work. Does anyone see anything wrong with this? Is there an easier way to do this? I was thinking a hash table too, but not really sure how to do that in C.
Thanks.
If you can keep the entire list of integers in memory, you could sort the list first, which will make repeated values adjacent to each other. Then you can do a single pass over the sorted list to look for the mode. That way, you only need to keep track of the best candidate(s) for the mode seen up until now, along with how many times the current value has been seen so far.
The algorithm you have is fine for a homework assignment. There are all sorts of things you could do to optimise the code, such as:
use a binary tree for efficiency,
use an array of counts where the index is the number (assuming the number range is limited).
But I think you'll find they're not necessary in this case. For homework, the intent is just to show that you understand how to program, not that you know all sorts of tricks for wringing out the last ounce of performance. Your educator will be looking far more for readable, structured, code than tricky optimisations.
I'll describe below what I'd do. You're obviously free to use my advice as much or as little as you wish, depending on how much satisfaction you want to gain at doing it yourself. I'll provide pseudo-code only, which is my standard practice for homework questions.
I would start with a structure holding a number, a count and next pointer (for your linked list) and the global pointer to the first one:
typedef struct sElement {
int number;
int count;
struct sElement *next;
} tElement;
tElement first = NULL;
Then create some functions for creating and using the list:
tElement *incrementElement (int number);
tElement *getMaxCountElement (void);
tElement *getNextMatching (tElement *ptr, int count);
Those functions will, respectively:
Increment the count for an element (or create it and set count to 1).
Scan all the elements returning the maximum count.
Get the next element pointer matching the count, starting at a given point, or NULL if no more.
The pseudo-code for each:
def incrementElement (number):
# Find matching number in list or NULL.
set ptr to first
while ptr is not NULL:
if ptr->number is equal to number:
return ptr
set ptr to ptr->next
# If not found, add one at start with zero count.
if ptr is NULL:
set ptr to newly allocated element
set ptr->number to number
set ptr->count to 0
set ptr->next to first
set first to ptr
# Increment count.
set ptr->count to ptr->count + 1
def getMaxCountElement (number):
# List empty, no mode.
if first is NULL:
return NULL
# Assume first element is mode to start with.
set retptr to first
# Process all other elements.
set ptr to first->next
while ptr is not NULL:
# Save new mode if you find one.
if ptr->count is greater than retptr->count:
set retptr to ptr
set ptr to ptr->next
# Return actual mode element pointer.
return retptr
def getNextMatching (ptr, number):
# Process all elements.
while ptr is not NULL:
# If match on count, return it.
if ptr->number is equal to number:
return ptr
set ptr to ptr->next
# Went through whole list with no match, return NULL.
return NULL
Then your main program becomes:
# Process all the numbers, adding to (or incrementing in) list .
for each n in numbers to process:
incrementElement (n)
# Get the mode quantity, only look for modes if list was non-empty.
maxElem = getMaxCountElement ()
if maxElem is not NULL:
# Find the first one, whil exists, print and find the next one.
ptr = getNextMatching (first, maxElem->count)
while ptr is not NULL:
print ptr->number
ptr = getNextMatching (ptr->next, maxElem->count)
If the range of numbers is known in advance, and is a reasonable number, you can allocate a sufficiently large array for the counters and just do count[i] += 1.
If the range of numbers is not known in advance, or is too large for the naive use of an array, you could instead maintain a binary tree of values to maintain your counters. This will give you far less searching than a linked list would. Either way you'd have to traverse the array or tree and build an ordering of highest to lowest counts. Again I'd recommend a tree for that, but your list solution could work as well.
Another interesting option could be the use of a priority queue for your extraction phase. Once you have your list of counters completed, walk your tree and insert each value at a priority equal to its count. Then you just pull values from the priority queue until the count goes down.
I would go for a simple hash table based solution.
A structure for hash table containing a number and corresponding frequency. Plus a pointer to the next element for chaining in the hash bucket.
struct ItemFreq {
struct ItemFreq * next_;
int number_;
int frequency_;
};
The processing starts with
max_freq_so_far = 0;
It goes through the list of numbers. For each number, the hash table is looked up for a ItemFreq element x such that x.number_ == number.
If no such x is found, then a ItemFreq element is created as { number_ = number, frequency_ = 1} and inserted into the hash table.
If some x was found then its frequency_ is incremented.
If frequency_ > max_freq_so_far then max_freq_so_far = frequency
Once traversing through the list of numbers of complete, we traverse through the hash table and print the ItemFreq items whose frequency_ == max_freq_so_far
The complexity of the algorithm is O(N) where N is the number of items in the input list.
For a simple and elegant construction of hash table, see section 6.6 of K&R (The C Programming Language).
This response is a sample for the idea of Paul Kuliniewicz:
int CompInt(const void* ptr1, const void* ptr2) {
const int a = *(int*)ptr1;
const int b = *(int*)ptr2;
if (a < b) return -1;
if (a > b) return +1;
return 0;
}
// This function leave the modes in output and return the number
// of modes in output. The output pointer should be available to
// hold at least n integers.
int GetModes(const int* v, int n, int* output) {
// Sort the data and initialize the best result.
qsort(v, v + n, CompInt);
int outputSize = 0;
// Loop through elements while there are not exhausted.
// (look there is no ++i after each iteration).
for (int i = 0; i < n;) {
// This is the begin of the new group.
const int begin = i;
// Move the pointer until there are no more equal elements.
for (; i < n && v[i] == v[begin]; ++i);
// This is one-past the last element in the current group.
const int end = i;
// Update the best mode found until now.
if (end - begin > best) {
best = end - begin;
outputSize = 0;
}
if (end - begin == best)
output[outputSize++] = v[begin];
}
return outputSize;
}

Resources