I have a "raffle" C++ program that I use to "draw out of a hat". I receive an EXC_BAD_ACCESS signal when I try to use it, though. Here is the function:
vector<int> speedRaffle(vector<Player>players,int pNum){
vector<int> spdtics,order;
int ticnum,randy;
vector<int>::iterator iter = spdtics.begin();
for (int k=0;k<pNum;k++){
for (int i=0; i<pNum; i++) {
for (int j=0; j<pow(players[i].speed,2); j++){
for (int io=0; io<order.size(); io++) {
if(order[io]!=i){
spdtics.push_back(i);
ticnum++;
}
}
}
}
randy=random() % ticnum;
for(int i=0;i<randy;i++){
iter++;
}
order[k]=*iter; //Thread 1: Program received signal: "EXC_BAD_ACCESS".
iter=spdtics.begin();
}
return order;
}
This function should take all of the players' speeds and square them. Then, it puts that many (the squares of speeds) "raffle tickets" into spdtics. It then randomly draws one "ticket" from spdtics, and puts the number of the player who owned the ticket into order. Then, it repeats again until all players have been drawn, not drawing the same player twice. It returns the order in which the players won.
The class Player contains an int speed. I call this function like this:
order=speedRaffle(players,pNum);
where players is vector and pNum is int. What am I doing wrong?
1. You are trying to access element at index k in empty vector order
It crashes because vector order is empty when you call order[k] = *iter;, you should use push_back function instead: order.push_back(*iter);.
2. You use loop for "moving" iterator instead of simple advance call
advance(iter, randy - 1); has same effect as this loop: for(int i=0;i<randy;i++){ iter++; }.
3. You call pow in every single iteration
for (int j=0; j<pow(players[i].speed,2); j++)
Note, that this would be much faster:
int maxspeed = pow(players[i].speed,2);
for (int j = 0; j < maxspeed; j++)
4. Elements in vector can be accessed directly by using index
You don't need any iterator at all in this case.
5. Passing vector by value instead of passing it by reference
vector<int> speedRaffle(vector<Player>players,int pNum)
Note, that copy of vector players is created every time you call this function. You don't want to do that. You also don't want to change this vector inside of function, so declaring this argument as const would be much better:
vector<int> speedRaffle(const vector<Player>& players, int pNum)
6. Your code does not do what you need it to do
"It should take all of the players' speeds and square them. Then, it puts that many (the squares of speeds) "raffle tickets" into spdtics. It then randomly draws one "ticket" from spdtics, and puts the number of the player who owned the ticket into order. Then, it repeats again until all players have been drawn, not drawing the same player twice. It returns the order in which the players won."
According to this, your function should look like this:
vector<int> speedRaffle(vector<Player>& players)
{
// create vector of tickets:
set<int> ticketOwners;
vector<int> spdtics;
for (int i = 0; i < players.size(); i++)
{
ticketOwners.insert(i);
int maxspeed = pow(players[i].speed,2);
for (int j = 0; j < maxspeed; j++)
{
spdtics.push_back(i);
}
}
// draw ticket for every player:
vector<int> order;
while (!ticketOwners.empty())
{
set<int>::const_iterator to;
int randy;
do
{
randy = random() % spdtics.size();
to = ticketOwners.find(spdtics[randy]);
}
while (to == ticketOwners.end());
spdtics.erase(spdtics.begin() + randy);
order.push_back(*to);
ticketOwners.erase(to);
}
return order;
}
Also note that you don't need pNum argument if it's equal to players.size().
Hope this will help you.
Related
Let's say I have a vector of integers:
vector<int> v(n);
Which I fill up in a for loop with valid values. What I want to do is to find a index of a given value in this vector. For example if I have a vector of 1, 2, 3, 4 and a value of 2, i'd get a index = 1. The algorithm would assume that the vector is sorted in ascending order, it would check a middle number and then depending of it's value (if its bigger or smaller than the one we're asking for) it would check one of halves of the vector. I was asked to do this recursive and using pointer. So I wrote a void function like:
void findGiven(vector<int> &v){
int i = 0;
int *wsk = &v[i];
}
and I can easily access 0th element of the vector. However I seem to have some basic knowledge lacks, because I can't really put this in a for loop to print all the values. I wanted to do something like this:
for (int j = 0; j<v.size(); j++){
cout << *wsk[j];
}
Is there a way of doing such a thing? Also I know it's recurisve, I'm just trying to figure out how to use pointers properly and how to prepare the algorithm so that later I can build it recursively. Thanks in advance!
The correct way is:
for (int wsk : v) {
cout << wsk;
}
If you insist on pointers:
int* first = v.data();
for (size_t j = 0; j < v.size(); ++j) {
cout << first[j];
}
So, I tried to make an array using input first, then sorting it out from smallest to biggest, then display the array to monitor.
So I come up with this code :
#include <iostream>
using namespace std;
void pancakeSort(int sortArray[], int sortSize);
int main()
{
// Input The Array Element Value
int pancake[10];
for(int i=0; i<10; i++)
{
cout << "Person " << i+1 << " eat pancakes = ";
cin >> pancake[i];
}
// call pancake sorting function
pancakeSort(pancake, 10);
}
void pancakeSort(int sortArray[], int sortSize)
{
int length = 10;
int temp;
int stop = 10;
// this is where the array get sorting out from smallest to biggest number
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
// after that, the array get display here
for(int x=0; x<sortSize; x++)
{
cout << sortArray[x] << " ";
}
}
but the output is weird :
enter image description here
the function is successfully sorting the array from smallest to biggest,
but there is 2 weird things :
1. The biggest value element (which is 96 from what I input and it's the 10th element after got sorted out), disappear from the display.
2. For some reason, there is value 10 , which I didn't input on the array.
So, what happened?
In the loop
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop is the length of the array, and you are iterating through values of j = 0 to stop - 1. When j reaches stop - 1, the next element that is j+1 becomes stop (10 in this case). But since your array has a length of 10, sortArray[10] is not part of the array, but is referring to some other object in memory which is usually a garbage value. The garbage value is 10 in this case. When you swap sortArray[10] and sortArray[9], the garbage value becomes part of the array and the value at index 9 leaves the array. This keeps on happening till the outer loop ends.
The end result is that unless the garbage value < largest element in the array, the garbage value is pushed in the array and the greatest value of the array is put at sortArray[10] which is not part of the array. If the garbage value is greater than all the values of the array, it'll be found at sortArray[10] which is again not part of the array and your code will return the desired result.
Essentially, what you are doing is giving the function an array of 10 (or stop) elements, but the function is actually working with an array of 11 (or stop + 1) elements, with the last element being a garbage value. The simple fix is to change the conditional of the loop to j < stop - 1.
Note that if you had written this code in a managed (or a comparatively higher level) language like Java or C#, it would have raised an IndexOutOfBoundsException.
At index 9, j+1 is out of bounds. So to fix this, you only need to check till index 8
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop-1; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
Look carefully at the inner loop condition j<stop-1
I have a class that should generate a 2D vector of ints (in the range of 0-1) that I want to use as a map (called matrix).
class generator
{
public:
void draw(void);
void iterate(void);
generator();
~generator();
private:
vector<vector<int>> matrix;
};
In the constructor I want to fill the matrix with random data:
vector<vector<int>> matrix(height, vector<int>(width));
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++) {
matrix[i][j] = rand() % 2;
}
}
But I get a read acess violation.
Thank you for your time and effort.
DEPRECATED UPDATE:
I tried using the member function .data() to retrieve the pointer to the data and accessing it directly
ptr = matrix[i][j].data();
*ptr = rand() % 2;
But the result doesn't differ. I'm fairly convinced that this isn't about how I want to access the vector but how I set it up.
UPDATE 2:
The correction provided below does result in the vector being filled as intended. When trying to
cout << matrix[i][j];
in the draw member function I get a read-acess-violation again.
UPDATE 3:
As suggested I checked when exactly this error happens. It happens on the very first try do print out the first integer at matrix[0][0]. The value returned is 0x8. Important: If not replaced by a constant matrix.size() already causes the error.
UPDATE 4:
This is basically my draw()
void generator::draw() {
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j];
}
cout << endl;
}
}
The original source has been updated to reflect the current one.
UPDATE 4:
Slightly cut source code at http://pastebin.com/83vrDJWZ
UPDATE 5:
One more simple mistake on my part has been resolved in the comments. Problem is silved. Thank you all.
Looks like the problem is an invalid pointer due to:
vector<vector<int>*> matrix;
You have a vector of pointers to vector of int, but you never actually allocate the inner elements.
Instead use:
vector<vector<int>> matrix;
And during the initialization steps:
matrix[i].resize(width); // instead of: matrix[i]->resize(width);
Actually, you could simplify it a bit:
std::vector<std::vector<int>> matrix(height, std::vector<int>(width));
Still have to iterate to fill the data, though.
I have a game that creates a random string of letters and then inputs it to a 2d vector. I was oringally using an array and it filled the array with random letters as it should, but the array was giving me some problems. My friend suggested a 2d array.
Here is the print function that gives me the error that actually causes a break in the program:
const vector<vector<char>>& Board::get_board()
{
for (int i = 0; i < 16; i++)
{
letters.insert(letters.begin(), 1, random_letter());
}
uppercase(letters);
random_shuffle(letters.begin(), letters.end());
int counter = 0;
for (size_t i = 0; i < 4; i++){
for (size_t j = 0; j < 4; j++)
{
board[0].push_back(letters[counter++]);
}
}
I keep getting the array to fill the first row, but then it throws an exception. I'm not sure what the exception is, but when I try to move forward, it tells me the code exited with exception 0 and points to the board[][] line in the print method. I don't think the second vector is being filled. How can I do this? Should I make another temp vector, or use a pair method? I tried the pair method before without much success.
I just changed the 0 to i and indeed, that solved the issue. Thanks! I think that I was thinking the vector would just push to the front counter number of times, not that we had 2 dimensions where the board[i] set the row. Thanks again. Silly error.
Your vector isn't being populated correctly in your get_board() method:
board[0].push_back(letters[counter]);
You're always pushing back onto the first element, but then you use it with the expectation that the board vector has 4 entries in it with the print() method. You also never increment counter and so you always push back the same letter...
Okay, based on comments, you've said you fixed how populate to something more like?
int counter = 0;
for (size_t i = 0; i < 4; i++){
for (size_t j = 0; j < 4; j++)
{
board[i].push_back(letters[counter++]);
}
}
I also don't see the point of the if statement in the print() method.
I have 2 arrays called xVal, and yVal.
I'm using these arrays as coords. What I want to do is to make sure that the array doesn't contain 2 identical sets of coords.
Lets say my arrays looks like this:
int xVal[4] = {1,1,3,4};
int yVal[4] = {1,1,5,4};
Here I want to find the match between xVal[0] yVal[0] and xVal[1] yVal[1] as 2 identical sets of coords called 1,1.
I have tried some different things with a forLoop, but I cant make it work as intended.
You can write an explicit loop using an O(n^2) approach (see answer from x77aBs) or you can trade in some memory for performance. For example using std::set
bool unique(std::vector<int>& x, std::vector<int>& y)
{
std::set< std::pair<int, int> > seen;
for (int i=0,n=x.size(); i<n; i++)
{
if (seen.insert(std::make_pair(x[i], y[i])).second == false)
return false;
}
return true;
}
You can do it with two for loops:
int MAX=4; //number of elements in array
for (int i=0; i<MAX; i++)
{
for (int j=i+1; j<MAX; j++)
{
if (xVal[i]==xVal[j] && yVal[i]==yVal[j])
{
//DUPLICATE ELEMENT at xVal[j], yVal[j]. Here you implement what
//you want (maybe just set them to -1, or delete them and move everything
//one position back)
}
}
}
Small explanation: first variable i get value 0. Than you loop j over all possible numbers. That way you compare xVal[0] and yVal[0] with all other values. j starts at i+1 because you don't need to compare values before i (they have already been compared).
Edit - you should consider writing small class that will represent a point, or at least structure, and using std::vector instead of arrays (it's easier to delete an element in the middle). That should make your life easier :)
int identicalValueNum = 0;
int identicalIndices[4]; // 4 is the max. possible number of identical values
for (int i = 0; i < 4; i++)
{
if (xVal[i] == yVal[i])
{
identicalIndices[identicalValueNum++] = i;
}
}
for (int i = 0; i < identicalValueNum; i++)
{
printf(
"The %ith value in both arrays is the same and is: %i.\n",
identicalIndices[i], xVal[i]);
}
For
int xVal[4] = {1,1,3,4};
int yVal[4] = {1,1,5,4};
the output of printf would be:
The 0th value in both arrays is the same and is: 1.
The 1th value in both arrays is the same and is: 1.
The 3th value in both arrays is the same and is: 4.