I am going through some CodingAbbey problems to learn basic programming tasks, with a focus on taking input from a file, and saving to another. I have just completed this task:
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line. Following lines will contain a pair of numbers to compare each. For Answer please enter the same amount of minimums separated by space, for example:
data:
3 5 3 2 8 100 15
answer:
3 2 15
Here is my code:
using System;
namespace cosnPrjo
{
class MinimumOfTwo
{
const string inputPath = @"/Users/rs/Dropbox/InputFile.txt";
const string outputPath = @"/Users/rs/Dropbox/OutputFile.txt";
const string searchAfterParam = "\n";
static void Main ()
{
string input = readFile (inputPath);
input = input.Substring (input.IndexOf (searchAfterParam) + searchAfterParam.Length);
string[] pairDelims = { "\n" };
string[] paramDelims = { " " };
string[] pairs = input.Split (pairDelims, StringSplitOptions.RemoveEmptyEntries);
string result = "";
foreach (string pair in pairs) {
int numToAppend = 0;
string[] paramas = pair.Split (paramDelims, StringSplitOptions.RemoveEmptyEntries);
int firstNum = Convert.ToInt32 (paramas [0]);
int secondNum = Convert.ToInt32 (paramas [1]);
numToAppend = firstNum < secondNum ? firstNum : secondNum;
result += numToAppend.ToString () + " ";
}
writeFile (outputPath, result.TrimEnd ());
}
static string readFile (string input)
{
return System.IO.File.ReadAllText (input);
}
static void writeFile (string path, string contents)
{
System.IO.File.WriteAllText (path, contents);
}
}
}
My questions are:
- Is this method (reading from and writing to files) an effective and/or sensible way to deal with multi-line input? I find it more cumbersome when I am using the console.
- Should a
StringBuilder
be used to append elements to string in this case? - Is the exercise of ignoring the first number, as I have done here, useful or useless in this context? I don't need to use that number, but should I?
- This code is pretty long for such a small task. Is it more useful to write shorter code for such tasks?