Counting Sort for a set - c++

Hello i know how couting sort works, how to implement it, But is it possible to implement it on a class who got 3 attributs and need to countSort the whole DisjointSet on a specific attribut.
If so, lets say i have this class:
class myStructure {
public:
int m_id = -1;
myStructure* m_parent = NULL;
int m_sortie = -1;
int m_echeance = -1;
myStructure() {}
myStructure(int id, myStructure* parent, int sortie, int echeance)
: m_id(id), m_parent(parent), m_sortie(sortie), m_echeance(echeance)
{ }
};
How can i implement the counting sort on the m_echance.
Thanks

Surely you can apply counting sort.
It is applicable to any field which can be mapped with integers. In general counting sort should be used if the range of values(in your case m_echeance) is small.
Below is high level approach to do that-
Let's say your objects are stored in array A[]
range of m_echeance is [0,R-1]
Make a count array.
loop through the array A to count frequencies of the objects with different m_echeance values.
something like count[A[i]->m_echeance + 1]++;
Get the cumulative frequencies for the count array.
Copy objects in auxiliary array based on cumulative frequencies.
Copy back objects from auxiliary array to original array.
Hope it helps!

Related

Finding a clean way to set a value in a node preferably using an algorithm

I have a range of bools in a vector and some vectors with a set size and I want to iterate over the larger vector and insert the values from the large bool vector into the smaller vectors in the nodes.
These are the smaller vectors. And the structure of the nodes
std::vector<BrainNode> _inputNodes;
std::vector <std::vector<BrainNode>> _hiddenNodes;
std::vector<BrainNode> _outputNodes;
class BrainNode
{
float _value{ 0 };
std::vector<bool> connections;
public:
bool operator[](size_t index);
};
Is there a nice algorithm mby a std::copy but with a predict or ranged move and removing the moved sub-range? I am happy to any input please share your ideas.
I was thinking of maybe using std::move and then rotating and remove but it seems messy.
I have done this, but I know this has to be a better way.
std::vector<bool> gaia::NeuralNet::set_input_nodes(std::vector<bool> nodeConactions)
{
uint i = 0;
for (BrainNode& node : _inputNodes)
{
node[nodeConactions[i++]];
}
auto it = std::rotate(nodeConactions.begin(), nodeConactions.begin()+i, nodeConactions.end());
nodeConactions.erase(it);
return nodeConactions;
}
Is there an algorithm that can remove that part that it moves from?
That works kinda like this?
v is a vector of bools and out is a vector of bools that is a data member in a class.
v.erese(std::algorithm(v.begin(),v.end(),v.begin()+n,out));
return v;

Organize integers by size?

I am relatively new to C++, and I am in need of some advice. I will try to keep it short. What is the simplest and best way of organizing integer values by their size? Then, I want to be able to use that information. My goal is basically, I can get an integer from a source, and then I want to organize the sources by the size of the integer value, and if two different sources has the same value I want the program to perform a bunch of code. Hopefully that made sense.
Any help would be greatly appreciated.
(By the size I mean the value, sorry for any inconvenience)
EDIT:
I don't have a sample code to show off unfortunately, but I will try to clarify what I am aiming for. I want to compare the speed of between 2-20 "characters" in a game. The fastest one will go first in the next part of the game, followed by the second fastest etc. If 2 "characters" has the same speed I want their starting position to be randomized (between them two). I have most of this pictured in my head, but I am mostly struggling to figure out how to sort the speed and know who had the highest speed value.
If the integers have to be unique (not 2 times the same integer in the container) and sorted, you might want to use a set
The next part of your question isn't very clear, but I'll try anyway.
If you want to know if a certain integer is already in your container, the best way is to go through said container and test every element, to do that a vector would do I guess, but since ordering is important, I would rather use a set or a priority_queue, but those are a little bit more complicated.
Now there's the "source" part. By source, do you mean input from exterior sources ? I think that's what you mean anyway. Basically you want a container storing "sources" by their values in ascending order, and when two get to the same value, do something.
The most natural and optimized way to do this would be to make your sources objects, and to overload the < operator in those objects, and then in that operator you can test if those objects have the same value to execute your 'bunch of code'.
Here a sample :
class Source
{
private:
int m_value; // The value of this source
public:
Source(int const& v) // setting the source's value
{
setValue(v);
}
int getValue() // Returns the sources value for comparison
{
return m_value;
}
int setValue(int const& v) // Sets the source's value
{
m_value = v;
}
// ... [Insert other methods here]
bool operator<(Source const& s) // Testing which source has the lowest value
{
if(m_value == s.m_value()) // If their values are equal
{
// Your code
}
return (m_value < s.m_value()); // Else we test if the other value's bigger
}
};
And then you can store these in a set, for example.
std::sort
Simple usage:
// intArray will be replaced by your collection of integers.
const int SIZE = 7;
int intArray[SIZE] = {5, 3, 32, -1, 1, 104, 53};
std::sort(intArray, intArray + SIZE);
cout << "Sorted Array looks like this." << endl;
for (size_t i = 0; i != SIZE; ++i)
cout << intArray[i] << " ";
This should print: -1 1 3 5 32 53 104
This article might be some help if you are new to stl: http://www.cplusplus.com/articles/NhA0RXSz/

