ranlin/main.cpp

41 lines
875 B
C++
Raw Normal View History

2018-01-23 13:17:40 +01:00
//
// main.cpp
// ranlin
//
// Created by Bob Polis on 05-03-15.
// Copyright (c) 2015 Thalictrum. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <random>
using namespace std;
double next_random() {
static random_device dev;
static default_random_engine engine {dev()};
static uniform_real_distribution<double> dist {0, 1};
return dist(engine);
}
string random_line_from_file(istream& file) {
string line;
string result;
for (int nr {1}; getline(file, line); ++nr) {
if (next_random() * nr < 1.0) {
result = line;
}
}
return result;
}
int main(int argc, const char * argv[]) {
if (argc > 1) {
ifstream infile {argv[1]};
cout << random_line_from_file(infile) << '\n';
} else {
cout << random_line_from_file(cin) << '\n';
}
}