Reputation: 11
I am done the work-- but my output is odd. I am basically trying to compare a bunch of objects and if they share ttns and their time is up-- then they need to recalculate their ttns. After checking all the hosts I increment the clock and try again. The objective is to find the fist host which can make it through the check without a collision. This is basically a simulation of a network that does some backoff calculation if two hosts send at the same time (CLOCK). I put in a check to ensure the host didn't check itself-- I know what my expected output is and it isn't it. I have worked through this a few times but can't find my logic error(s). Any pointers?
// Should insert n number as argument 1 on the command line.
#include <iostream>
#include <vector>
#include <stdlib.h> // srand(), time()
static int CLOCK = 0;
class Host{
private:
int sid;
int cc;
int ttns;
public:
Host();
int get_sid(){ return sid; }
void set_sid(int id){ sid = id; }
int get_cc(){ return cc; }
void inc_cc(){ cc += 1; }
int get_ttns(){ return ttns; }
void new_ttns(){ ttns = (rand()%(cc+1))+CLOCK+1; }
};
Host::Host(){
sid = -666;
cc = 0;
ttns = 0;
}
bool work(std::vector<Host> &hosts){
int count = 0;
for(CLOCK = 0; /*INFINITE*/; CLOCK++){
for(int i = 0; i < hosts.size(); i++){
count = 0;
for(int n = 0; n < hosts.size(); n++){
if( (i != n) && /* host i doesn't compare to host n */
(hosts[i].get_ttns() == hosts[n].get_ttns()) &&/* host i and n share ttns */
(hosts[i].get_ttns() == CLOCK) /* host i ttns = now */
){
hosts[i].inc_cc();
hosts[i].new_ttns();
count = -666; // collision occured
}
count++;
}
if ( count == hosts.size() ){
std::cout << "Host " << hosts[i].get_sid() << "\nTTNS: " << hosts[i].get_ttns();
std::cout << std::endl;
return false;
}
}
}
return true; // pretty pointless
}
int main(int argc, char *argv[]){
srand(time(NULL));
std::vector<Host> hosts;
// Push hosts into vector
int nhosts = atoi(argv[1]);
for(int i = 0; i < nhosts; i++){
Host newhost;
newhost.set_sid(i);
hosts.push_back(newhost);
}
while (work(hosts)){
; // hang out
}
return 0;
}
Upvotes: 1
Views: 162
Reputation: 14705
It seems to me you should update the cc and ttns for the host n you are checking for in the inner loop.
hosts[n].inc_cc();
hosts[n].new_ttns();
Instead of
hosts[i].inc_cc();
hosts[i].new_ttns();
And move the check for
( hosts[i].get_ttns() == CLOCK )
outside the inner loop.
if ( hosts[i].get_ttns() == CLOCK )
for(int n = 0; n < hosts.size(); n++){
The condition inside then becomes
if( (i != n) && /* host i doesn't compare to host n */
(hosts[i].get_ttns() == hosts[n].get_ttns()) /* host i and n share ttns */
){
This way you don't count++
for invalid hosts.
Upvotes: 0
Reputation: 9424
one of the error is probably in this line:
(hosts[i].get_ttns() == CLOCK)
you can't compare this, since CLOCK is global and incremented by more than one host. that means a host doesn't have a monotonous CLOCK.
maybe you want this:
(hosts[i].get_ttns() <= CLOCK
Upvotes: 1