My MCVC is compiling but is not functioning as intended. The goal is a genetic algorithm that performs the basics i.e. crossover,mutation,evolution. In the code I have provided should print out the good job statements but thats not the case. I am a new programmer, sorry.
My questions are:
1) The cpu and ram are rev'ed up, is this array declaration and implementation the cause for the uncontrolled spike?
std::array<std::auto_ptr<Individual>,50>myarray;
2) Is my 2.53 GHz Intel Core 2 Duo not up for it?
3) Should I cut down the amount of loops?
Any help is always welcomed !
Individual.h
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <array>
#include <iostream>
class Individual
{
public:
inline int getRandomNumber(int min = 0, int max = 1)
{
srand(static_cast<unsigned int>(time(0)));
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
private:
int defaultGeneLength = 64;
std::vector<char>genes;
int fitness = 0;
public:
Individual()
{
std::cout<<"Good Job";
}
//setters and getters
void generateIndividual();
void setDefaultGeneLength(int length);
char getGene(int index);
void setGene(int index, char value);
//public methods
unsigned int size();
int getFitness();
std::string toString();
};
Individual.cpp
#include "Individual.h"
void Individual::generateIndividual()
{
for (int i = 0; i < size(); i++)
{
genes.push_back(getRandomNumber());
}
}
//setters and getters
void Individual::setDefaultGeneLength(int length)
{
defaultGeneLength = length;
}
char Individual::getGene(int index)
{
return genes.at(index);
}
void Individual::setGene(int index, char value)
{
genes[index] = value;
fitness = 0;
}
//public methods
unsigned int Individual::size()
{
return genes.max_size();
}
int Individual::getFitness()
{
if(fitness == 0)
{
fitness = 1;
} return fitness;
}
std::string Individual::toString()
{
std::string geneString = "";
for (int i = 0; i < size(); i++)
{
geneString.append(getGene(i),1);
}
return geneString;
}
Population.h
#include "Individual.h"
class Population
{
std::array<std::auto_ptr<Individual>,50>myarray;
public:
Population(int populationSize, bool initialise)
{
std::cout<<"Good Job2";
if(initialise)
{
for (int i = 0; i < populationSize; ++i)
{
std::auto_ptr<Individual>newIndividual(new Individual());
myarray.at(i) = newIndividual;
myarray.at(i)->generateIndividual();
saveIndividual(i,*(myarray.at(i)));
}
}
std::cout<<"Good Job 3";
}
Individual getIndividual(int index);
Individual getFittest();
unsigned long size();
void saveIndividual (int index, Individual indiv);
~Population()
{
}
};
Population.cpp
#include "Population.h"
Individual Population::getIndividual(int index)
{
return *myarray.at(index);
}
Individual Population::getFittest()
{
Individual fittest = *myarray.at(0);
for (int i = 0; i < myarray.max_size(); i++)
{
if (fittest.getFitness() <= getIndividual(i).getFitness())
{
fittest = getIndividual(i);
}
}
return fittest;
}
unsigned long Population::size()
{
return myarray.max_size();
}
void Population::saveIndividual (int index, Individual indiv)
{
*myarray.at(index) = indiv;
}
Main.cpp
int main(int argc, const char * argv[]) {
Population *mypop = new Population(2,true);
delete mypop;
mypop = nullptr;
return 0;
}
unsigned int Individual::size()
{
return genes.max_size();
}
Your genes is a:
std::vector<char> genes;
The C++ standard defines std::vector::max_size() as follows:
distance(begin(), end()) for the largest possible container
It is not specified what "largest possible container" means. "Possible" could mean anything, like, if the system had a ten terabyte hard drive, so that the operating system could use the entire hard drive to page its virtual memory address space. That's certainly "possible", in some sense of the word. But it goes without saying that paging out ten terabytes will take a while.
With 64 bit gcc, the following simple program:
#include <iostream>
#include <vector>
int main()
{
std::vector<char> c;
std::cout << c.max_size() << std::endl;
return 0;
}
Produces the following output:
18446744073709551615
However, my chances of being able to actually create a vector of such size are not very good.
But let's get back to your code:
void Individual::generateIndividual()
{
for (int i = 0; i < size(); i++)
{
genes.push_back(getRandomNumber());
}
}
Ok. You must be feeling quite lucky. You believe that it will be possible for you to create a vector<char> that's max_size() big.
Are you quite sure about that?
I'm somewhat skeptical.
Related
I'm trying to "build" a house which contains rooms. My teacher told me to do it with composition. My idea was to generate as many Rooms objects as many rooms my house has. I tried it with the following code but in the house.cpp's constructor my for cycle runs only once than it crashes at the line rooms[i] = load; with Exception thrown: read access violation.
_Pnext was 0xFDFDFE05.
Here's my code:
main.cpp:
'''
#include <iostream>
#include "House.h"
#include "Rooms.h"
using namespace std;
int main()
{
Rooms basic("basic");
House house(basic,2);
house.setRooms();
house.setWhichroom(1);
cout << house.getRooms().getRoomname();
return 0;
}
'''
house.h:
'''
#pragma once
#include <iostream>
#include <string>
#include "Rooms.h"
using namespace std;
class House
{
Rooms* rooms;
unsigned roomcount;
unsigned whichroom = 0;
public:
House();
House(const Rooms&, unsigned);
House(unsigned);
~House();
void setRoomcount(unsigned);
unsigned getRoomcount()const;
void setWhichroom(unsigned );
unsigned getWhichroom()const;
void setRooms();
Rooms getRooms()const;
};
'''
house.cpp:
'''
#include "House.h"
House::House(const Rooms& load, unsigned rc)
{
roomcount = rc;
for (int i = 0; i < roomcount; i++)
{
rooms = new Rooms;
rooms[i] = load;
}
}
House::House(unsigned x):roomcount(x)
{
}
House::~House()
{
roomcount = 0;
delete rooms;
}
void House::setRoomcount(unsigned x)
{
roomcount = x;
}
unsigned House::getRoomcount() const
{
return roomcount;
}
void House::setWhichroom(unsigned x)
{
whichroom = x;
}
unsigned House::getWhichroom() const
{
return whichroom;
}
void House::setRooms()
{
for (unsigned i = 1; i <= roomcount; i++)
{
char c = i;
string s = "room";
s += c;
rooms[i].setRoomname(s);
}
}
Rooms House::getRooms() const
{
return rooms[whichroom];
}
'''
rooms.h:
'''
#pragma once
#include <iostream>
#include "Things.h"
using namespace std;
class Rooms
{
protected:
string roomname;
Things things;
public:
Rooms();
Rooms(string);
~Rooms();
void setRoomname(string);
string getRoomname()const;
void setThings();
unsigned getThings()const;
};
'''
rooms.cpp:
'''
#include "Rooms.h"
Rooms::Rooms()
{
}
Rooms::Rooms(string name)
{
roomname = name;
}
Rooms::~Rooms()
{
}
void Rooms::setRoomname(string name)
{
roomname = name;
}
string Rooms::getRoomname() const
{
return roomname;
}
void Rooms::setThings()
{
things.setOnoff();
}
unsigned Rooms::getThings() const
{
return things.getOnoff();
}
'''
The problem is in the House constructor, where you have
for (int i = 0; i < roomcount; i++)
{
rooms = new Rooms;
rooms[i] = load;
}
You will create one single Rooms object, but treat it as an array of multiple rooms.
You also create and create and create new Room objects each iteration of the loop, making you loose the earlier objects.
The simple solution, if you need to continue to use explicit memory handling yourself, is to allocate the objects once and before the loop:
rooms = new Rooms[roomcount];
for (int i = 0; i < roomcount; i++)
{
rooms[i] = load;
}
Since you now use new[] you must match it with a delete[] in the destructor. And you need to learn about the rules of three and five.
To simplify your code I implore you to use a std::vector instead, as that will make life so much simpler for you as a C++ programmer.
I'm attempting to implement an intvector in C++ and am getting a "Segmentation fault: 11" error. I understand this has something to do with memory management, and considering how new I am to C++ it could definitely be a pretty minor mistake. I debugged the code with valgrind and was given messages such as the following:
Use of uninitialized value of size 8, Invalid read of size 4,Conditional jump or move depends on uninitialized value(s).
My best guess is it has something to do with how I'm implementing the arrays. I originally had the arrays stored on the heap but changed it to the stack and still got the same error. I've already implemented an intvector in java, so I was attempting to use similar logic here, which perhaps is part of the issue.
#include <iostream>
#include "IntVector.h"
#include <cmath>
using namespace std;
int num_elements = 0;
int array_size = 0;
int expansion_factor;
void IntVector::expandArray(){
int tempArr[array_size*2];
for(int i =0;i<array_size;i++){
tempArr[i] = array[i];
}
array = tempArr;
array_size = array_size * 2;
}
void IntVector::add(int val){
int tempArr[array_size];
if(array_size == num_elements){
expandArray();
array[num_elements] = val;
}
else{
for(int i = 0;i<array_size;i++){
tempArr[i] = array[i];
}
tempArr[num_elements] = val;
array = tempArr;
}
num_elements++;
}
void IntVector::remove(int index){
}
int IntVector::get(int index) const{
return index;
}
void IntVector::removeLast(){
}
void IntVector::set(int index, int val){
}
std::string IntVector::toString()const {
return "";
}
IntVector::IntVector(int initial_size){
int* array = new int[initial_size];
}
IntVector:: ~IntVector(){
delete[] array;
}
int main(){
IntVector v(0);
v.add(5);
}
#ifndef INTVECTOR_H_
#define INTVECTOR_H_
using std::cout;
class IntVector {
private:
int* array;
int num_elements;
int array_size;
int expansion_factor;
void expandArray();
public:
void add(int val);
void remove(int index);
int get(int index) const;
void removeLast();
void set(int index, int val);
std::string toString() const;
IntVector(int initial_size);
~IntVector();
};
#endif
As mention in the comments, there are definitely some holes in your understanding of C++. Really when dealing with header files you should have a main.cpp, someotherfile.h, someotherfile.cpp. That just best practices to avoid redefinition errors.
There was quite a bit wrong with the way you accessed the private variable. If a class has a private( or even public) variable you don't have to redeclare it each time you want to change its value.
There were one or two major flaws with the way you expanded the vector. If the vector size is initialized to 0 then 0*2 is still 0 so you never actually increased the size. Secondly, when you set the original array = to the new array the new array was just a local array. This means that the memory wasn't actually allocated permanently, once the function ended the temparr was destroyed.
I know this was probably a lot but if you have any question feel free to ask.
main.cpp
#include "IntVector.h"
int main()
{
IntVector v;
IntVector x(10);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.push(5);
v.print();
cout << endl;
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.push(5);
x.print();
return 0;
}
IntVector.h
#include <string>
#include <iostream>
using namespace std;
class IntVector {
private:
int *array;
int num_elements;
int array_size;
//int expansion_factor =; you would only need this if you plan on more than double the vector size
void expandArray(); //normally c++ array double in size each time they expand
public:
//Constructors
IntVector(); //this is a contructor for if nothing is called
IntVector(int initial_size);
//setters
void push(int val); //add
void pop(); //removelast
void remove(int index); //remove
void at(int index, int val); //set
//Getters
int at(int index);
//std::string toString(); I'm changing this to print
void print(); //will print the contents to the terminal
//Deconstructor
~IntVector();
};
IntVector.cpp
#include "IntVector.h"
//constructors
IntVector::IntVector() //no arguments given
{
array = new int[0];
num_elements = 0;
array_size = 0;
}
IntVector::IntVector(int initial_size)
{
array = new int[initial_size];
num_elements = 0;
array_size = initial_size;
}
void IntVector::expandArray()
{
int *tempArr;
if(array_size == 0){
array_size = 1;
tempArr = new int[1];
} else {
//make sure to allocate new memory
//you were creating a local array which was destroy after the function was completed
//using new will allow the array to exist outside the function
tempArr = new int[array_size * 2];
}
for (int i = 0; i < array_size; i++)
{
tempArr[i] = array[i];
}
//make sure to delete the old array otherwise there is a memory leak.
//c++ doesn't have a garbage collector
delete[] array;
array = tempArr;
array_size = array_size * 2;
}
void IntVector::push(int val)
{
num_elements++;
//checking if vector needs to increase
if (array_size <= num_elements)
{
expandArray();
array[num_elements-1] = val;
}
else
{
array[num_elements-1] = val;
}
}
void IntVector::remove(int index)
{
//not sure how to implment this becuase each element has to be a number.
}
int IntVector::at(int index)
{
return array[index];
}
void IntVector::pop()
{
num_elements = num_elements-1; //not really removing it from the "vector" but it won't print out again
}
void IntVector::at(int index, int val)
{
array[index] = val;
}
void IntVector::print()
{
for (int i = 0 ; i < num_elements; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
IntVector::~IntVector()
{
delete[] array;
}
output
5 5 5 5 5
5 5 5 5 5
Hopefully, the comments help. I changed the name of the functions to better match the actual vecter class the already exists in C++. I think it's good to pick apart already defined functions like this because you get a better understanding of how they actually work and not just how to use them.
If you got any questions just leave a comment
I am trying to implement a producer <-> consumer pattern in C++.
When I read about this pattern they always seems to mention a potential deadlock that has to be avoided.
However I have implemented this below without using any mutex below.
What is wrong with my code?
#include <vector>
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
class CircularBuffer
{
public:
CircularBuffer();
int* getWritePos();
void finishedWriting();
int* getReadPos();
void finishedReading();
private:
void waitForReaderToCatchUp();
void waitForWriterToCatchUp();
const int size = 5;
std::vector<int> data;
// Changed from int since these variables are shared between the two threads and assignment is not necessarily atomic:
std::atomic<int> writePos = 0;
std::atomic<int> readPos = 0;
};
CircularBuffer::CircularBuffer() {
data.resize(size);
}
void
CircularBuffer::waitForReaderToCatchUp() {
int unread = writePos - readPos;
while (unread >= size) {
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
unread = writePos - readPos;
}
}
int*
CircularBuffer::getWritePos() {
waitForReaderToCatchUp();
int pos = writePos % size;
return &data[pos];
}
void
CircularBuffer::finishedWriting() {
writePos++;
}
void
CircularBuffer::waitForWriterToCatchUp() {
int unread = writePos - readPos;
while (unread < 1) {
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
unread = writePos - readPos;
}
}
int*
CircularBuffer::getReadPos() {
waitForWriterToCatchUp();
int pos = readPos % size;
return &data[pos];
}
void
CircularBuffer::finishedReading() {
readPos++;
}
const int produceMinTime = 100;
void produce(CircularBuffer *cb) {
for (int i = 0; i < 15; i++) {
int r = rand() % 1000;
std::this_thread::sleep_for(std::chrono::milliseconds(produceMinTime + r));
int *p = cb->getWritePos();
memcpy(p, &i, 4);
cb->finishedWriting();
}
}
void consume(CircularBuffer *cb) {
for (int i = 0; i < 15; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
int *p = cb->getReadPos();
int j = *p;
std::cout << "Value: " << j << std::endl;
cb->finishedReading();
}
}
int main()
{
CircularBuffer cb;
std::thread t1(produce, &cb);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
std::thread t2(consume, &cb);
t1.join();
t2.join();
int k;
std::cin >> k;
}
std::vector<int> is not a thread-safe data structure. So, if you access it from two threads simultaneously, that would be considered undefined behavior. You could crash, have other problems, or it could seemingly work (but still be wrong).
The ints inside the vector, and the ones representing your positions are also not thread-safe -- read/write isn't necessarily atomic (there are lock-free ways to do that).
So, you could totally implement something like this lock-free, but not this way. Some info here: https://www.infoq.com/news/2014/10/cpp-lock-free-programming/
Generally, you want to look at the primitives in std::atomic: https://en.cppreference.com/w/cpp/atomic/atomic
Also see: Ring buffer with atomic indexes
I have been attempting to write this program where I am required to utilize dynamically allocated arrays to print out a 2d matrix. I am only to write the cpp files and not allowed to modify anything in the header files.
I keep getting an exception
0 [main] review2_cis17c_objectarray 4018 cygwin_exception::open_stackdumpfile: Dumping stack trace to review2_cis17c_objectarray.exe.stackdump
I am relatively new to learning c++; after contemplating, I think something is wrong in my PlusTab.cpp, where I am trying to assign an allocated address to a constructor-defined array in a class. Can someone please help and let me know here I did wrong in the project? Thank you very much!
AbsRow.h:
class AbsRow {
protected:
int size;
int *rowData;
public:
virtual int getSize()const = 0;
virtual int getData(int)const = 0;
};
AbsTabl.h:
class AbsTabl {
protected:
int szRow;
int szCol;
RowAray **columns;
public:
virtual int getSzRow()const = 0;
virtual int getSzCol()const = 0;
virtual int getData(int,int)const = 0; };
PlusTab.h
class PlusTab:public Table {
public:
PlusTab(unsigned int r,unsigned int c):Table(r,c){};
PlusTab operator+(const PlusTab &);
};
RowAray.h
class RowAray:public AbsRow {
public:
RowAray(unsigned int);
virtual ~RowAray();
int getSize()const{return size;}
int getData(int i)const{
if(i>=0&&i<size)return rowData[i];
else return 0;}
void setData(int,int);
};
Table.h
#include "AbsTabl.h"
class Table:public AbsTabl {
public:
Table(unsigned int,unsigned int);
Table(const Table &);
virtual ~Table();
int getSzRow()const {return szRow;}
int getSzCol()const {return szCol;}
int getData(int,int)const;
void setData(int,int,int);
};
PlusTab.cpp:
#include "PlusTab.h"
PlusTab PlusTab::operator+(const PlusTab &t) {
PlusTab tab(this->getSzRow(), this->getSzCol());
for(int i = 0; i < tab.getSzRow(); i++) {
for (int j = 0; j <tab.getSzCol(); j++) {
(tab.columns[i])->setData(j, this->getData(i,j) + t.getData(i,j));
}
}
return tab;
}
RowAray.cpp:
#include "RowAray.h"
RowAray::RowAray(unsigned int c) {
size = c;
rowData = new int[c];
}
RowAray::~RowAray() {
delete []rowData;
}
void RowAray::setData(int i, int value) {
rowData[i] = value;
}
Table.cpp:
#include "Table.h"
#include <cstdlib>
Table::Table(unsigned int r, unsigned int c) {
szRow = r;
szCol = c;
columns = new RowAray*[r];
for (int i = 0; i < r; i++) {
columns[i] = new RowAray(c);
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
columns[i]->setData(j, (rand()%90 + 10));
}
}
}
Table::~Table() {
for (int i = 0; i < szRow; i++) {
delete []columns[i];
}
delete []columns;
}
Table::Table(const Table &t) {
szRow = t.szRow;
szCol = t.szCol;
columns = t.columns;
};
int Table::getData(int r ,int c) const {
return columns[r]->getData(c);
};
void Table::setData(int r, int c, int value) {
columns[r]->setData(c,value);
}
and finally my main.cpp, which I am not allowed to modify either.
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;
//User Libraries
#include "PlusTab.h"
//Global Constants
//Function Prototype
void prntTab(const Table &);
//Execution Begins Here!
int main(int argc, char** argv) {
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
int rows=3,cols=4;
//Test out the Tables
PlusTab tab1(rows,cols);
PlusTab tab2(tab1);
PlusTab tab3=tab1+tab2;
// Print the tables
cout<<"Abstracted and Polymorphic Print Table 1 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab1);
cout<<"Copy Constructed Table 2 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab2);
cout<<"Operator Overloaded Table 3 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab3);
//Exit Stage Right
return 0;
}
void prntTab(const Table &a){
cout<<endl;
for(int row=0;row<a.getSzRow();row++){
for(int col=0;col<a.getSzCol();col++){
cout<<setw(4)<<a.getData(row,col);
}
cout<<endl;
}
cout<<endl;
}
I apologize for this massive amount of code. This is my first time posting, will learn to use the website! I appreciate your help:)
I read Google’s native client tutorial on how to build my own C++ based PNaCl module several times and somehow I'm not getting wiser, I know that if I want to implement a messaging functionality. I have the following in the .cc file as basis for a PNaCl code, all this is taken from Googles's Hello World tutorial:
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/cpp/var.h"
namespace {
// The expected string sent by the browser.
const char* const kHelloString = "hello";
// The string sent back to the browser upon receipt of a message
// containing "hello".
const char* const kReplyString = "hello from NaCl";
} // namespace
class job1Instance : public pp::Instance {
public:
explicit job1Instance(PP_Instance instance): pp::Instance(instance) {}
virtual ~job1Instance() {}
virtual void HandleMessage(const pp::Var& message) {
if (!message.is_string()) {
return;
}
std::string message_txt = message.AsString();
pp::Var reply;
if (message_txt == kHelloString) {
reply = pp::Var(kReplyString);
PostMessage(kReplyString);
}
}
};
class job1 : public pp::Module {
public:
job1() : pp::Module() {}
virtual ~job1() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new job1Instance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new job1();
}
} // namespace pp
As I understand the PNaCl modules don’t use a main() function and yet let’s say I have an old C++ code that creates 2 arrays unsorted1 and unsorted2 with random numbers which I want to use in my PNaCl module:
#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <array>
// a function to create a random number between min and max
int32_t rangeRandomAlg (int32_t min, int32_t max) {
int32_t num = max - min + 1;
int32_t remainder = RAND_MAX % num;
int32_t x;
do {
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % num;
}
// a function to create arrays with random numbers
void unsortedArrays(int32_t unsorted1[], int32_t unsorted2[],int32_t arrayElements, int32_t minNum, int32_t maxNum){
for(int32_t i = 0; i <= arrayElements; i++) {
if (i < arrayElements/2) {
unsorted1[i] = rangeRandomAlg(minNum, maxNum);
} else {
unsorted2[i] = rangeRandomAlg(minNum, maxNum);
}
}
}
// the main function
int32_t main(int32_t argc, char *argv[]) {
// declare all the zises
int32_t minNum = 0;
int32_t maxNum = 100;
int32_t arrayElements = maxNum;
// the arrays
int32_t unsorted1[arrayElements/2];
int32_t unsorted2[arrayElements/2];
// fill the arrays with random numbers
unsortedArrays(unsorted1, unsorted2, arrayElements, minNum, maxNum);
return 0;
}
My problem is that I didn’t quite understand how can I integrate this code into the PNaCl module and use the HandleMessage() function to sent the unsorted1 and unsorted2 arrays back to the JavaScript with the PostMesage() function. I know I have to work with arrays and not strings in the HandleMessage() function.
I hope to get some help here, since I’m really new to this whole native client thing.
Well here is the solution that took some hours to get to:
// pepper includes
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/cpp/var.h"
#include "json/json.h"
#include <sstream>
// cpp includes
#include <stdint.h>
#include <unistd.h>
#include <array>
#include <string>
//static variables
namespace {
// The expected string sent by the browser.
const char* const kHelloString = "Bereit fuer dein Modul";
// The string sent back to the browser upon receipt of a message
// containing "hello".
const char* const kReplyString = "PNaCl hat Ergebnisse geschickt";
} // namespace
class job1Instance : public pp::Instance {
public:
explicit job1Instance(PP_Instance instance): pp::Instance(instance) {}
virtual ~job1Instance() {}
virtual void HandleMessage(const pp::Var& message) {
/*
if (!message.is_string()) {
return;
}
std::string message_txt = message.AsString();
pp::Var reply;
if (message_txt == kHelloString) {
reply = pp::Var(kReplyString);
PostMessage(kReplyString);
}
*/
/*** my functions and data for the cpp code to integrate start here ***/
// declare all the zises
int32_t minNum = 0;
int32_t maxNum = 100;
int32_t arrayElements = maxNum;
// the arrays
int32_t unsorted1[arrayElements/2];
int32_t unsorted2[arrayElements/2];
// fill the arrays with random numbers
unsortedArrays(unsorted1, unsorted2, arrayElements, minNum, maxNum);
std::string outRes1, outRes2;
arrayToString(unsorted1, arrayElements/2, outRes1);
arrayToString(unsorted2, arrayElements/2, outRes2);
PostMessage(outRes1); // send the unsorted1 array as a string to the JavaScript back
}
private:
// function to create a random number between min and max
int32_t rangeRandomAlg (int32_t min, int32_t max) {
int32_t num = max - min + 1;
int32_t remainder = RAND_MAX % num;
int32_t x;
do {
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % num;
}
// function to create arrays with random numbers
void unsortedArrays (int32_t unsorted1[], int32_t unsorted2[],int32_t arrayElements, int32_t minNum, int32_t maxNum) {
for(int32_t i = 0; i <= arrayElements; i++) {
if (i < arrayElements/2) {
unsorted1[i] = rangeRandomAlg(minNum, maxNum);
} else {
unsorted2[i] = rangeRandomAlg(minNum, maxNum);
}
}
}
// convert the arrays to string
void arrayToString (int32_t array[], int32_t arraySize, std::string& arrayString) {
for (int32_t i = 0; i <= arraySize; ++i){
arrayString+= std::to_string(array[i]);
if (i != arraySize) {
arrayString+= ',';
}
}
}
};
/*** my functions and data for the cpp code to integrate end here ***/
class job1 : public pp::Module {
public:
job1() : pp::Module() {}
virtual ~job1() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new job1Instance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new job1();
}
} // namespace pp
This is only the precompiled C++ code of the PNaCl module with my code integrated in it, it sends only the outRes1 variable = unsorted1 array variable as string to the JavaScript code in the index.html file. You have to have the .nmf and the index.html files written separately. If anyone wants to see my code of those files, which has the basic and working code for this PNaCl module should write me a comment and I’ll post those to.