C# Read random line
-
How to read random line from text file that startswith * and lines below him that are related to him? I have created to get random line with question using commands below, but after that it doesn't read lines below him that are related to him,instead of that he read lines from beggining!!! var questions = File.ReadLines(filePath) .Where(line => line.StartsWith("*")).ToList(); var rng = new Random(); var myRandomQuestion = questions[rng.Next(questions.Count)].Substring(1); label1.Text = myRandomQuestion; My text file has 15000 lines.Lines with * character are questions and lines below them are terms relating to that question. This is one part of file: *Planete i njihovi sateliti Zemlja=Mesec Mars=Fobos Jupiter=Io Saturn=Titan Uran=Titania Neptun=Triton Pluton=Haron Merkur=Nema satelit *Čuveni parovi iz umetnosti Hamlet=Ofelija Ruslan=Ljudmila Zevs=Hera Otelo=Dezdemona Paris=Helena Abelard=Eloiza Paolo=Frančeska Lanselot=Ginevra *Latinski pojmovi Kvalifikacija=Osposobljenost Karantin=Izolacija Radijacija=Zračenje Ratifikacija=Potpisivanje Racionalan=Razuman Reakcija=Otpor Realizacija=Ostvarenje Rekapitulacija=Ponavljanje *Poveži aktuelne predsednike sa državama u kojima vladaju. Trajan Basesku=Rumunija Karolos Papuljas=Grčka Đorđo Napolitano=Italija Tomas Hendrik Ilves=Estonija Danilo Tirk=Slovenija Dimitris Hristofias=Kipar Tarja Halonen=Finska Meri Mekelis=Irska *Francuski gradovi Bordeaux=Bordo Auxerre=Okser Toulouse=Tuluz Nantes=Nant Marseille=Marselj Dijon=Dižon Limoges=Limož Chateauroux=Šatero
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Collections.Specialized;
using System.IO;namespace Slagalica
{
public partial class Spojnice : MetroFramework.Forms.MetroForm
{
public Spojnice()
{
InitializeComponent();
}string igra; int j = 0; Button\[\] button; private void Spojnice\_Load(object sender, EventArgs e) { Random r = new Random(); int indeks; igra = "spojnice"; StreamReader sr = new StreamReader(igra + ".txt"); string\[\] niz1 = new string\[8\]; string\[\] niz2 = new string\[8\]; //label1.Text = sr.ReadLine(); var q
-
How to read random line from text file that startswith * and lines below him that are related to him? I have created to get random line with question using commands below, but after that it doesn't read lines below him that are related to him,instead of that he read lines from beggining!!! var questions = File.ReadLines(filePath) .Where(line => line.StartsWith("*")).ToList(); var rng = new Random(); var myRandomQuestion = questions[rng.Next(questions.Count)].Substring(1); label1.Text = myRandomQuestion; My text file has 15000 lines.Lines with * character are questions and lines below them are terms relating to that question. This is one part of file: *Planete i njihovi sateliti Zemlja=Mesec Mars=Fobos Jupiter=Io Saturn=Titan Uran=Titania Neptun=Triton Pluton=Haron Merkur=Nema satelit *Čuveni parovi iz umetnosti Hamlet=Ofelija Ruslan=Ljudmila Zevs=Hera Otelo=Dezdemona Paris=Helena Abelard=Eloiza Paolo=Frančeska Lanselot=Ginevra *Latinski pojmovi Kvalifikacija=Osposobljenost Karantin=Izolacija Radijacija=Zračenje Ratifikacija=Potpisivanje Racionalan=Razuman Reakcija=Otpor Realizacija=Ostvarenje Rekapitulacija=Ponavljanje *Poveži aktuelne predsednike sa državama u kojima vladaju. Trajan Basesku=Rumunija Karolos Papuljas=Grčka Đorđo Napolitano=Italija Tomas Hendrik Ilves=Estonija Danilo Tirk=Slovenija Dimitris Hristofias=Kipar Tarja Halonen=Finska Meri Mekelis=Irska *Francuski gradovi Bordeaux=Bordo Auxerre=Okser Toulouse=Tuluz Nantes=Nant Marseille=Marselj Dijon=Dižon Limoges=Limož Chateauroux=Šatero
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Collections.Specialized;
using System.IO;namespace Slagalica
{
public partial class Spojnice : MetroFramework.Forms.MetroForm
{
public Spojnice()
{
InitializeComponent();
}string igra; int j = 0; Button\[\] button; private void Spojnice\_Load(object sender, EventArgs e) { Random r = new Random(); int indeks; igra = "spojnice"; StreamReader sr = new StreamReader(igra + ".txt"); string\[\] niz1 = new string\[8\]; string\[\] niz2 = new string\[8\]; //label1.Text = sr.ReadLine(); var q
I'm not reading that entire code dump. Most of is probably not related to the problem. You can't randomly seek to a specific "line" in a text file. You have to read through it, looking for the lines that start with "*". You can do ignore a random number of them but you might want to initialize some structure with the data from the file, reading through the entire file looking for the "*" lines and recording which line you found it. You can then pick one at random, and get the line number to skip to. You have to go back re-read the file, counting lines until you get to the one you want. When you get the line with the "*" in it, you start reading and recording the data from each line, these are your answers, until you get to another line with a "*" in it.
A guide to posting questions on CodeProject
Click this: Asking questions is a skill. Seriously, do it.
Dave Kreskowiak -
How to read random line from text file that startswith * and lines below him that are related to him? I have created to get random line with question using commands below, but after that it doesn't read lines below him that are related to him,instead of that he read lines from beggining!!! var questions = File.ReadLines(filePath) .Where(line => line.StartsWith("*")).ToList(); var rng = new Random(); var myRandomQuestion = questions[rng.Next(questions.Count)].Substring(1); label1.Text = myRandomQuestion; My text file has 15000 lines.Lines with * character are questions and lines below them are terms relating to that question. This is one part of file: *Planete i njihovi sateliti Zemlja=Mesec Mars=Fobos Jupiter=Io Saturn=Titan Uran=Titania Neptun=Triton Pluton=Haron Merkur=Nema satelit *Čuveni parovi iz umetnosti Hamlet=Ofelija Ruslan=Ljudmila Zevs=Hera Otelo=Dezdemona Paris=Helena Abelard=Eloiza Paolo=Frančeska Lanselot=Ginevra *Latinski pojmovi Kvalifikacija=Osposobljenost Karantin=Izolacija Radijacija=Zračenje Ratifikacija=Potpisivanje Racionalan=Razuman Reakcija=Otpor Realizacija=Ostvarenje Rekapitulacija=Ponavljanje *Poveži aktuelne predsednike sa državama u kojima vladaju. Trajan Basesku=Rumunija Karolos Papuljas=Grčka Đorđo Napolitano=Italija Tomas Hendrik Ilves=Estonija Danilo Tirk=Slovenija Dimitris Hristofias=Kipar Tarja Halonen=Finska Meri Mekelis=Irska *Francuski gradovi Bordeaux=Bordo Auxerre=Okser Toulouse=Tuluz Nantes=Nant Marseille=Marselj Dijon=Dižon Limoges=Limož Chateauroux=Šatero
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Collections.Specialized;
using System.IO;namespace Slagalica
{
public partial class Spojnice : MetroFramework.Forms.MetroForm
{
public Spojnice()
{
InitializeComponent();
}string igra; int j = 0; Button\[\] button; private void Spojnice\_Load(object sender, EventArgs e) { Random r = new Random(); int indeks; igra = "spojnice"; StreamReader sr = new StreamReader(igra + ".txt"); string\[\] niz1 = new string\[8\]; string\[\] niz2 = new string\[8\]; //label1.Text = sr.ReadLine(); var q
I would have approached this issue 'a bit differently' - it depends if you want to have to whole file in memory, or what you wish to optimise ... Assuming you dont want the whole file in memory, you read the file multiple times In the OnLoad event for the WinForm, I would fire off a Background thread, to parse the file to extract all the questions, their start lines in the file, the number of answers, to a data structure - possible an array of struct(string question, int start line, int num answers) - this is your 'index' once you have a random number, you get that element from the index and use the start line and num answers to locate the answers in the file If you can keep the entire set of data in memory, then you parse the file to something like array of struct(string question, List answers), which means once you have your random number, you can jump straight to the index and get the question and answers
-
How to read random line from text file that startswith * and lines below him that are related to him? I have created to get random line with question using commands below, but after that it doesn't read lines below him that are related to him,instead of that he read lines from beggining!!! var questions = File.ReadLines(filePath) .Where(line => line.StartsWith("*")).ToList(); var rng = new Random(); var myRandomQuestion = questions[rng.Next(questions.Count)].Substring(1); label1.Text = myRandomQuestion; My text file has 15000 lines.Lines with * character are questions and lines below them are terms relating to that question. This is one part of file: *Planete i njihovi sateliti Zemlja=Mesec Mars=Fobos Jupiter=Io Saturn=Titan Uran=Titania Neptun=Triton Pluton=Haron Merkur=Nema satelit *Čuveni parovi iz umetnosti Hamlet=Ofelija Ruslan=Ljudmila Zevs=Hera Otelo=Dezdemona Paris=Helena Abelard=Eloiza Paolo=Frančeska Lanselot=Ginevra *Latinski pojmovi Kvalifikacija=Osposobljenost Karantin=Izolacija Radijacija=Zračenje Ratifikacija=Potpisivanje Racionalan=Razuman Reakcija=Otpor Realizacija=Ostvarenje Rekapitulacija=Ponavljanje *Poveži aktuelne predsednike sa državama u kojima vladaju. Trajan Basesku=Rumunija Karolos Papuljas=Grčka Đorđo Napolitano=Italija Tomas Hendrik Ilves=Estonija Danilo Tirk=Slovenija Dimitris Hristofias=Kipar Tarja Halonen=Finska Meri Mekelis=Irska *Francuski gradovi Bordeaux=Bordo Auxerre=Okser Toulouse=Tuluz Nantes=Nant Marseille=Marselj Dijon=Dižon Limoges=Limož Chateauroux=Šatero
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Collections.Specialized;
using System.IO;namespace Slagalica
{
public partial class Spojnice : MetroFramework.Forms.MetroForm
{
public Spojnice()
{
InitializeComponent();
}string igra; int j = 0; Button\[\] button; private void Spojnice\_Load(object sender, EventArgs e) { Random r = new Random(); int indeks; igra = "spojnice"; StreamReader sr = new StreamReader(igra + ".txt"); string\[\] niz1 = new string\[8\]; string\[\] niz2 = new string\[8\]; //label1.Text = sr.ReadLine(); var q
I would suggest that the best thing to do would be to change your file format. If you used each line to hold a single question, together with it's possible answers, separated by '|' characters:
Planete i njihovi sateliti|Zemlja=Mesec|Mars=Fobos|Jupiter=Io|Saturn=Titan|Uran=Titania|Neptun=Triton|Pluton=Haron|Merkur=Nema satelit
Čuveni parovi iz umetnosti|Hamlet=Ofelija|Ruslan=Ljudmila|Zevs=Hera|Otelo=Dezdemona|Paris=Helena|Abelard=Eloiza|Paolo=Frančeska|Lanselot=Ginevra
...Then the problem becomes trivial: Use File.ReadAllLines to read the whole file into an array of strings: each element of the array is a question together with it's answers, so selecting a random question is a trivial use of the Random class. Each question and answer can be easily split out into an array of strings using string.Split - the first element of the array is the question, the rest of them are possible answers. But do yourself a favour: stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
I would suggest that the best thing to do would be to change your file format. If you used each line to hold a single question, together with it's possible answers, separated by '|' characters:
Planete i njihovi sateliti|Zemlja=Mesec|Mars=Fobos|Jupiter=Io|Saturn=Titan|Uran=Titania|Neptun=Triton|Pluton=Haron|Merkur=Nema satelit
Čuveni parovi iz umetnosti|Hamlet=Ofelija|Ruslan=Ljudmila|Zevs=Hera|Otelo=Dezdemona|Paris=Helena|Abelard=Eloiza|Paolo=Frančeska|Lanselot=Ginevra
...Then the problem becomes trivial: Use File.ReadAllLines to read the whole file into an array of strings: each element of the array is a question together with it's answers, so selecting a random question is a trivial use of the Random class. Each question and answer can be easily split out into an array of strings using string.Split - the first element of the array is the question, the rest of them are possible answers. But do yourself a favour: stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
Simple! Write a quick app to do it for you. Something like this should do the donkey work:
private void ConvertFile(string inPath, string outPath) { string\[\] inData = File.ReadAllLines(inPath); List outData = new List(); StringBuilder sb = new StringBuilder(); foreach (string line in inData) { if (line.StartsWith("\*")) { if (sb.Length > 0) { outData.Add(sb.ToString()); sb.Clear(); } sb.Append(line.Substring(1)); } else { sb.Append("|"); sb.Append(line); } } if (sb.Length > 0) { outData.Add(sb.ToString()); } File.WriteAllLines(outPath, outData); }
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
Simple! Write a quick app to do it for you. Something like this should do the donkey work:
private void ConvertFile(string inPath, string outPath) { string\[\] inData = File.ReadAllLines(inPath); List outData = new List(); StringBuilder sb = new StringBuilder(); foreach (string line in inData) { if (line.StartsWith("\*")) { if (sb.Length > 0) { outData.Add(sb.ToString()); sb.Clear(); } sb.Append(line.Substring(1)); } else { sb.Append("|"); sb.Append(line); } } if (sb.Length > 0) { outData.Add(sb.ToString()); } File.WriteAllLines(outPath, outData); }
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
-
I have added questions and answer to list!How to get random question with it's answers from the list?
string[] data = File.ReadAllLines("spojnice1.txt");
List questions = new List();
foreach (string line in data)
questions.Add(line);You know the number of questions, so you should be easily able to use the Random class to pick the appropriate question. And I'm pretty sure that Griff recommended that you used a parent-child relationship so you added only the lines starting with * to the questions list, and then you would expose a list of answers as a child of the question.
This space for rent
-
You know the number of questions, so you should be easily able to use the Random class to pick the appropriate question. And I'm pretty sure that Griff recommended that you used a parent-child relationship so you added only the lines starting with * to the questions list, and then you would expose a list of answers as a child of the question.
This space for rent
He told me to change to this format text file:
Planete i njihovi sateliti|Zemlja=Mesec|Mars=Fobos|Jupiter=Io|Saturn=Titan|Uran=Titania|Neptun=Triton|Pluton=Haron|Merkur=Nema satelit
Čuveni parovi iz umetnosti|Hamlet=Ofelija|Ruslan=Ljudmila|Zevs=Hera|Otelo=Dezdemona|Paris=Helena|Abelard=Eloiza|Paolo=Frančeska|Lanselot=Ginevra
...When I change to that format I cannot add lines starting with * to list!!!
-
He told me to change to this format text file:
Planete i njihovi sateliti|Zemlja=Mesec|Mars=Fobos|Jupiter=Io|Saturn=Titan|Uran=Titania|Neptun=Triton|Pluton=Haron|Merkur=Nema satelit
Čuveni parovi iz umetnosti|Hamlet=Ofelija|Ruslan=Ljudmila|Zevs=Hera|Otelo=Dezdemona|Paris=Helena|Abelard=Eloiza|Paolo=Frančeska|Lanselot=Ginevra
...When I change to that format I cannot add lines starting with * to list!!!
Sigh. Let me simplify this for you. Griff has suggested that you break your original list down (the ones that originally started with * being your question). These then have a number of answers stored as a series of pipe delimited fields. That's your parent/child relationship there. The lines originally marked with * will now be the first entry in this pipe delimited list. You know how many entries you have in this list, so you use this as the upper bound of the Random number. That's it - the code is trivial. To make things more random, don't forget to seed the Random when you instantiate it. Read the documentation for details on how to do this.
This space for rent
-
How to read random line from text file that startswith * and lines below him that are related to him? I have created to get random line with question using commands below, but after that it doesn't read lines below him that are related to him,instead of that he read lines from beggining!!! var questions = File.ReadLines(filePath) .Where(line => line.StartsWith("*")).ToList(); var rng = new Random(); var myRandomQuestion = questions[rng.Next(questions.Count)].Substring(1); label1.Text = myRandomQuestion; My text file has 15000 lines.Lines with * character are questions and lines below them are terms relating to that question. This is one part of file: *Planete i njihovi sateliti Zemlja=Mesec Mars=Fobos Jupiter=Io Saturn=Titan Uran=Titania Neptun=Triton Pluton=Haron Merkur=Nema satelit *Čuveni parovi iz umetnosti Hamlet=Ofelija Ruslan=Ljudmila Zevs=Hera Otelo=Dezdemona Paris=Helena Abelard=Eloiza Paolo=Frančeska Lanselot=Ginevra *Latinski pojmovi Kvalifikacija=Osposobljenost Karantin=Izolacija Radijacija=Zračenje Ratifikacija=Potpisivanje Racionalan=Razuman Reakcija=Otpor Realizacija=Ostvarenje Rekapitulacija=Ponavljanje *Poveži aktuelne predsednike sa državama u kojima vladaju. Trajan Basesku=Rumunija Karolos Papuljas=Grčka Đorđo Napolitano=Italija Tomas Hendrik Ilves=Estonija Danilo Tirk=Slovenija Dimitris Hristofias=Kipar Tarja Halonen=Finska Meri Mekelis=Irska *Francuski gradovi Bordeaux=Bordo Auxerre=Okser Toulouse=Tuluz Nantes=Nant Marseille=Marselj Dijon=Dižon Limoges=Limož Chateauroux=Šatero
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;using System.Collections.Specialized;
using System.IO;namespace Slagalica
{
public partial class Spojnice : MetroFramework.Forms.MetroForm
{
public Spojnice()
{
InitializeComponent();
}string igra; int j = 0; Button\[\] button; private void Spojnice\_Load(object sender, EventArgs e) { Random r = new Random(); int indeks; igra = "spojnice"; StreamReader sr = new StreamReader(igra + ".txt"); string\[\] niz1 = new string\[8\]; string\[\] niz2 = new string\[8\]; //label1.Text = sr.ReadLine(); var q
Hi, if the majority of your application needs to know the file structure, then something is definitely wrong. At the minimum you should define data structures that reflect the problem domain, read your file once, and stuff all the info into the data structures, then work from there. However, I would also consider using a database; from what I understood you would need two tables: one for questions, one for the remaining info; and an N-to-1 relationship between them. :)
Luc Pattyn [My Articles] Nil Volentibus Arduum