PHP CodeJam Problem - 2010 (Problem B. Reverse Words)

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Code:
[NO-PARSE]#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
#include <algorithm>

/* solves the case in question, and writes the result to the
 * output filestream, where k represents the current case #.
 *
 * Format -> Case #k: {results}
 * ---------------------------------------------------------------------- */
void solve_case(int k, std::ofstream &ofs, std::ifstream &ifs)
{
  std::string s;
  std::getline(ifs, s);

  std::vector<std::string> v;
  std::istringstream isstrm(s);
  std::copy(
    std::istream_iterator<std::string>(isstrm),
    std::istream_iterator<std::string>(),
    std::back_inserter<std::vector<std::string>>(v)
  );
  ofs << "Case #" << k << ": ";
  std::copy(v.rbegin(), v.rend(), std::ostream_iterator<std::string>(ofs, " "));
  ofs << std::endl;
}

/* ---------------------------------------------------------------------- */

int main(int argc, char const *argv[])
{
  if (argc < 2) return 1;

  /* open output file for case results */
  std::ofstream ofs;
  std::string output_name(argv[1]);
  output_name.append("-result.txt");
  ofs.open(output_name.c_str(), std::ofstream::out);
  if (!ofs.is_open())
  {
    std::cerr << "Error: Could not open 'case results.txt' file for write access." << std::endl;
    return 1;
  }

  /* open input file for reading */
  std::ifstream ifs;
  ifs.open(argv[1], std::ifstream::in | std::ifstream::binary);
  if (!ifs.is_open())
  {
    std::cerr << "Error: Could not open input file for read access." << std::endl;
    return 1;
  }

  int N, k = 0;
  ifs >> N; ifs.get();
  do
  {
    solve_case(++k, ofs, ifs);
  }
  while (--N);

  /* close filestreams */
  ifs.close(); ofs.close();

  // std::cout << "Finished!\n"
  //           "Press enter to exit."
  //           << std::endl;

  // std::cin.sync();
  // std::cin.get();
}[/NO-PARSE]

It's that time of year again, time to gear up for CodeJam 2014 in a few weeks. I'm going through problem sets and solving them for a warmup before the qualification round starts in April.

I figured I'd post one of my solutions in case anybody wants to learn or is curious.

If you want to participate when the real thing starts: Google Code Jam

:beerchug2:
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top