Download PSCSTA Programming Contest

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PSCSTA Programming Contest File Input Notes Remember that you will be given the packet’s example input files (contained in a folder called StudentData) at the beginning of the contest. You should copy these files to your computer. By doing this, you will be able to test your solutions’ output against the sample output provided in the packet. When you are ready for a judge to grade a problem, you will need to change the path to the data file to read from the judge’s flash drive (e.g. E:\JudgesData\input.txt) instead of the folder on your computer. To make this process easier, you may opt to have constants that define the path to your test data (that you copy to your computer at the contest start) and to the judge’s data (when they insert their thumb drive). You can comment/uncomment to easily switch between the two. For example, in C#, you might say: string path = "C:\\Users\\somebody\\Desktop\\StudentData\\"; // your directory //string path = "E:\\JudgesData\\"; // judge’s directory on their flash drive string file = "input.txt"; // specific file for this program then instead of using new StreamReader(“input.txt”), you could use new StreamReader(path + file) Most contest input files are structured as: a number telling you how many data sets are contained in the file, followed by that number of datasets, usually one dataset per line. The file input examples in this packet reflect this general structure. Table of Contents Language Page Number C++ 2 Python 2 Whitespace 2 Perl 3 Racket 3 Java try/catch 4 Java throws 5 C# 6 These file input notes were created by Crystal Hess and Alec McTavish 1 /**************** C++ FILE INPUT ****************/ #include <iostream> #include <fstream> #include <string> using namespace std; int main () { ifstream myfile ("input.txt"); if (myfile.is_open()) { //read in how many data sets you should expect int numSets; myfile >> numSets; for (int i = 0; i < numSets; i++) { // do whatever for each data set int firstToken; myfile >> firstToken; } myfile.close(); } else cout << "Unable to open file"; return 0; } #**************** PYTHON FILE INPUT ****************# #open the file file = open("input.txt","r") #read in how many data sets you should expect datasets = int(file.readline()) #loop that many times for i in range(datasets): #do whatever for each data set x = file.readline() #When reading in data from the text file: #to remove extra newline characters #
x = file.readline().rstrip #to convert to int #
x = int(file.readline()) /**************** WHITESPACE FILE INPUT ****************/ These file input notes were created by Crystal Hess and Alec McTavish 2 #**************** PERL FILE INPUT ****************# # open the file and associate with filehandler open my $file_handler', '<', 'input.txt' or die "Can't open your file: $!\n"; while (<$file_handler>) { # $_ contains each record from the file in turn # do whatever for each data set } /**************** RACKET FILE INPUT ****************/ #lang racket (require 2htdp/batch­io) (define datasets (rest (read­words­and­numbers/line "input.txt"))) ; complete the function process­dataset which takes a dataset ; as an input and prints the result to the screen (define (process­dataset dataset) ; do whatever for each data set (for­each process­dataset datasets) Explanation: read­words­and­numbers/line reads in the input.txt file as a list of datasets, where each dataset is represented as a list of words and numbers. rest gets rid of the first line, since it is usually not useful to know the number of datasets. Other useful methods in the batch­io teachpack: read­file, read­lines, read­words, and read­words/line The function (read­line), called with no inputs, is the best way to read a single line of input for problems where the judge will type the input directly, rather than coming from a file. If you need to mimic Java's rounding, you can do so: ; format­decimal: Number Number ­> String ; format­decimal rounds a given number to a certain level of precision ; (i.e., the number of digits past the decimal point) and produces a string ; Example: (format­decimal 2.545 2) produces "2.55" (define (format­decimal number precision) (define (java­round n) (floor (+ n 1/2))) (define 10p (expt 10 precision)) (real­>decimal­string (/ (java­round (* 10p number)) 10p) precision)) These file input notes were created by Crystal Hess and Alec McTavish 3 /**************** JAVA FILE INPUT #1 USING TRY/CATCH ****************/ import java.io.File; import java.util.Scanner; public class FileInputExample { public static void main(String[] args) { Scanner file = null; try { file = new Scanner(new File("input.txt")); //read in how many data sets you should expect int num = file.nextInt(); //Java hates us: throw away newline after this int file.nextLine(); //loop that many times for(int i = 0; i < num; i++) { //do whatever for each data set //When reading in data from the text file into x, use: // x = file.nextInt() // x = file.nextDouble() // x = file.nextLine() } } catch (Exception e) { //print out the exception if there is one for debugging System.out.println(e); } } } These file input notes were created by Crystal Hess and Alec McTavish 4 /**************** JAVA FILE INPUT #2 USING THROWS ****************/ import java.util.*; import java.io.*; public class FileInputExample { public static void main(String[] args) throws FileNotFoundException { Scanner reader = new Scanner(new File("input.txt")); // Typically need to read in the number of lines to process int number = reader.nextInt(); // throw away newline after this int reader.nextLine(); // loop that many times for(int i = 0; i < num; i++) { //do whatever for each data set //When reading in data from the text file into x, use: // x = file.nextInt() // x = file.nextDouble() // x = file.nextLine() } } } These file input notes were created by Crystal Hess and Alec McTavish 5 /**************** C# FILE INPUT ****************/ using System.IO; using (StreamReader sr = new StreamReader(“input.txt”)) { //read in how many data sets you should expect int datasets = int.Parse(sr.ReadLine()); //loop for each data set from the file for(int i = 0; i < datasets; i++) { //do whatever for each data set // to read in a single piece of data on a line string oneThing = sr.ReadLine(); } } At the top of your code file (above namespace… etc): // put at top of code; needed any time we want to access files using System.IO; Within Main() or any other method, open the appropriate text file (in the appropriate location) for reading: using (StreamReader sr = new StreamReader(path + file)) { // sr is valid until you hit the closing brace of this block } To read a single piece of data on a line: string oneThing = sr.ReadLine(); To split multiple pieces of data (tokens on a single line): string multiple = sr.ReadLine(); // there should be a single space between each token (piece of data) string[] allTokens = multiple.Split(' ');
To specify separators other than spaces use this: string[] allTokens = multiple.Split(' ', '\t', ','); // space, tab, and comma
To keep reading from a file until you’ve read every line of text it contains: while (!sr.EndOfStream) { // read and process lines of text from file... }
You can hand a StreamReader to a method that you call, allowing that method to read text from the file static void MethodThatReadsFromFile(StreamReader reader) { string something = reader.ReadLine(); //... } This method can be called from your code where you first created StreamReader MethodThatReadsFromFile(sr); These file input notes were created by Crystal Hess and Alec McTavish 6