Rearraging a rotated sorted array - arrays

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.

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.

Selection Sort using a pointer and without loops

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.

How to get interpolated value for 1D array in LabVIEW?

I have two 1D arrays that gives an array of points on the XY plane. What I am trying to achieve is to find that steps interpolation for which values is exactly 0.5. I've tried to solve it using Interpolate 1D array and Threshold 1D array but no success. The first only returns values information for which steps == 0.5 and the latter is not doing anything apparently, returning 0 always.
I've attached the front panel and block diagram to the post. On the front panel I indicated which information I need.
Could you please help me figure out what I am doing wrong here? Because I'm quite stuck with this. Thank you in advance.
Kudos for solving it yourself, but a vi post of the solution would be appreciated for further reference by other people. Here is a solution that uses the 1D interpolation from the mathematics section. One VI, only downside is that you need to convert you interpolation value to an array and the answer back.
I managed to solve it. Threshold 1D array vi cannot deal with arrays that contain decreasing values... a rather frustrating error, as I need to transform the array so that the characteristics become increasing to obtain the interpolated value.
From the documentation:
Note Use this function only with arrays sorted in non-descending
order.

Using A* search algorithm to solve 3x3 three-dimensional box puzzle?

I am working on a 3x3 three-dimensional box puzzle problem in my homework. I will code with C.
There are 26 boxes and at first, first place is empty. By sliding boxes I must arrange them in correct order. Red numbers shows correct order and 27th place must be empty at last. I do not want you to give me code; I searched in forums and it seems that I must use the A* search algorithm, but how?
Can you give me tips about how I can use the A* algorithm on this problem? What type of data structure should I use?
Define your problem as a states-graph:
G=(V,E) where V=S={(x_1,x_2,...,x_54) | all possible states the 3d board can be in} [each number is representing a single 'square' on the 3d board].
and define E={(v1,v2)| it is possible to move from state v1 to state v2 with a single step} an alternative definition [identical] for E is by using the function successors(v):
For each v in V: successors(v)={all possible boards you can get, with 1 step from v}
You will also need an admissible heuristic function, a pretty good one for this problem can be: h(state)=Sigma(manhattan_distance(x_i)) where i in range [1,54]) basically, it is the summation of manhattan distances for each number from its target.
Now, once we got this data, we can start running A* on the defined graph G, with the defined heuristic. And since our heuristic function is admissible [convince yourself why!], it is guaranteed that the solution A* finds will be optimal, due to admissibility and optimality of A*.
Finding the actual path: A* will end when you develop the target state. [x_i=i in the terms we used earlier]. You will find your path to it by stepping back from the target to the source, using the parent field in each node.
You know how graphs work and how A* finds shortest paths on them, right?
The basic idea is that each configuration of the puzzle can be considered a vertex in a graph and the edges represent the moves (by connecting the configurations before and after the move).
Finding a set of moves that leads from an original configuration to a desired one can be seen as a path finding problem.

showing that any algorithm that accesses an array only by comparisons takes sigma(logn) steps

For this I think to properly solve it I need to show that sigma(logn) is its lower bound. I know all of the comparisons in my book run in O(nlogn), but im not sure how to form this into a concrete answer.
I think you've misread the problem: The array you are given is sorted. You are not sorting it. You are accessing it. Let's play a game. I pick a US state and you try to guess it. Every guess I will tell you if my chosen state is alphabetically before or after your guessed state. How many guesses do you need? The problem gives you a great clue with binary search.
Add this to your general algorithm toolbox: To show a lower bound is valid (but not necessarily tight), assume there exists an upper bound that is smaller, and do a proof by contradiction. For your problem, this should be doable.

Resources