I'm trying to solve a Josephus problem where, in addition to the value of the remaining element, I need to return its index in the original list. I implemented the list myself and it works well, I get the value correctly, but I can’t figure out how to get the index from the original array!
Can anyone explain this to me please?
My code:
#include "circular_linked_list.h"
enum class direction { clockwise, counterclockwise };
template<typename T>
std::pair<int, T> Josephus_problem(CircularLinkedList<T> list, direction dir, unsigned step) {
if (list.getLength() == 0) {
throw std::invalid_argument("List is empty");
}
int currentIndex = 0;
int size = list.getLength();
int finalIndex = 0;
while (list.getLength() > 1) {
if (dir == direction::counterclockwise) {
finalIndex -= step + 1;//???
currentIndex = (currentIndex - step + 1) % list.getLength();
} else {
finalIndex += step - 1;//???
currentIndex = (currentIndex + step - 1) % list.getLength();
}
list.removeAt(currentIndex);
}
finalIndex = ...;//Don't know what to do here!
return {finalIndex, list[0]};
}
Pretty much this:
Initialize a std::list of unsigned integers (size_t) that represent the index of each element in the list from 0 to N-1.
Then just iterate through the list one by one. Each time you hit the STEPth element, you erase it. You can take advantage of the fact that
list.eraseon a position element will return the next item after.Here's the simple logic:
And you can take advantage of reverse iterators for the counterclockwise operations. Some small tweaks to the above logic to make it work for reverse iterations.
In both cases, the "last remaining index" is this: