Skip to content

Instantly share code, notes, and snippets.

@cmdcolin
Last active February 5, 2016 14:15
Show Gist options
  • Select an option

  • Save cmdcolin/ef76022a595ce697498f to your computer and use it in GitHub Desktop.

Select an option

Save cmdcolin/ef76022a595ce697498f to your computer and use it in GitHub Desktop.
Programming challenge v1 - find max contiguous product of integers in an array
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
if(argc < 3) {
cout << "Usage: " << argv[0] << " <n> <m> <s>" << endl;
cout << "Generates <n> random numbers to stdout max value <m> using seed <s>" << endl;
return -1;
}
srand (argc==4?atoi(argv[3]):time(NULL));
int n=atoi(argv[1]);
int m=atoi(argv[2]);
while(n--) {
cout << rand()%m << endl;
}
}
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <numeric>
using namespace std;
int main(int argc, char **argv) {
if(argc < 3) {
cerr << "Usage: " << argv[0] << " <filename> <n>" << endl;
cerr << "Finds maximum contiguous product of ints from <filename> of with a set of length <n>" << endl;
return -1;
}
int num;
vector<int> nums;
ifstream f( argv[1] );
if( !f ) {
cerr << "File not found"<<endl;
return -1;
}
while( f>>num ) {
nums.push_back(num);
}
int n = atoi(argv[2]);
int accum = 1;
int max = 0;
for( auto i = nums.begin(); i != nums.end(); i++ ) {
accum = accumulate( i, i+n, 0 );
if( max < accum ) {
cout << "record broken "<<max << " "<<accum<<endl;
max = accum;
}
}
}

contig_product

A challenge by my friend to find the maximum contiguous product of numbers in an array in the fastest way possible. This solution uses a sliding window without any other optimizations...so, nothing fancy here

$ g++ genrand.cpp -o genrand && ./genrand 100 2000 > rand.txt 
$ g++ process.cpp -o process && ./process rand.txt 5
record broken 0 2906
record broken 2906 3301
record broken 3301 3514
record broken 3514 4317
record broken 4317 4702
record broken 4702 4793
record broken 4793 5542
record broken 5542 6277
record broken 6277 7160
record broken 7160 7345
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment