[ create a new paste ] login | about

Link: http://codepad.org/4gg8jlY4    [ raw code | output | fork ]

C++, pasted on Oct 29:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <cstdlib>
#include <functional>

// 条件
class Red : public std::binary_function< int, int, bool > {
public:
	result_type operator() ( first_argument_type lhs, second_argument_type rhs ) const {
		return rhs - lhs == 3;
	}
};

// 条件を満たす組み合わせを見つけだすアルゴリズム
template < typename T, typename F >
int combination( T const &beg, T const &end, F const &func ) {
	int count = 0;
	for ( T i = beg; i != end - 1; ++i ) {
		for ( T j = i + 1; j != end; ++j ) {
			if ( func( *i, *j ) ) {
				++count;
				//	std::cout << "(" << *i << "," << *j << ") ";
			}
		}
	}
	return count;
}

int main() {
	using namespace std;

	typedef vector< int > Vec;
	Vec v;

	//	適当な集合を準備する
	int const maxelement = 25;
	srand( ( unsigned int ) time( 0 ) );
	for ( int i = 0; i != maxelement; ++i ) {
		v.push_back( rand() % maxelement );
	}

	cout << "集合 ";
	copy( v.begin(), v.end(), ostream_iterator< Vec::value_type >( cout, "," ) );
	cout << "\n";

	//	集計
	int count = combination( v.begin(), v.end(), Red() );
	cout << "\ncount : " << count << endl;

	return 0;
}


Output:
1
2
3
集合 18,14,3,15,19,3,2,22,10,5,9,16,5,1,10,20,2,13,13,23,7,1,5,2,22,

count : 11


Create a new paste based on this one


Comments: