C++ Code Outline
Nov 29, 2016 at 11:14am UTC
Can you give me the outline for a code. I want to count the number of girls and boys entering a exam hall. This counting i am planning to do through swipe machine.
Thanks & regards, Sindhu
Nov 29, 2016 at 11:30am UTC
No idea what your contraints are. Here is a class to handle a swipe and increment a counter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
enum Gender
{
boy,
girl
};
class Swiper
{
int boys;
int girls;
public :
Swiper() : boys(0), girls(0) {}
void Swipe(Gender g)
{
if ( g == Gender::boy ) boys++;
else if ( g == Gender::girl ) girls++;
}
};
Nov 29, 2016 at 1:30pm UTC
Improved version on Stewbond's code (aside from changes in style and other minor things).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
enum class Gender { boy, girl, both };
class Swiper
{
private :
int boys;
int girls;
public :
Swiper() : boys(0), girls(0) { }
void swipe(int val, Gender g)
{
if (g == Gender::boy) { boys += (boys + val >= 0 ? val : -boys); }
else if (g == Gender::girl) { girls += (girls + val >= 0 ? val : -girls); }
else if (g == Gender::both)
{
boys += (boys + val >= 0 ? val : -boys);
girls += (girls + val >= 0 ? val : -girls);
}
}
void reset(Gender g)
{
if (g == Gender::both) { boys = 0; girls = 0; }
else if (g == Gender::boy) { boys = 0; }
else if (g == Gender::girl) { girls = 0; }
}
void set(int val, Gender g)
{
if (val >= 0)
{
if (g == Gender::both) { boys = val; girls = val; }
else if (g == Gender::boy) { boys = val; }
else if (g == Gender::girl) { girls = val; }
}
}
int get(Gender g)
{
if (g == Gender::both) { return boys + girls; }
else if (g == Gender::boy) { return boys; }
else if (g == Gender::girl) { return girls; }
return -1;
}
};
Last edited on Nov 29, 2016 at 2:04pm UTC
Topic archived. No new replies allowed.