r/dailyprogrammer • • Jul 06 '12

[7/6/2012] Challenge #73 [intermediate]

Write a program that, given an ASCII binary matrix of 0's and 1's like this:

0000000000000000
0000000000000000
0000011001110000
0000001111010000
0000011001110000
0000011011100000
0000000000110000
0000101000010000
0000000000000000
0000000000000000
0000000000000000

Outputs the smallest cropped sub-matrix that still contains all 1's (that is, remove all borders of 0's):

01100111
00111101
01100111
01101110
00000011
10100001
9 Upvotes

28 comments sorted by

View all comments

1

u/aimlessdrive Jul 08 '12

C++: I'm ashamed that I can't wrap my head around some ways to make this more efficient. I experimented with iterators, but you can tell me whether or not it would be quicker to just use integer counters. Pretty inexperienced programmer. All criticism/comments welcome.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(int argc, char** argv) {
	vector<string> matrix;
	string line;
	//read matrix in
	for (int i=0; cin >> line; ++i)	matrix.push_back(line);
	
	//top cropping
	bool cropping = true;
	while (cropping) {
		for (string::iterator stIt = matrix.front().begin(); stIt != matrix.front().end(); ++stIt) {
			if ((*stIt) == '1') {
				cropping = false;
				break;
			}
		}
		if (cropping) matrix.erase(matrix.begin());
	}
	
	//bottom cropping
	cropping = true;
	while (cropping) {
		for (string::iterator stIt = matrix.back().begin(); stIt != matrix.back().end(); ++stIt) {
			if ((*stIt) == '1') {
				cropping = false;
				break;
			}
		}
		if (cropping) matrix.erase(matrix.end());
	}
	
	//left cropping
	cropping = true;
	unsigned int lCap = 0;
	while (cropping) {
		for (lCap = 0; lCap < matrix.front().size(); ++lCap) {
			for (unsigned int j = 0; j < matrix.size(); ++j) {
				if (matrix[j][lCap] == '1') {
					cropping = false;
					break;
				}
			}
			if (!cropping) {
				break;
			}
		}
	}
	//crop it
	for (unsigned int j = 0; j < matrix.size(); ++j) matrix[j] = matrix[j].substr(lCap);
	
	//right cropping
	cropping = true;
	unsigned int rCap = 0;
	while (cropping) {
		for (rCap = matrix.front().size()-1; rCap > 0; --rCap)
		{
			for (unsigned int j = 0; j < matrix.size(); ++j) {
				if(matrix[j][rCap] == '1') {
					cropping = false;
					break;
				}
			}
			if (!cropping) break;
		}
	}
	//crop it
	for (unsigned int j = 0; j < matrix.size(); ++j) matrix[j] = matrix[j].substr(0,rCap+1);
	
	//write out
	for (unsigned int i = 0; i < matrix.size(); ++i) {
		cout << matrix[i] << endl;
	}
	
	return 1;
}