public CustomerAccount(System.IO.TextReader textIn) { name = textIn.ReadLine(); string balanceText = textIn.ReadLine(); balance = decimal.Parse(balanceText); }
private void Initialize(TextReader input) { rand = new Random(); fortunes = new List<string>(); StringBuilder sb = new StringBuilder(); string line = input.ReadLine(); while (line != null) { if (line == "%") { if (sb.Length > 0) { fortunes.Add(sb.ToString()); sb.Clear(); } } else { if (sb.Length > 0) { sb.Append(' '); } sb.Append(line); } line = input.ReadLine(); } if (sb.Length > 0) { fortunes.Add(sb.ToString()); } }
public void Load(TextReader reader) { var verse = new List<string> (); for (var line = reader.ReadLine (); line != null; line = reader.ReadLine ()) { var tline = line.Trim (); if (tline.Length == 0 || tline [0] == '#') { continue; } if (line [0] == '.' || line [0] == '/' || line [0] == '!') { if (verse.Count > 0) { LoadVerse (verse); } verse = new List<string> (); } verse.Add (line); } if (verse.Count > 0) { LoadVerse (verse); } }
private void Read(TextReader reader) { var line = reader.ReadLine(); ulong commitNumber, tripleCount; if (!UInt64.TryParse(line, out commitNumber)) { throw new BrightstarInternalException( "Error reading statistics record. Could not parse commit number line."); } CommitNumber = commitNumber; line = reader.ReadLine(); if (!UInt64.TryParse(line, out tripleCount)) { throw new BrightstarInternalException( "Error reading statistics record. Could not parse triple count line."); } TotalTripleCount = tripleCount; while (true) { line = reader.ReadLine(); if (String.IsNullOrEmpty(line) || line.Equals("END")) break; var splitIx = line.IndexOf(','); if (UInt64.TryParse(line.Substring(0, splitIx), out tripleCount)) { string predicate = line.Substring(splitIx + 1); PredicateTripleCounts[predicate] = tripleCount; } } }
private void Solve(TextReader reader) { var nTestCases = int.Parse(reader.ReadLine().Trim()); for (int iTestCases = 0; iTestCases < nTestCases; iTestCases++) { var nVines = int.Parse(reader.ReadLine().Trim()); var vines = Enumerable.Repeat(0, nVines) .Select( _ => { var values = reader.ReadLine().Split(' ').Select(int.Parse).ToList(); return new Vine(values[0], values[1], 0); }) .ToList(); var distance = int.Parse(reader.ReadLine().Trim()); vines[0].Height = Math.Min(vines[0].Length, vines[0].Pos); var maxDistance = 0; for (int iVines = 0; iVines < nVines; iVines++) { if (vines[iVines].Height <= 0) { continue; } var d = vines[iVines].Pos + vines[iVines].Height; maxDistance = Math.Max(maxDistance, d); for (int i = iVines + 1; i < nVines && vines[i].Pos <= d; i++) { vines[i].Height = Math.Max( vines[i].Height, Math.Min(vines[i].Length, vines[i].Pos - vines[iVines].Pos)); } } var answer = maxDistance >= distance; Console.WriteLine( "Case #" + (iTestCases + 1) + ": " + (answer ? "YES" : "NO")); } }
/// <summary> /// Read a facet /// </summary> protected virtual Facet ReadFacet(TextReader reader) { Facet facet = new Facet(); // Read the normal if ((facet.Normal = ReadVertex(reader, facetRegex)) == null) return null; // Skip the "outer loop" reader.ReadLine(); // Read the vertices for (int i = 0; i < 3; i++) { var vertice = ReadVertex(reader, verticeRegex); if (vertice == null) return null; facet.Vertices.Add(vertice); } // Read the "endloop" and "endfacet" reader.ReadLine(); reader.ReadLine(); return facet; }
public static Knapsack GetKnapsack(TextReader reader) { Contract.Requires<ArgumentNullException>(reader != null, "reader"); var firstRow = reader.ReadLine(); var firtsRowParts = firstRow.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); int capacity = int.Parse(firtsRowParts[0]); int numberOfItems = int.Parse(firtsRowParts[1]); var items = new List<KnapsackItem>(numberOfItems); while (true) { string row = reader.ReadLine(); if (row == null) { break; } var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var parameters = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray(); items.Add(new KnapsackItem(parameters[0], parameters[1])); } return new Knapsack(items, capacity); }
static TextWriter tw; //= new StreamReader("A-small-attempt3.in"); #endregion Fields #region Methods static void Main(string[] args) { tr = new StreamReader("C-large-1.in"); int n = Convert.ToInt16(tr.ReadLine()); List<TestCase> testCases = new List<TestCase>(); for (; i < n; i++) { TestCase t = new TestCase(); string[] temp2 = tr.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //string[] temp2 = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); t.lowLimit = Convert.ToInt64(temp2[0]); t.upperLimit = Convert.ToInt64(temp2[1]); testCases.Add(t.processInput()); } tw = new StreamWriter("output.txt"); i = 0; for (; i < testCases.Count-1; i++) { tw.WriteLine("Case #{0}: {1}", (i + 1), testCases[i].output); } tw.Write("Case #{0}: {1}", (i + 1), testCases[i].output); tr.Close(); tw.Close(); //Console.ReadLine(); }
public Terrain(Stage theStage, string label, string terrainDataFile) : base(theStage, label) { constructorInit(); // common constructor initialization code, base call sets "stage" // read vertex data from "terrain.dat" file System.IO.TextReader file = System.IO.File.OpenText(terrainDataFile); file.ReadLine(); // skip the first description line x y z r g b int i = 0; // index for vertex[] string line; string[] token; for (int z = 0; z < height; z++) { for (int x = 0; x < width; x++) { line = file.ReadLine(); token = line.Split(' '); terrainHeight[x, z] = int.Parse(token[1]) * multiplier; // Y vertex[i] = new VertexPositionColor( new Vector3(int.Parse(token[0]) * spacing, terrainHeight[x, z], int.Parse(token[2]) * spacing), // position new Color(int.Parse(token[3]), int.Parse(token[4]), int.Parse(token[5]))); // material i++; } } file.Close(); makeIndicesSetData(); }
public static DirectedWeightedGraph GetGraph(TextReader reader, bool makeUndirected) { if (reader == null) throw new ArgumentNullException("reader"); var graph = new DirectedWeightedGraph(); reader.ReadLine(); while (true) { string row = reader.ReadLine(); if (row == null) { break; } var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray(); var node1 = numbers[0] - 1; var node2 = numbers[1] - 1; var weight = numbers[2]; graph.AddEdge(node1, node2, weight); if (makeUndirected) { graph.AddEdge(node2, node1, weight); } } return graph; }
static void ReadText(TextReader input) { string line; string[] parts; line = input.ReadLine(); System.Console.WriteLine(">> " + line); line = input.ReadLine(); parts = line.Split(' '); System.Console.WriteLine( ">> int: {0} double: {1} bool: {2}", int.Parse(parts[1]), double.Parse(parts[3]), bool.Parse(parts[5])); line = input.ReadLine(); parts = line.Split(','); bool writeSeparator = false; System.Console.Write(">> "); foreach (string actPart in parts) { if (writeSeparator) System.Console.Write(", "); writeSeparator = true; System.Console.Write(int.Parse(actPart)); } System.Console.WriteLine(); string actStrValue; for(;;) { actStrValue = input.ReadLine(); if (actStrValue == null) break; actStrValue = actStrValue.Trim(); System.Console.WriteLine(">> \"{0}\"", actStrValue); } }
public void LoadDataFile() { fileReader = new StreamReader(filename); if (System.IO.File.Exists(filename) == false) { throw new System.InvalidOperationException("Error: " + filename + " could not be found."); } saveData.Clear(); string line = ""; string read = ""; line = fileReader.ReadLine(); while (line != null) { for (int i = 0; i < line.Length; i++) { if (line[i] != '=') { read += line[i]; } else { string status = line.Substring(i+1, (line.Length - (i+1) )); saveData.Add(read, Convert.ToBoolean(status)); } } read = ""; line = fileReader.ReadLine(); } fileReader.Close(); }
//private static void Main(string[] args) { // new ProblemB().Solve(Console.In); //} private void Solve(TextReader input) { var ns = input.ReadLine().Split(' ').ToArray(); var ns2 = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; var ns3 = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; var count = int.Parse(input.ReadLine()); var vs = new List<string>(); for (int i = 0; i < count; i++) { vs.Add(input.ReadLine().Trim()); } var answer = vs.Select( v => { var result = v; foreach (var t in ns.Zip(ns2, Tuple.Create)) { result = result.Replace(t.Item1, t.Item2); } foreach (var t in ns2.Zip(ns3, Tuple.Create)) { result = result.Replace(t.Item1, t.Item2); } return Tuple.Create(v, result); }).Select(t => Tuple.Create(t.Item1, int.Parse(t.Item2))).OrderBy(t => t.Item2); foreach (var t in answer) { Console.WriteLine(t.Item1); } }
public void Answer(TextReader input) { string line = input.ReadLine(); int nOfCases = Convert.ToInt32(line); bool[] DP = new bool[100000000000000]; for (int caseNo = 1; caseNo <= nOfCases; caseNo++) { //Size line = input.ReadLine(); long low = Convert.ToInt64(line.Split(' ')[0]); long hi = Convert.ToInt64(line.Split(' ')[1]); long result = 0; for (long i = 1; i * i <= hi; i++) { if(i * i >= low) { if (IsPalindrome(i) && IsPalindrome(i * i)) { DP[i] = true; result++; } } } Console.Out.WriteLine("Case #{0}: {1}", caseNo, result); } }
//private static void Main(string[] args) { // new ProblemC().Solve(Console.In); //} private void Solve(TextReader input) { var nad = input.ReadLine().Split(' ').Select(int.Parse).ToList(); int n = nad[0]; double a = nad[1]; double d = nad[2]; var lastTime = 0.0; for (int i = 0; i < n; i++) { var tv = input.ReadLine().Split(' ').Select(int.Parse).ToList(); double startTime = tv[0]; double maxSpeed = tv[1]; var maxSpeedTime = maxSpeed / a; var time = startTime; var maxSpeedDistance = maxSpeedTime * maxSpeedTime * a / 2; if (maxSpeedDistance >= d) { time += Math.Sqrt(d * 2 / a); } else { time += maxSpeedTime; time += (d - maxSpeedDistance) / maxSpeed; } if (lastTime <= time) { lastTime = time; } Console.WriteLine( lastTime.ToString(new CultureInfo("ja-JP", false))); } }
public void Parse(TextReader authorsFileStream) { if (authorsFileStream != null) { int lineCount = 0; string line = authorsFileStream.ReadLine(); while (line != null) { lineCount++; if (!line.StartsWith("#")) { //regex pulled from git svn script here: https://github.com/git/git/blob/master/git-svn.perl Regex ex = new Regex(@"^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$"); Match match = ex.Match(line); if (match.Groups.Count != 4 || String.IsNullOrWhiteSpace(match.Groups[1].Value) || String.IsNullOrWhiteSpace(match.Groups[2].Value) || String.IsNullOrWhiteSpace(match.Groups[3].Value)) { throw new GitTfsException("Invalid format of Authors file on line " + lineCount + "."); } else { if (!authors.ContainsKey(match.Groups[1].Value)) { //git svn doesn't trim, but maybe this should? authors.Add(match.Groups[1].Value, new Author() { Name = match.Groups[2].Value, Email = match.Groups[3].Value }); } } } line = authorsFileStream.ReadLine(); } } }
public void Answer(TextReader input) { string line = input.ReadLine(); int nOfCases = Convert.ToInt32(line); for (int caseNo = 1; caseNo <= nOfCases; caseNo++) { //Init board char[][] board = new char[4][]; for (int i = 0; i < 4; i++) { board[i] = new char[4]; } //Read board for (int row = 0; row < 4; row++) { line = input.ReadLine(); board[row][0] = line[0]; board[row][1] = line[1]; board[row][2] = line[2]; board[row][3] = line[3]; } //Blank line input.ReadLine(); string result = EvalBoard(board); Console.Out.WriteLine("Case #{0}: {1}", caseNo, result); } }
/// <summary> /// Creates a <see cref="ReadOnlyCollection<VerificationError>" /> based /// on the output of peverify. /// </summary> /// <param name="peVerifyOutput">The output from peverify.</param> /// <returns>A collection of errors.</returns> public static ReadOnlyCollection<VerificationError> Create(TextReader peVerifyOutput) { var errors = new List<VerificationError>(); if (peVerifyOutput == null) return errors.AsReadOnly(); var peOutputLine = peVerifyOutput.ReadLine(); while (peOutputLine != null) { peOutputLine = peOutputLine.Replace("\0", string.Empty); if (peOutputLine.Length > 0) { var error = VerificationError.Create(peOutputLine); if (error != null) errors.Add(error); } peOutputLine = peVerifyOutput.ReadLine(); } return errors.AsReadOnly(); }
/// <summary>Read in rating data from a TextReader</summary> /// <param name="reader">the <see cref="TextReader"/> to read from</param> /// <param name="user_mapping">mapping object for user IDs</param> /// <param name="item_mapping">mapping object for item IDs</param> /// <param name="ignore_first_line">if true, ignore the first line</param> /// <returns>the rating data</returns> public static IRatings Read(TextReader reader, IMapping user_mapping = null, IMapping item_mapping = null, bool ignore_first_line = false) { if (user_mapping == null) user_mapping = new IdentityMapping(); if (item_mapping == null) item_mapping = new IdentityMapping(); if (ignore_first_line) reader.ReadLine(); var ratings = new Ratings(); string line; while ( (line = reader.ReadLine()) != null ) { if (line.Length == 0) continue; string[] tokens = line.Split(Constants.SPLIT_CHARS); if (tokens.Length < 3) throw new FormatException("Expected at least 3 columns: " + line); int user_id = user_mapping.ToInternalID(tokens[0]); int item_id = item_mapping.ToInternalID(tokens[1]); float rating = float.Parse(tokens[2], CultureInfo.InvariantCulture); ratings.Add(user_id, item_id, rating); } ratings.InitScale(); return ratings; }
public void Answer(TextReader input) { string line = input.ReadLine(); int nOfCases = Convert.ToInt32(line); for (int caseNo = 1; caseNo <= nOfCases; caseNo++) { //Read Credit amount line = input.ReadLine(); int c = Convert.ToInt32(line); //Read itens number line = input.ReadLine(); //Read itens line = input.ReadLine(); String[] itens = line.Split(' '); int count = 1; Mapping[] intItens = (from x in itens select new Mapping {Value = Convert.ToInt32(x), OldPos = count++}).OrderBy(x => x.Value).ToArray(); int[] solution = FindItens(intItens, c); Console.Out.WriteLine( String.Format("Case #{0}: {1} {2}", caseNo, solution[0], solution[1]) ); } }
/// <summary> /// Parses the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <returns></returns> /// <remarks></remarks> public Modification[] Parse(TextReader reader, DateTime from, DateTime to) { var mods = new List<Modification>(); string currentLine = reader.ReadLine(); while (currentLine != null) { // TODO - do it all with a regex? if (currentLine.Contains(DELETED_DIR_TAG)) { mods.Add(ParseDeletedDirectory(currentLine)); } else if (currentLine.Contains(DELETED_FILE_TAG)) { mods.Add(ParseDeletedFile(currentLine)); } else if (currentLine.Contains(ADDED_FILE_TAG)) { mods.Add(ParseAddedFile(currentLine)); } else if (currentLine.Contains(UPDATED_FILE_TAG)) { mods.Add(ParseUpdatedFile(currentLine)); } currentLine = reader.ReadLine(); } return mods.ToArray(); }
private bool ParseRaw(TextReader reader) { var values = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); string current; while (!string.IsNullOrEmpty(current = reader.ReadLine())) { var parts = current.Split(':'); if (parts.Length != 2) continue; values.Add(parts[0].Trim(), parts[1].Trim()); } while (string.IsNullOrEmpty(current)) { current = reader.ReadLine(); } PostBody = current + reader.ReadToEnd(); if (values.ContainsKey("title")) Title = values["title"]; if (values.ContainsKey("publish")) { var dto = DateTimeOffset.ParseExact(values["publish"], "yyyy.MM.dd HH.mm 'UTC' zzz", CultureInfo.InvariantCulture); Publish = dto.UtcDateTime; } if (values.ContainsKey("tags")) Tags = values["tags"].Split(',').Select(s => s.Trim().ToLowerInvariant()).ToList(); return !string.IsNullOrEmpty(Title) && (Tags != null) && !string.IsNullOrEmpty(PostBody); }
public TransactionImportResult Import(TextReader reader) { var parsed = new List<Transaction>(); var failed = new List<string>(); var line = reader.ReadLine(); while (line != null) { if (!string.IsNullOrEmpty(line)) { Transaction transaction; if (TryParseTransaction(line, out transaction)) parsed.Add(transaction); else failed.Add(line); } line = reader.ReadLine(); } if (parsed.Count > 0) { ImportTransactions(parsed); } return new TransactionImportResult { TotalRecordCount = parsed.Count + failed.Count, TotalImported = parsed.Count, Failed = failed }; }
public void Answer(TextReader input) { string line = input.ReadLine(); int nOfCases = Convert.ToInt32(line); for (int caseNo = 1; caseNo <= nOfCases; caseNo++) { //Size line = input.ReadLine(); long r = Convert.ToInt64(line.Split(' ')[0]); long t = Convert.ToInt64(line.Split(' ')[1]); var result = 1; var used = 0.0; while(used < t) { used += Math.Pow(r + 1, 2) - Math.Pow(r, 2); if(used > t) break; result++; r += 2; } Console.Out.WriteLine("Case #{0}: {1}", caseNo, result); } }
public void LoadModelProperties(IModel model, TextReader reader) { var svdModel = model as ISvdModel; if (svdModel == null) return; //get feature count var line = reader.ReadLine(); if (line == null) throw new ArgumentException("File is not a valid ISvdModel."); var featureCount = int.Parse(line.Split(new[] {'='}, StringSplitOptions.None)[1]); //get user count line = reader.ReadLine(); if (line == null) throw new ArgumentException("File {0} is not a valid ISvdModel."); var userCount = int.Parse(line.Split(new[] {'='}, StringSplitOptions.None)[1]); svdModel.UserFeatures = new float[featureCount,userCount]; //get artist count line = reader.ReadLine(); if (line == null) throw new ArgumentException("File {0} is not a valid ISvdModel."); var artistCount = int.Parse(line.Split(new[] {'='}, StringSplitOptions.None)[1]); svdModel.ArtistFeatures = new float[featureCount,artistCount]; }
/// <summary>Read in rating data which will be interpreted as implicit feedback data from a TextReader</summary> /// <param name="reader">the TextReader to be read from</param> /// <param name="rating_threshold">the minimum rating value needed to be accepted as positive feedback</param> /// <param name="user_mapping">user <see cref="IMapping"/> object</param> /// <param name="item_mapping">item <see cref="IMapping"/> object</param> /// <param name="ignore_first_line">if true, ignore the first line</param> /// <returns>a <see cref="IPosOnlyFeedback"/> object with the user-wise collaborative data</returns> static public IPosOnlyFeedback Read(TextReader reader, float rating_threshold, IMapping user_mapping = null, IMapping item_mapping = null, bool ignore_first_line = false) { if (user_mapping == null) user_mapping = new IdentityMapping(); if (item_mapping == null) item_mapping = new IdentityMapping(); if (ignore_first_line) reader.ReadLine(); var feedback = new PosOnlyFeedback<SparseBooleanMatrix>(); string line; while ((line = reader.ReadLine()) != null) { if (line.Trim().Length == 0) continue; string[] tokens = line.Split(Constants.SPLIT_CHARS); if (tokens.Length < 3) throw new FormatException("Expected at least 3 columns: " + line); int user_id = user_mapping.ToInternalID(tokens[0]); int item_id = item_mapping.ToInternalID(tokens[1]); float rating = float.Parse(tokens[2], CultureInfo.InvariantCulture); if (rating >= rating_threshold) feedback.Add(user_id, item_id); } return feedback; }
/* ----------------------------------------------------------------- */ /// Run /* ----------------------------------------------------------------- */ public override void Run(TextReader src) { var buffer = new StringBuilder(); for (var line = src.ReadLine(); line != null; line = src.ReadLine()) { if (line.Length == 0 || this.HasSymbol(line)) { if (buffer.Length > 0) { this._elements.Add(new Element(ElementType.Paragraph, 0, buffer.ToString())); buffer.Remove(0, buffer.Length); } if (line.Length == 0) continue; else if (line[0] == '*') this.ParseBasicElement(line, ElementType.Section); else if (line[0] == '-') this.ParseBasicElement(line, ElementType.List); else if (line[0] == '+') this.ParseBasicElement(line, ElementType.NumericList); else if (line[0] == '#') this.ParseImage(line); } else { if (line[line.Length - 1] == '~') line = line.Substring(0, line.Length - 1) + "\r\n"; buffer.Append(line); } } if (buffer.Length > 0) { this._elements.Add(new Element(ElementType.Paragraph, 0, buffer.ToString())); buffer.Remove(0, buffer.Length); } }
public static List<Hook> ParseHooks(TextReader reader) { var hooks = new List<Hook>(); var currentLine = reader.ReadLine(); while (currentLine != null) { if (currentLine[0] == '"') { var cmdEndIndex = currentLine.IndexOf('"', 1); if (cmdEndIndex < 0) throw new HooksParserException("Unterminated quotes."); if (currentLine.Length > cmdEndIndex + 1 && currentLine[cmdEndIndex + 1] != ' ') throw new HooksParserException("Command and argument not separated by a space."); if (currentLine.Length <= cmdEndIndex + 2) hooks.Add(new Hook() { Command = currentLine.Substring(1, cmdEndIndex - 1) }); else hooks.Add(new Hook() { Command = currentLine.Substring(1, cmdEndIndex - 1), Arguments = currentLine.Substring(cmdEndIndex + 2, currentLine.Length - (cmdEndIndex + 2)) }); } else { var spaceIndex = currentLine.IndexOf(' '); if (spaceIndex < 0 || spaceIndex >= currentLine.Length - 1) hooks.Add(new Hook() { Command = currentLine }); else hooks.Add(new Hook() { Command = currentLine.Substring(0, spaceIndex), Arguments = currentLine.Substring(spaceIndex + 1, currentLine.Length - (spaceIndex + 1)) }); } currentLine = reader.ReadLine(); } return hooks; }
Read(TextReader reader) { var candidates = new Dictionary<int, IList<int>>(); string line; while ( (line = reader.ReadLine()) != null ) { string[] tokens = line.Split('|'); int user_id = int.Parse(tokens[0]); int num_ratings = int.Parse(tokens[1]); // number of ratings for this user var user_candidates = new int[num_ratings]; for (int i = 0; i < num_ratings; i++) { line = reader.ReadLine(); user_candidates[i] = int.Parse(line); } candidates.Add(user_id, user_candidates); } return candidates; }
public static TestCaseConfig Read(TextReader reader) { var line = reader.ReadLine().Trim(); Assert.AreEqual("/*---", line); var lines = new List<string>(); string rawLine; while((line = (rawLine = reader.ReadLine()).Trim()) != "---" && line != "*/") lines.Add(rawLine); var vson = string.Join("\r\n", lines); var config = JsonConvert.DeserializeObject<TestCaseConfig>(vson); if(line == "---") { // read in expected console output lines.Clear(); while((line = (rawLine = reader.ReadLine()).Trim()) != "*/") lines.Add(rawLine); config.VerifyConsoleOutput = true; config.ExpectedConsoleOutput = string.Join("\r\n", lines); } return config; }
//public static void Main(string[] args) { // new ProblemC().Solve(Console.In); //} private void Solve(TextReader input) { var nx = input.ReadLine().Split(' ').Select(int.Parse).ToList(); var n = nx[0]; var x = nx[1]; var values = input.ReadLine().Split(' ').Select(int.Parse) .OrderBy(i => i) .ToList(); var counts = new int[3]; foreach (var value in values) { counts[value.CompareTo(x) + 1]++; } var mid = (values.Count - 1) / 2; if (values[mid] == x) { Console.WriteLine(0); } else if (values[mid] < x) { // 000xx2 Console.WriteLine(counts[0] - (counts[2] + counts[1]) + 1); } else { // 0xx2222 Console.WriteLine(counts[2] - (counts[0] + counts[1])); } }
public static void Answer(TextReader reader) { int n = Convert.ToInt32(reader.ReadLine()); int[] coordinates = reader.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToArray(); List<Line> lines = new List<Line>(); for (int index = 0; index < coordinates.Length - 1; index++) { int a = coordinates[index]; int b = coordinates[index + 1]; lines.Add(new Line {From = Math.Min(a,b), To = Math.Max(a,b)}); } for (int i = 0; i < lines.Count; i++) { for(int j = 0; j< lines.Count; j++) { if (intersect(lines[i], lines[j])) { Console.WriteLine("yes"); return; } } } Console.WriteLine("no"); }
public async System.Threading.Tasks.Task InputLoop() { string input = null; while (!nameof(Commands.Quit).Equals(input, StringComparison.OrdinalIgnoreCase)) { txtOut.WriteLine("Syntax: Origin-Destination outDate [inDate]"); txtOut.Write(">>"); input = txtIn.ReadLine(); await Run(input); } }
public static DictionaryBank Load(System.IO.TextReader textIn) { DictionaryBank result = new DictionaryBank(); string countString = textIn.ReadLine(); int count = int.Parse(countString); for (int i = 0; i < count; i++) { string className = textIn.ReadLine(); IAccount account = AccountFactory.MakeAccount(className, textIn); result.StoreAccount(account); } return(result); }
protected bool LoadRecord(System.IO.TextReader reader) { _data.Content.Clear(); int contentMultiRecordInterval = _format.ContentMultiRecordInterval; if (_format.IsContentMultiRecord == false) { contentMultiRecordInterval = 1; } for (int i = 0; i < contentMultiRecordInterval; i++) { string line; try { line = reader.ReadLine(); } catch { line = string.Empty; return(false); } if (line == null) { return(false); } string[] valueAry = this.SplitString(line, _format.HeaderColumnSeparator); _data.SetContent(i, valueAry); } return(true); }
private void IRCInputProcedure(System.IO.TextReader input, System.Net.Sockets.NetworkStream networkStream) { while (!stopThreads) { //Debug.Log(networkStream.DataAvailable); if (networkStream.DataAvailable) { buffer = input.ReadLine(); //Debug.Log(buffer); if (buffer.Contains("PRIVMSG #")) { lock (recievedMsgs) { recievedMsgs.Add(buffer); } } if (buffer.StartsWith("PING ")) { SendCommand(buffer.Replace("PING", "PONG")); } if (buffer.Split(' ')[1] == "001") { SendCommand("JOIN #" + channelName.ToLower()); } } } }
static int cos_io() { // Standard input stream System.IO.TextReader stdin = In; WriteLine("x cos(x)\n"); string s = string.Empty; double x = 0; double cosx = 0; while (true) { s = stdin.ReadLine(); if (s == null) { break; } x = double.Parse(s); cosx = Cos(x); WriteLine("{0} {1}\n", x, cosx); } return(0); }
/*************************************************************************************************************************/ public void read_throttle_values() { string temp_string; Log.PushStackInfo("FMRS_THL.read_throttle_values", "FMRS_THL_Rep: entering read_throttle_values()"); Log.dbg("FMRS_THL_Rep: read throttle values"); for (int i = 0; i < 1000; i++) { temp_string = reader.ReadLine(); if (temp_string.Contains("EOF")) { EOF = true; Log.dbg("FMRS_THL_Rep: EOF"); break; } else if (temp_string.Contains("#")) { continue; } Throttle_Replay.Enqueue(new entry(temp_string)); } Log.dbg("FMRS_THL_Rep: buffer size = {0}" + Throttle_Replay.Count); Log.PopStackInfo("FMRS_THL_Rep: leave read_throttle_values()"); }
static int Main() { System.Console.Write("Part B:\n"); // Dmitri did some funky magic System.IO.TextReader stdin = System.Console.In; System.IO.TextWriter stdout = System.Console.Out; //System.IO.TextWriter stderr = System.Console.Error; do { string s = stdin.ReadLine(); if (s == null) { break; } string[] words = s.Split(' ', ',', '\t'); foreach (var word in words) { double x = double.Parse(word); stdout.WriteLine("{0} {1} {2}", x, Math.Sin(x), Math.Cos(x)); } }while(true); return(0); }
static void ARPScan(ScanOptions options) { Dictionary <IPAddress, List <ArpEntry> > results = new Dictionary <IPAddress, List <ArpEntry> >(); IEnumerable <string> targets; if (options.FromFile) { List <string> targetList = new List <string>(); foreach (string filename in options.StringSeq) { using (System.IO.TextReader r = System.IO.File.OpenText(filename)) { string s = String.Empty; while ((s = r.ReadLine()) != null) { string[] separators = options.separator == "" ? new string[] { System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator } : new string[] { options.separator }; string[] lineElts = s.Split(separators, StringSplitOptions.RemoveEmptyEntries); if (lineElts.Length == 1) //IP only { targetList.Add(lineElts[0]); } else if (lineElts.Length == 2) //Target name,IP { targetList.Add(lineElts[1]); } } } } targets = targetList; } else { targets = options.StringSeq; } foreach (string target in targets) { Dictionary <IPAddress, List <ArpEntry> > scanresult = ScanTarget(target, options); results = results.Union(scanresult).ToDictionary(k => k.Key, v => v.Value); } if (options.OutputFileName != "") { OutputToCSV(results, options); } else { foreach (IPAddress ipaddr in results.Keys) { foreach (ArpEntry entry in results[ipaddr]) { Console.WriteLine("On {0}, IP {1} : MAC {2}", ipaddr, entry.ipEntry.AddressList[0], entry.physAddress); } } Console.ReadLine(); } }
private void IRCInputProcedure(System.IO.TextReader input, System.Net.Sockets.NetworkStream networkStream) { while (!stopThreads) { if (!networkStream.DataAvailable) { continue; } buffer = input.ReadLine(); //was message? if (buffer.Contains("PRIVMSG #")) { lock (recievedMsgs) { recievedMsgs.Add(buffer); } } //Send pong reply to any ping messages if (buffer.StartsWith("PING ")) { SendCommand(buffer.Replace("PING", "PONG")); } //After server sends 001 command, we can join a channel if (buffer.Split(' ')[1] == "001") { SendCommand("JOIN #" + GuestManager.TwitchNameText); } } }
IEnumerator Refresh() { while (true) { Debug.Log(compare); //Split command line input to only display message if (compare != buf) { buf = input.ReadLine(); compare = buf; command = buf.Split(splitter)[buf.Split(splitter).Length - 1]; //Display received irc message Debug.Log(buf); //Filter messages switch (command) { case "bomb": gameCommand = "bomb"; break; case "up": gameCommand = "up"; break; case "down": gameCommand = "down"; break; case "left": gameCommand = "left"; break; case "right": gameCommand = "right"; break; //Close IRC Stream case "quit": input.Close(); output.Close(); sock.Close(); StopCoroutine("Refresh"); break; } /* if (buf.Split(' ')[1] == "001") * { * output.Write( * "MODE " + nick + " +B\r\n" + * "JOIN " + chan + "\r\n" * ); * output.Flush(); * } * */ } yield return(new WaitForSeconds(0.1f)); } }
public void LoadStateText(System.IO.TextReader reader) { string hex = reader.ReadLine(); byte[] state = new byte[hex.Length / 2]; state.ReadFromHex(hex); LoadStateBinary(new BinaryReader(new MemoryStream(state))); }
/// <summary> /// Read in the set of nodes and their connectivity /// </summary> /// <param name="reader"></param> private void readConnectivity(System.IO.TextReader reader) { _nodes = new Dictionary <string, GraphNode>(); while (reader.Peek() >= 0) { processLine(reader.ReadLine()); } }
/// <summary> /// Read in all the angles into the cache from the supplied open reader /// </summary> /// <param name="reader"></param> private void readAngles(System.IO.TextReader reader) { _dihedrals = new Dictionary <string, float>(); while (reader.Peek() >= 0) { processLine(reader.ReadLine()); } }
public static HashBank Load(System.IO.TextReader textIn) { HashBank result = new HashBank(); string countString = textIn.ReadLine(); int count = int.Parse(countString); for (int i = 0; i < count; i++) { // CustomerAccount account = CustomerAccount.Load(textIn); // Override using factory class to create bank accounts string className = textIn.ReadLine(); IAccount account = AccountFactory.MakeAccount(className, textIn); result.bankHashtable.Add(account.GetName(), account.GetBalance()); } return(result); }
public override void Init(System.IO.TextReader r) { string[] z = r.ReadLine().Split(' '); n = int.Parse(z[0]); m = int.Parse(z[1]); olddirs = new string[n]; newdirs = new string[m]; for (int i = 0; i < n; i++) { olddirs[i] = r.ReadLine(); } for (int i = 0; i < m; i++) { newdirs[i] = r.ReadLine(); } }
/// <summary> /// Converts a map from HOG to gwmap format. /// </summary> /// <param name="Stream"></param> /// <returns></returns> public static String Convert(System.IO.TextReader Stream) { var dim = Stream.ReadLine( ).Trim( ).Split( ); int H = int.Parse(dim[0]); int W = int.Parse(dim[1]); Stream.ReadLine( ); string[] map = new string[H]; for (int i = 0; i < H; i++) { map[i] = Stream.ReadLine( ); } Random Gen = new Random( ); int x, y, dx, dy; do { x = Gen.Next(W); y = Gen.Next(H); } while (map[y][x].Equals('#')); do { dx = Gen.Next(W); dy = Gen.Next(H); } while (map[dy][dx].Equals('#')); var ca = map[y].ToCharArray( ); ca[x] = '*'; map[y] = new String(ca); for (int i = 0; i < H; i++) { map[i] = map[i].Replace(' ', '_'); } StringBuilder sb = new StringBuilder( ); sb.AppendLine(W.ToString( )); sb.AppendLine(H.ToString( )); sb.AppendFormat("{0} {1} {2} {3}\r\n", x, y, dx, dy); sb.AppendLine("--- end units ---"); foreach (var line in map) { sb.AppendLine(line); } return(sb.ToString( )); }
public void LoadStateText(System.IO.TextReader reader) { CheckDisposed(); string hex = reader.ReadLine(); byte[] state = new byte[hex.Length / 2]; state.ReadFromHexFast(hex); LoadStateBinary(new System.IO.BinaryReader(new System.IO.MemoryStream(state))); }
public static Account Load( System.IO.TextReader textIn) { Account result = null; try { string name = textIn.ReadLine(); string balanceText = textIn.ReadLine(); decimal balance = decimal.Parse(balanceText); result = new Account(name, balance); } catch { return(null); } return(result); }
public TestTokenizer(System.IO.TextReader reader) : base(reader) { //Caution: "Reader" is actually of type "ReusableStringReader" and some //methods (for ex. "ReadToEnd", "Peek", "ReadLine") is not implemented. Assert.AreEqual("ReusableStringReader", reader.GetType().Name); Assert.AreEqual("First Line", reader.ReadLine(), "\"ReadLine\" method is not implemented"); Assert.AreEqual("Second Line", reader.ReadToEnd(), "\"ReadToEnd\" method is not implemented"); }
private string GetLine(System.IO.TextReader reader) { var result = string.Empty; do { result = reader.ReadLine(); } while (result.Trim().StartsWith("//")); return(result); }
static void Main(string[] args) { System.IO.TextReader r = Console.In; int t = int.Parse(r.ReadLine()); for (int i = 0; i < t; i++) { string [] s = r.ReadLine().Split(' '); int a1 = int.Parse(s[0]); int a2 = int.Parse(s[1]); int b1 = int.Parse(s[2]); int b2 = int.Parse(s[3]); int ret = 0; for (int a = a1; a <= a2; a++) { for (int b = b1; b <= b2; b++) { if (a > b) { if (simple(a, b)) { ret++; } } if (b > a) { if (simple(b, a)) { ret++; } } } } Console.WriteLine("Case #{0}: {1}", i + 1, ret); } }
int[] readint(System.IO.TextReader r) { string[] x = (r.ReadLine().Trim().Split(' ')); int[] y = new int[x.Length]; for (int i = 0; i < y.Length; i++) { y[i] = int.Parse(x[i]); } return(y); }
/// <summary> /// 读入谱面和动画信息 /// </summary> /// <param name="reader"></param> /// <param name="isEditorMode">目前没使用</param> public void ReadCSV(string _sName, System.IO.TextReader reader, bool isEditorMode = false) { string line; //多少行,调试用 int line_number = 0; while ((line = reader.ReadLine()) != null) //-读取一行 { line_number++; string[] lineCells = line.Split(','); //-按逗号分割 switch (lineCells[0]) { case "beatPerSecond": //-每秒拍数= BPM / 60 songInfo.beatPerSecond = float.Parse(lineCells[1]); break; case "beatPerBar": //-每个小节的节拍数量 songInfo.beatPerBar = float.Parse(lineCells[1]); break; case "scoringUnitSequenceRegion-Begin": line_number = ReadCSV_OnBeatAction(reader, line_number, int.Parse(lineCells[1])); break; case "stagingDirectionSequenceRegion-Begin": //-舞台活动开始 ReadCSV_StagingDirection(reader); break; case "include": //-如果是include,用递归的方式继续读一下个信息 TextReader textReader; #if UNITY_EDITOR if (isEditorMode)//-没啥用 { textReader = File.OpenText("Assets/Resources/" + _sName + lineCells[1] + ".txt"); } else #endif { string data = System.Text.Encoding.UTF8.GetString ( (Resources.Load(_sName + lineCells[1]) as TextAsset).bytes ); textReader = new StringReader(data); } Debug.Log("include :" + lineCells[1]); ReadCSV(_sName, textReader); break; } } }
public PosEventReader(System.IO.TextReader data, IPosContextGenerator contextGenerator) { mContextGenerator = contextGenerator; mTextReader = data; string nextLine = mTextReader.ReadLine(); if (nextLine != null) { AddEvents(nextLine); } }
/// <summary> /// 从文件流中读取 /// </summary> /// <param name="reader">已经打开的流对象</param> public Graph(System.IO.TextReader reader) { //标准的图 string V = reader.ReadLine();//点数 adj = new Bag <Tuple <int, double> > [int.Parse(V)]; for (int i = 0; i < adj.Length; ++i) { adj[i] = new Bag <Tuple <int, double> >(); } string E = reader.ReadLine();//边数 int ie = int.Parse(E); this.V = adj.Length; this.E = ie; for (int i = 0; i < ie; ++i) { AddEdge(reader.ReadLine()); } reader.Close(); }
/// <summary> Reads lines from a Reader and adds every line as an entry to a HashSet (omitting /// leading and trailing whitespace). Every line of the Reader should contain only /// one word. The words need to be in lowercase if you make use of an /// Analyzer which uses LowerCaseFilter (like StandardAnalyzer). /// </summary> /// <param name="reader">Reader containing the wordlist</param> /// <returns>A HashSet with the reader's words</returns> public static ISet <string> GetWordSet(System.IO.TextReader reader) { var result = Support.Compatibility.SetFactory.CreateHashSet <string>(); System.String word; while ((word = reader.ReadLine()) != null) { result.Add(word.Trim()); } return(result); }
/// <summary> /// /// </summary> /// <param name="context_name"></param> /// <param name="stringCodeReader"></param> /// <returns></returns> public virtual object Read(string context_name, System.IO.TextReader stringCodeReader, OutputDelegate WriteLine) { object res = null; int line = 0; while (stringCodeReader.Peek() != -1) { line++; res = Eval(stringCodeReader.ReadLine()); } return(res); } // method: Read
/// <summary> /// /// </summary> /// <param name="context_name"></param> /// <param name="stringCodeReader"></param> /// <returns></returns> public override object Read(string context_name, System.IO.TextReader stringCodeReader, OutputDelegate WritResulteLine) { CmdResult res = null; int line = 0; while (stringCodeReader.Peek() != -1) { line++; res = BotClient.ExecuteCommand(stringCodeReader.ReadLine(), context_name, WriteLine, CMDFLAGS.ForceCompletion); } return(res); } // method: Read