Hi
I recently had to write a small code in a competition ,but my code was
rejected cause it failed in 1 of test cases.
The problm was .....we are given vector of strings....each string
consists of either 1 or 2("12122" 0r "2121" so on..)...i had to find
the that string where percentage of '1' is minimum.Now the problem and
solution both are trivial but i was told that comparing double with <
or > sign doesn't ensure a correct solution always ie it fails for
number differing by a very small value.
Also if two string have indentical small percentage of '1 then the
smallest indexed string is to be returned(ie string of index 0 in
vector is identical with index 4 then 0 is to be returned.)
The code goes something like this.....
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
class Elections{
public:
int visit(vector<string> like);
};
int Elections::visit(vector<string>like)
{
double min=1000,temp=0;
int index=0;
for(int i=0;i<like.size();i++)
{
temp=0;
for(int j=0;j<like.size();j++)
if(like[i][j]=='1')
temp++;
temp=temp/like[i].size();
if(min>temp)
{
min=temp;
index=i;
}
}
return index;
}
The test case for which my solution fails is
{"11122211222111111112121", "11122211222111111112121",
"11122211222111111112121", "11122211222111111112121",
"11122211222111111112121", "11122211222111111112121",
"11122211222111111112121", "11122211222111111112121",
"11122211222111111112121", "11122211222111111112121"}
The above case has all equal string yet it returned 9(index instead of
0) according to the system test they carried out.
I tried running the above code in a different compiler and the answer i
got was correct.(ie 0)
I am not sure , besides the floating point comparison ambiguity what
other reason could have led to different results in two different
compilers.
thanks in advance
Somesh