Zhendos
Posts: 73
Joined: Mon Oct 05, 2015 2:46 pm

c++ algorhitm

Tue Dec 01, 2015 7:35 am

Dear RBPI forum;

I am doing a c++ course and with a certain exersise I need to make a few users and tell for each user howmuch pancakes they have eaten.

Currently I've a Player.h file and a Player.cpp file.
https://github.com/Zhendos/c-training/b ... /4-1-1.cpp
https://github.com/Zhendos/c-training/b ... /4-1-2.cpp
https://github.com/Zhendos/c-training/b ... /4-1-3.cpp

Now I need to compare 10 objects their integer, but I really can't make an algorhitm for this.
I could do if(...) if(...) 100 times to check which object got the highest integer but I am sure there is a way more efficienter way for this.

Thanks anyway!

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: c++ algorhitm

Tue Dec 01, 2015 2:34 pm

Looks like you would be better of storing your player instances in an iterable collection and iterating through them to find the max... Fairly elementary programming course exercise. Also the '#include <Windows.h>' looks a bit off when on this forum :roll:
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

scotty101
Posts: 3648
Joined: Fri Jun 08, 2012 6:03 pm

Re: c++ algorhitm

Tue Dec 01, 2015 4:16 pm

Would you like to steal our lunch money as well as have us do your homework? :roll:
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
DougieLawson
Posts: 35529
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: c++ algorhitm

Wed Dec 02, 2015 12:31 am

Zhendos wrote:
Now I need to compare 10 objects their integer, but I really can't make an algorhitm for this.
I could do if(...) if(...) 100 times to check which object got the highest integer but I am sure there is a way more efficienter way for this.
Sort them. The highest will sort to the top, the lowest to the bottom. There's a million and one sort algorithms out on Google. With ten objects a simple bubble sort should run quickly enough.
Note: Having anything remotely humorous in your signature is completely banned on this forum. Wear a tinfoil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

danjperron
Posts: 3374
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: c++ algorhitm

Thu Dec 03, 2015 5:09 am

Yesterday I was watching canadian favorite sport and between the intermission I just have fun by creating a small c++ application.

So I do have the sorting but this is a build-in std:sort. Now you will have to figure out how this code works.

I use thread, mutex of course , list and vector.

it is is c++ V11 so you will have to enable the experimental flag. gnu++0x

I tried my best not to thing in C but in C++.

this is the code breakfast.cpp

Code: Select all

#include <iostream>
#include <ctime>
#include <mutex>
#include <deque>
#include <thread>
#include <random>
#include <chrono>
#include <vector>
#include <iomanip>
#include <list>

using namespace std;

 std::random_device rd;
 default_random_engine e1(rd());
 uniform_int_distribution<int> uniform_dist(0, 1000);


vector<string>   Names{"Sherril","Cecila","Emmaline","Jona","Grisel","Kesha","Toccara","Candance","Emmitt","Ji","Paulette",\
                        "Vincenzo","Kristi","Latina","Autumn","Bess","Madeline","Porfirio","Mathew","Arnulfo","Melanie",\
                        "Marcelene","Carletta","Kyong","Juliet","Cierra","Bethann","Lynn","Trisha","Ilda","Alec","Pamelia",\
                        "Weston","Sophie","Colette","Delois","Lauralee","Esmeralda","Arlean","Carissa","Davida","Jerrold",\
                        "Maurita","Delta","Benjamin","Rosita","Katerine","Stephanie","Armando","Georgene"};



class Pancake
{
  public:
   Pancake(int sirop, int Temperature)  : sirop(sirop),Temperature(Temperature) {};
   int getTemperature() { return Temperature;};
   int getSirop()       { return sirop;};

  protected:
   int  sirop;
   int  Temperature;
};


template <class T>
class LockPile {
 private:
    std::mutex mtx;
    std::deque<T> myque;
public:
    LockPile() {};

    void push(T x)
    {
        mtx.lock();
        myque.push_back(x);
        mtx.unlock();
    }

     T   pop()
    {
      mtx.lock();
       if(myque.empty())
        {
         mtx.unlock();
         return nullptr;
        }

       T  top =  std::move(myque.back());
       myque.pop_back();
       mtx.unlock();
       return top;
    }



    void clear()
    {
        mtx.lock();
        myque.clear();
        mtx.unlock();
    }

    int count()
    {
      int temp;
      mtx.lock();
      temp = myque.size();
      mtx.unlock();
      return temp;
    }

    bool empty()
    {
        bool flag;
        mtx.lock();
        flag = myque.empty();
        mtx.unlock();
        return flag;
    }
};


class   Kid
{
 public:
   Kid(int Id, LockPile<Pancake *> * Pile){
   pile = Pile;
   this->Id = Id;
   PancakeEated=0;
   int itemp=uniform_dist(e1) % Names.size();
   Name = Names[itemp];
   Names.erase(Names.begin()+itemp);
   t1 = thread(&Kid::Action,this);
   EatFactor= uniform_dist(e1);
   };

   void WaitT() { t1.join();}
   int PancakeEated;
   int getId() { return Id;}
   string getName() { return Name;}
   int EatFactor;
   static bool Quit;
  private:
   int Id;
   LockPile<Pancake *> * pile;
   thread t1;
   string Name;
  void  Action()
  {

      cout << Name << "is in!" << endl;
      while(!Quit)
       {
         int myrnd= uniform_dist(e1);
         usleep(500000  + ((myrnd * EatFactor) /2));
         if(pile->empty()) continue;
         pile->pop();
         PancakeEated++;
         cout << left << setw(15) << Name;
         cout << " grabs 1 pancake.   " << pile->count() << " left" << endl;
       }
  }
};

