-3

I am trying to solve the AdvertisingAgency problem from TopCoder. When I submit this code aand run system tests it shows that the program failed system tests. Hovewer when I run tests from the Test Panel it passess all of them. Do you have any idea on where the problem is?

Source code:

#include<iostream>
#include<vector>
using namespace std;
class AdvertisingAgency{
public:
    int numberOfRejections(vector<int>requests){
        int rejections=0;
        bool billboards[100];
        for(int request:requests){
            if(billboards[request]){
                rejections++;
            }
            else{
                billboards[request]=true;
            }
        }
        return rejections;
    }
};
Revi
  • 50
  • 2
  • 10
  • 4
    Better to spend time with some of these [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) then on some bogus _competitive programming_ site. – Ron Oct 12 '17 at 18:59
  • 4
    You are accessing `billboards[request]`, which is not initialized. This is UB. What problem do you have to solve / what is the expected outcome? – Stephan Lechner Oct 12 '17 at 19:01

2 Answers2

1

First of all you used unintialized array, which is UB. And as stated in problem, billboards numbered from 1 to 100. You use that number directly as array index, but array is zero based, so you have out of range problem, which also leads to UB:

 std::vector<bool> billboards( 100 ); // unlike array vector will be properly initialized 
 for(int request:requests) {
    auto &board = billboards[request-1]; // index is zero based
    rejections += board;
    board = true;
 } 
Slava
  • 43,454
  • 1
  • 47
  • 90
0

I solved this problem thanks to you! I added 'for' that set billboards values to false at the beginning of the function and it helped :)

#include<iostream>
#include<vector>
using namespace std;
class AdvertisingAgency{
public:
    int numberOfRejections(vector<int>requests){
        int rejections=0;
        bool billboards[101];
        for(int i=0;i<101;i++){
            billboards[i]=false;
        }
        for(int request:requests){
            if(billboards[request]){
                rejections++;
            }
            else{
                billboards[request]=true;
            }
        }
        return rejections;
    }
};
Revi
  • 50
  • 2
  • 10