Selection Sort using a pointer and without loops - c

I am trying to use a recursive function to sort an array in ascending order. The catch is I can't use any for, while, or do/while loops. There are plenty of selection sort resources online but I'm having difficulty finding anything without loops and also including a pointer.
A short step-by-step of what I'm trying to do.
Place the marker at the first element of the array
2.If the marker is pointing at the last element of the array, then stop. Otherwise continue
3.Find the smallest element to the right of the marker
4.If this element is smaller than the element the marker is pointing at, then swap
5.Advance the marker to the next element to the right
6.Go to step 2

At the very least, you can design it using loops, and convert the loops.
Any loop can be converted into the following form:
State state = init();
while (cond(&state))
body(&state);
tail(&state);
And this loop be implemented trivially using recursion.
void recursive(State *state) {
if (!cond(state))
return;
body(state);
recursive(state);
}
State = state = init();
recursive(&state);
tail(&state);
That said, it's a lot easier to tackle this problem head on.
Selection sort is trivial to implement using recursion. As a whole, you are repeatedly sorting an ever shrinking portion of the array. After swapping the first element for smallest element, you need to sort the remainder of the array, which can easily be done using a recursive call.
That leaves the loop to find the smallest element of the array. Again, this is trivial to define in terms of itself. The smallest element of a list is the smallest of first element and the smallest element of the remainder of the list.

Related

what is the conventional way to represent snake when coding snake game in C?

A bit of context:
I have some experience with other programing languages, but when it comes to C my knowledge is not that big. I'm also attempting to make the snake game without relying on dynamic memory allocation which is not the part of std, as it is intended to run on a microcontroller.
I previously coded snake game in python, rust, and java and my go to approach was to store pairs of x and y coordinates in some form of dynamic list or vector. Every iteration of the game loop I would append the element to the list/vector of pairs based on the current last element and and respective dx and dy, and if the snake was not growing deleted or poped the first element of the vector/list, making the snake "move".
I was particularly fond of this approach, since it meant I'm not required to store my entire game field in a 2d array. It also was a very clean implementation in my opinion. Now in C, I have to major problems - no dynamically sized lists and ability to delete first element of the array and shifting all the elements back without iterating through all of the array.
For the first problem, I've considered either using a fixed size array with some limit which would be above reasonable snake length while keeping track of snake length separately, or using a linked list of structs which would contain a nullable pointer to itself. Latter one seems to be unnecessarily complex, while the first one seems like a very dirty fix.
For the second problem, I've considered overriding array pointer with the pointer to its second element, but while that semi worked - I'm concerned with following issues:
do I have to free the previous array pointer (a.k.a. the previous first element)
when doing something like this, I assume that the pointer to the array would keep on growing, and sooner or later it would segfault as it does not reuse the memory it already slided away from.
So I thought I should ask more experienced coders on a cleaner and more conventional ways to implement snake in C.
Thank you in advance,
There is an upper bound on the length of the snake -- the size of your 2d board. And this upper bound is very well achievable if your player is good at the game. Therefore you can preallocate an array of that size and use it as a pool for your linked-list nodes or a circular queue.
You can simplify further by using a 2d array for your board, and storing just the next/previous links within each cell where there's a snake. Then you don't need to store the x/y of each segment:
enum { TYPE_EMPTY, TYPE_FOOD, TYPE_SNAKE };
struct Cell { int type, next, prev; };
struct Cell board[width*height];
int head, tail;
This approach is easy to generalize to multiple players on the same board, multiple items or item types, etc.
There is nothing 'wrong' in storing an explicit 2d representation of your board. In fact it is a natural way to attack the problem. It allows fast checks for self-collisions, among other things. I bet your previous implementations resorted to a slow O(n) check to see if the snake self-intersects, which isn't pretty by itself.

Implement a stack using the first element of an array as top

I am implementing a stack in C. The task i have been given requires me to use the first element of the array as top.
For example:
If i have the struct:
struct stack {
int arr[MAX];
int top
};
I need to assign the first element of arr(i.e. arr[0]) to top and then implement the stack.
I don't get the question as top is usually assigned the value -1 and is accordingly incremented or decremented. What exactly do I need to do here?
This is a rather strange requirement, because the most natural way to implement the stack is using the last element of the array as the top by adding new elements at the end of the array and removing them from the end.
This way you will satisfy the LIFO requirement of the stack and also avoid moving the rest of the data in the array as you would have if you were adding and removing elements from the beginning of the array.
Also I'm not sure what is the top member of your struct is supposed to do, but the most natural thing to have here is some way to indicate what is the last element of the array currently is (i.e. the top of the stack). So it seems to me that the top member should contain the index of the last element in the array and by doing stack.arr[stack.top] you will retrieve the top element of the stack.

