Pairs in an array that sum to 15…

Messy and hacky, should use set rather than map. In reality should use a hash…

#include
#include

using namespace std;

int main() {

vector array;

array.push_back(1);
array.push_back(10);
array.push_back(5);

map exists;
for(size_t n=0;n

Select a random line from a file in a single pass

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <vector>

using namespace std;

void getrandline(string filename,size_t &selected_line_no,string &selected_line) {

  ifstream file(filename.c_str());
  selected_line_no = 0;
  for(size_t n=1;!file.eof();n++) {

    string current_line;
    getline(file,current_line);

    if(file.eof()) break;

    if(rand()%n == 0) { selected_line = current_line; selected_line_no = n-1; }
  }

}

int main(int argc,char **argv) {

  srand(time(NULL));

  vector<size_t> count(100,0); // just for testing, 100 should be > size of the file...
  for(size_t n=0;n<100000;n++) {
   size_t linenum;
   string line;
   getrandline(argv[1],linenum,line);

   count[linenum]++;
   cout << linenum << " " << line << endl;
  }

  for(size_t n=0;n<count.size();n++) {
    cout << n << " " << count[n] << endl;
  }

}

Removing things that occur once only from an array

I wonder if there is a better way…

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

using namespace std;


void remonce(vector<int> &array) {

  map<int,int> counts;

  for(size_t n=0;n<array.size();n++) {
    counts[array[n]]++;
  }

  vector<int> newarray;
  for(size_t n=0;n<array.size();n++) {
    if(counts[array[n]] != 1) {
      newarray.push_back(array[n]);
    }
  }

  array = newarray;
}

int main() {

  vector<int> array;
  array.push_back(4);
  array.push_back(4);
  array.push_back(3);
  array.push_back(3);
  array.push_back(8);
  array.push_back(16);
  array.push_back(8);

  remonce(array);

  for(size_t n=0;n<array.size();n++) {
    cout << array[n] << endl;
  }
}

Check if string palindrome

#include <iostream>
#include <string>

using namespace std;


bool check(string palendrome) {

  size_t limit=0;
  if(palendrome.size()%2 == 0) limit = palendrome.size()/2;
                          else limit = (palendrome.size()-1)/2;

  for(size_t n=0;n<limit;n++) {
    if(palendrome[n] != palendrome[palendrome.size()-n-1]) return false;
  }
  return true;
}

int main() {

  string palendrome1 = "catac";
  bool check1 = check(palendrome1); if(check1 == true) cout << palendrome1 << " is palendromic" << endl; else cout << palendrome1 << " is not palendromic" << endl;

  string palendrome2 = "caac";
  bool check2 = check(palendrome2); if(check2 == true) cout << palendrome2 << " is palendromic" << endl; else cout << palendrome2 << " is not palendromic" << endl;

  string palendrome3 = "zcaacr";
  bool check3 = check(palendrome3); if(check3 == true) cout << palendrome3 << " is palendromic" << endl; else cout << palendrome3 << " is not palendromic" << endl;
}