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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <iostream>
#include <vector>
#include <iomanip>
void insert_zeroes( std::vector<int>& original_row, std::vector<int>& temporary_row, int limit )
{
if( original_row.size() == temporary_row.size() )
{
std::vector<int> modified_original_row ;
std::vector<int> modified_temporary_row ;
int sum_so_far = 0 ;
for( std::size_t i = 0 ; i < original_row.size() ; ++i )
{
if( temporary_row[i] > limit ) return ; // error in data: give up
sum_so_far += temporary_row[i] ;
if( limit < sum_so_far ) // if sum exceeds limit
{
// append zeroes before writing these values
modified_original_row.push_back(0) ;
modified_temporary_row.push_back(0) ;
sum_so_far = temporary_row[i] ; // and reinitialise sum_so_far
}
modified_original_row.push_back( original_row[i] ) ;
modified_temporary_row.push_back( temporary_row[i] ) ;
}
// append the final zeroes
modified_original_row.push_back(0) ;
modified_temporary_row.push_back(0) ;
// finally, update the rows passed by reference
original_row.swap(modified_original_row) ;
temporary_row.swap(modified_temporary_row) ;
}
}
void insert_zeroes( std::vector< std::vector<int> >& original,
std::vector< std::vector<int> >& temporary,
int limit = 50 )
{
if( original.size() == temporary.size() )
{
for( std::size_t i = 0 ; i < original.size() ; ++i )
insert_zeroes( original[i], temporary[i], limit ) ;
}
}
void print( const std::vector<int>& vec )
{
for( int v : vec ) std::cout << std::setw(4) << v ;
std::cout << '\n' ;
}
void print( std::vector< std::vector<int> >& mtx )
{
for( const auto& row : mtx ) print(row) ;
std::cout << '\n' ;
}
int main()
{
std::vector< std::vector<int> > original =
{
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 },
{ 0, 0, 4, 3, 2, 1, 15, 14, 13, 12, 11, 14, 13, 12, 11, 10 },
{ 0, 1, 5, 7, 8, 9, 3, 4, 6, 9, 18, 11, 5, 7, 9 },
{ 0, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 },
{ 0, 0, 7, 9, 5, 11, 13, 15, 17, 19, 5, 7, 4, 9, 3, 2 }
};
print(original) ;
std::vector< std::vector<int> > temporary =
{
{ 0, 10, 20, 15, 25, 5, 10, 10, 8, 14, 16, 11, 6, 8, 9 },
{ 0, 0, 25, 18, 15, 6, 9, 15, 5, 10, 30, 6, 10, 15, 6, 8 },
{ 0, 10, 10, 10, 15, 5, 18, 18, 8, 5, 13, 15, 6, 14, 1 },
{ 0, 10, 30, 10, 25, 5, 20, 15, 9, 15, 9, 10, 10, 15, 7 },
{ 0, 0, 9, 19, 20, 10, 30, 8, 16, 15, 9, 10, 18, 5, 9, 7 }
};
print(temporary) ;
insert_zeroes( original, temporary, 50 ) ;
std::cout << "\nafter inserting zeroes\n----------------------\n\n" ;
print(original) ;
print(temporary) ;
}
|