From array to priority queue

I have items in array created from this struct:
struct ks{
int cap;
int val;
};
Array is named items and contains quantity of items.
items = new ks[quantity];
I want to put them in priority queue - which basically means sort them.
This is my compare function:
struct itemsCompare{
bool operator () (const ks &item1, const ks &item2){
if (item1.val/item1.cap > item2.val/item2.cap) return true;
return false;
}
};
How should creating of this queue looks like?
priority_queue <ks, What should I put here?, itemsCompare> comparedItems;
for(int i=0; i<quantity; i++) comparedItems.push(items[i]);
I know, that template requires having vector as container. How should I modify code to make it work? I know that I can put items into vector just before declaration of priority queue, but I'm curious if there's a way to do it just with array.
To create a std::priorty_queue from the array you can use
std::priority_queue <ks, std::vector<ks>, itemsCompare> comparedItems(items, items + quantity);
Answering the question as asked:
std::priority_queue <ks, std::vector<ks>, itemsCompare> comparedItems;
However, the question has some issues not directly asked. First, it sports division on uncontrolled substances :). What is going to happen if you divide by 0?
Second. You divide integer by integer. This result is always integer, and somehow I doubt this is what you want.

HashSet c++ clarification

I'm lost on this topic I have been studying. In my class we are implementing our own hash set class. Thus we have an underlying data structure , like a vector or array , and use a hash function to quickly determine whether an element is in the set it not . That is the part I do not follow. How would a hash function be used for this determination ?
imagine you have an underlying array of size 100, and you can only insert values from 0 to 99.
something like this:
class UselessHashMap
{
public:
void insert(int value){
_arr[hash(i)] = i;
}
private:
int hash(int i) { return i };
std::array<int,100> _arr;
}
now, imagine you want to store more than 100 elements, and you can't have an array that has an infinite (std::numeric_limits::max() )size.
In this case, your hash function will have to return you a value between 0-99, and of course your UselessHashMap class will need to take care of collisions as well, because that function could return the same value for different inputs.

Sorting eigenvectors by their eigenvalues (associated sorting)

I have an unsorted vector of eigenvalues and a related matrix of eigenvectors. I'd like to sort the columns of the matrix with respect to the sorted set of eigenvalues. (e.g., if eigenvalue[3] moves to eigenvalue[2], I want column 3 of the eigenvector matrix to move over to column 2.)
I know I can sort the eigenvalues in O(N log N) via std::sort. Without rolling my own sorting algorithm, how do I make sure the matrix's columns (the associated eigenvectors) follow along with their eigenvalues as the latter are sorted?
Typically just create a structure something like this:
struct eigen {
int value;
double *vector;
bool operator<(eigen const &other) const {
return value < other.value;
}
};
Alternatively, just put the eigenvalue/eigenvector into an std::pair -- though I'd prefer eigen.value and eigen.vector over something.first and something.second.
I've done this a number of times in different situations. Rather than sorting the array, just create a new array that has the sorted indices in it.
For example, you have a length n array (vector) evals, and a 2d nxn array evects. Create a new array index that has contains the values [0, n-1].
Then rather than accessing evals as evals[i], you access it as evals[index[i]] and instead of evects[i][j], you access it evects[index[i]][j].
Now you write your sort routine to sort the index array rather than the evals array, so instead of index looking like {0, 1, 2, ... , n-1}, the value in the index array will be in increasing order of the values in the evals array.
So after sorting, if you do this:
for (int i=0;i<n;++i)
{
cout << evals[index[i]] << endl;
}
you'll get a sorted list of evals.
this way you can sort anything that's associated with that evals array without actually moving memory around. This is important when n gets large, you don't want to be moving around the columns of the evects matrix.
basically the i'th smallest eval will be located at index[i] and that corresponds to the index[i]th evect.
Edited to add. Here's a sort function that I've written to work with std::sort to do what I just said:
template <class DataType, class IndexType>
class SortIndicesInc
{
protected:
DataType* mData;
public:
SortIndicesInc(DataType* Data) : mData(Data) {}
Bool operator()(const IndexType& i, const IndexType& j) const
{
return mData[i]<mData[j];
}
};
The solution purely relies on the way you store your eigenvector matrix.
The best performance while sorting will be achieved if you can implement swap(evector1, evector2) so that it only rebinds the pointers and the real data is left unchanged.
This could be done using something like double* or probably something more complicated, depends on your matrix implementation.
If done this way, swap(...) wouldn't affect your sorting operation performance.
The idea of conglomerating your vector and matrix is probably the best way to do it in C++. I am thinking about how I would do it in R and seeing if that can be translated to C++. In R it's very easy, simply evec<-evec[,order(eval)]. Unfortunately, I don't know of any built in way to perform the order() operation in C++. Perhaps someone else does, in which case this could be done in a similar way.