Remove a term from an array during a for loop

I've been creating a system for storing objects that persist for a specified duration, then remove themselves. However, I'm having some trouble figuring out how to remove expired items from the array while the for loop is running (to minimize extra iterations through the array)
Here is what I've made so far. Terms in the list are flagged with a Boolean value indicating that they're done.
For i = 0 To VisualEffects.Count - 1 Step 1
VisualEffects(i).Update(gt)
VisualEffects(i).Draw(sb, Pos, Cam)
If VisualEffects(i).CD.isExpired() Then
VisualEffects.RemoveAt(i)
i = -1
End If
Next
Why does this produce an error? How can I remove a term from an array and continue iterating through the remainder of the loop?
Regards
Ares
The line
i = -1
sets i to -1, causing the For loop to terminate.
If you can, reverse the order of the loop so that you start with the last array element and count down. That makes the remove logic much more straightforward.
.NET arrays are fixed-size so you can't actually remove an element from an array at all. You can change the value of an element, so you can set an element to Nothing to remove the object that it referred to, but the element is still there. If you read the MSDN documentation for the Array class, you'll see that the RemoveAt method throws a NotSupportedException for this reason.
If you're actually using a collection rather than an array then you can call RemoveAt but you need to loop from the last index to the first rather than first to last. That way, removing an item will not affect the indexes of those items that you are yet to visit.

Array Based Implementation of a Vector

Homework Assistance
Describe an array based implementation of a vector such that inserting and
removing at beginning and end of the vector can be done in constant time. Argue
convincingly.
Obviously this is impossible with a straight-up array. If you remove from the front, there will be a hole that needs to be filled in order to maintain the vector property. Of course, if we grab the next element over, we will need to do this n times, so the runtime will be linear, not constant.
Another way would be to grab the last element and stick it in the front, but what good is a data structure that scrambles your data?
What I have done so far is to create an array. The odd number indices are behind some point in the array (preferably the middle for size purposes, but it can be anywhere), then the even number indices are before that point. That takes up a whole bunch of memory and has lots of open slots if that special point is not the centre point. Worst case being 2n. However, it acts like there are no holes because it will always fill the next element out.
Insertion:
private int front = 0;
private int back = 0;
public void insertAtFront(int element)
{
(front+1));
dataArray[2*(front + 1) + 1] = element;
front++;
}
public void insertAtBack(int element)
{
dataArray[2*(back+1)] = element;
back++;
}
For removal, just decrement the front or the back. Then when accessing the array, only allow the values between front and back to be shown.
First, does this meet the requirements of a vector? Second, when removing, I am having some major issues figuring out how to get past that special centre point. Say you want to remove the entire array from the front, when you added everything from the back.
Thank you for any assistance.
The secret is to use two arrays. The end of the first array is the "front". The end of the second array is the "back".
I don't understand what you're trying to do with even and odd indices. But having a start index and an end index is basically the way to go - leave space empty at the front so that you can add elements there, and increment the start index again if you remove an element.
Another option is to use a circular array to allow you to add/remove both at the front and at the end efficiently.
There are other variations that could be applied: can you also find an implementation such that inserting/removing at the start, the end and (exactly) in the middle is efficient and has O(1) time?

Rearraging a rotated sorted array

I have seen several questions related to rotated sorted-arrays e.g. for searching for the pivot element or searching for an element in such an array.
However I did not find any question related to rearranging such an array to its original form without using sorting.
So my question: *Is there an efficient way, or trick, to rearrange a rotated, sorted-array to original form without using extra memory?
Heres what I would do..
I would find the starting element using a variation of binary search.
Once that is found , if you can use external memory, it can be done in O(n)
So the total time is O(lgn) + O(n) which is O(n)
Specifically to rotation: Seeing ajay's comments, I agree that since we have to rotate in place, the best option is bubble sort. Which is O(n*m) where m is number of elements rotated.
But if we can use some storage to keep the elements on either side of the starting element, basically, if we can use external memory, it just is a question of putting each element in the right place in the new array.

Resources