bool Kid::Quit= false;


int  main(void)
{
 int loop;

 LockPile<Pancake *> thePlate;

 list<Kid *>  Kids;

 std::chrono::time_point<std::chrono::system_clock> start, end;

 // Choose a random mean between 0 and 1000

 for(loop=0;loop<10;loop++)
 {
  Kid * aKid= new Kid((int)loop,(LockPile<Pancake *> *) &thePlate);
  Kids.push_back(aKid);
  usleep(100000);
 }


 start = std::chrono::system_clock::now();

 while(1)
   {
      Pancake * P = new Pancake(1,1);
      cout << "Pancake ready" << endl;
      thePlate.push(P);
      int myrnd= uniform_dist(e1);
      usleep(30000  + (myrnd * 50));
      end = chrono::system_clock::now();
      if(chrono::duration_cast<std::chrono::seconds> (end-start).count() > 15) break;
   }

   cout << endl << "The cook left" << endl <<endl;

   usleep(1000000);

   cout << endl  << "=============" << endl;


   Kid::Quit=true;
   for(list<Kid *>::iterator i = Kids.begin(); i != Kids.end() ; i++)
     {
        (*i)->WaitT();
      }


    struct CompareKidsPancakeEated{
    bool operator()(Kid * a, Kid * b) {return a->PancakeEated > b->PancakeEated;}
    };

    Kids.sort(CompareKidsPancakeEated());


   for(list<Kid *>:: iterator i = Kids.begin(); i != Kids.end() ;)
    {
       cout << left << setw(15) << (*i)->getName();
       cout << " ate a total of " << (*i)->PancakeEated << "  pancakes " << endl;
       delete (*i);
       i = Kids.erase(i);
    }

   cout << endl  << "=============" << endl;

   cout << endl << thePlate.count() << " pancake(s) left " << endl;
   thePlate.clear();
   cout << "Done." << endl;
  return 0;
and to compile

Code: Select all

g++ -std=gnu++0x -lpthread -o breakfast breakfast.cpp

let it run and the sort output will be at the end.

Have fun to decipher it . I specifically use std:sort because it is the C++ way.

danjperron
Posts: 3374
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: c++ algorhitm

Thu Dec 03, 2015 12:01 pm

Oops memory leak.

Needs to delete the pancake!

line 133

Code: Select all

         Pancake * myPancake=pile->pop();
         delete myPancake; //miam miam  it's gone!

swampdog
Posts: 221
Joined: Fri Dec 04, 2015 11:22 am

Re: c++ algorhitm

Fri Dec 04, 2015 12:44 pm

This is my first ever post so fingers-crossed!

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std; //beginners should not use this!

int
main()
{ifstream ifs ("./z.dat");
string s;
vector<int> v; //an array

while (getline(ifs,s)) { //read another text line
int i (atoi(s.c_str())); //stoi

// cout<<'['<<s<<"]\n";
v.push_back(i); //add it onto the end
}

sort(v.begin(),v.end());

copy(v.begin(),v.end(),ostream_iterator<int>(cout,"\n"));
// for (int i=0; i<v.size(); i++)cout<<v<<'\n';

return 0;
}


If you create a file "z.dat" with one number per line in the same folder as the executable the above will allow you to handle any number of people. A container such as std::vector<> can hold any type of data including ones (classes) you create yourself. The std::sort can take further arguments which will allow you to modify how it behaves. The commented out "for" is going to be easier for you to use instead of that std::copy above but both lines do the same thing.

There's no actual need to read in a whole line as a string then convert it into an integer but you'll need to know std::getline quite soon and it's clearer what's happening this way.

All the above does is read in the numbers from the file then sort them into order.

ejolson
Posts: 3227
Joined: Tue Mar 18, 2014 11:47 am

Re: c++ algorhitm

Sun Dec 06, 2015 8:56 am

danjperron wrote:Now you will have to figure out how this code works.
It appears one thread creates pancakes at random times and 10 threads at random times try to delete them. Which thread deleted the most pancakes is then reported. This appears to be a real-time simulation of what might happen at an all you can eat pancake breakfast. In world be interesting to write a program that quickly performs the same calculation using priority queues without taking all the time for the sleeps.

danjperron
Posts: 3374
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: c++ algorhitm

Sun Dec 06, 2015 1:14 pm

It appears one thread creates pancakes at random times and 10 threads at random times try to delete them. Which thread deleted the most pancakes is then reported. This appears to be a real-time simulation of what might happen at an all you can eat pancake breakfast.
.

Yes. Exactly! A simple answer is sometimes not enough. And I always try to push a little bit the enveloppe. This way you show to people that you could do more than a simple dull program. He ask for a sort algorithm. He got one but before sorting why not creating some real numbers using some kind of simulation. Demonstrate how to use threads, how to use a simple lock so one thread won't interfered with another, etc...

Also instead of using a simple array of integer to sort, why not using a list of objects and show how you could apply the sort on it.
priority queues without taking all the time for the sleeps.
usleep() doesn't take time! it just gives time to other process.
And yes you could used priority queues! it will sort at it goes!

Hey. B.T.W. it was just for fun . Sometimes I do have some crazy idea and why not just be creative!

Return to “C/C++”