Here's my code:
StreamReader reader = new StreamReader("war.txt");
string input = null;
while ((input = reader.ReadLine()) != null)
{
Console.WriteLine(input);
}
reader.Close();
The program above reads and prints out from the file “war.txt” line-by-line. I need to re-write the program so that it prints out in reverse order, i.e., last line first and first line last. For example, if “war.txt” contains the following:
Hello.
How are you?
Thank you.
Goodbye.
The program should prints out:
Goodbye.
Thank you.
How are you?
Hello.
I am very new in C# please help! Thanks!
To do that, you are going to have to buffer the data anyway (unless you do some tricky work with the FileStream API to read the file backwards). How about just:
var lines = File.ReadAllLines("war.txt");
for(int i = lines.Length - 1; i >= 0; i--)
Console.WriteLine(lines[i]);
which just loads the file (in lines) into an array, and then prints the array starting from the end.
A LINQ version of that would be:
foreach(var line in File.ReadLines("war.txt").Reverse())
Console.WriteLine(line);
but frankly the array version is more efficient.
You can do it using recursion with something like this:
void printReverse(int n)
{
String line = reader.readLine();
if (n > 0)
printReverse(n-1);
System.out.println(line);
}
Have a look at adding the lines to a List, then using Reverse on the list and then maybe the ForEach to output the items.
Another option: store each line into a Stack as you read them. After reading the file, pop the stack to print the lines in reverse order.
with the enumerable extension functions, this can be done shorter:
foreach(var l in File.ReadAllLines("war.txt").Reverse())
Console.WriteLine(l);
try
File.ReadAllLines(myFile)
.Reverse();
full code
var list = File.ReadAllLines(filepath).Reverse().ToList();
foreach (var l in list)
Console.WriteLine(l);
Implementation detail
Enumerable.Reverse Method - Inverts the order of the elements in a sequence
File.ReadAllLines Method (String) - Opens a text file, reads all lines of the file, and then closes the file.
here is a example mate, remember to add "using System.IO"
try
{
const int Size = 7;
decimal[] numbers = new decimal[Size];
decimal total = 0m;
int index = 0;
StreamReader inputfile;
inputfile = File.OpenText("Sales.txt");
while (index < numbers.Length && !inputfile.EndOfStream)
{
numbers[index] = decimal.Parse(inputfile.ReadLine());
index++;
}
inputfile.Close();
foreach (decimal Sales in numbers)
{
outputlistBox1.Items.Add(Sales);
total = total + Sales;
}
textBox1.Text = total.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is another example from a textbook i bought few years ago, this has highest/lowest/average scores..(remember to use 'using System IO;)
private double Average(int[] iArray)
{
int total = 0;
double Average;
for (int index = 0; index < iArray.Length;
index++)
{
total += iArray[index];
}
Average = (double) total / iArray.Length;
return Average;
}
private int Highest(int[] iArray)
{
int highest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] > highest)
{
highest = iArray[index];
}
}
return highest;
}
private int Lowest(int[] iArray)
{
int lowest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] < lowest)
{
lowest = iArray[index];
}
}
return lowest;
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
const int SIZE = 5;
int[] Scores = new int [SIZE];
int index = 0;
int highestScore;
int lowestScore;
double averageScore;
StreamReader inputFile;
inputFile = File.OpenText("C:\\Users\\Asus\\Desktop\\TestScores.txt");
while (!inputFile.EndOfStream && index < Scores.Length)
{
Scores[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in Scores)
{
listBox1.Items.Add(value);
}
highestScore = Highest(Scores);
lowestScore = Lowest(Scores);
averageScore = Average(Scores);
textBox1.Text = highestScore.ToString();
textBox2.Text = lowestScore.ToString();
textBox3.Text = averageScore.ToString("n1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Related
I have homework. I have to make a program which can input the length of an array with the value in it. After I click the "process" button, the program will make an output of index and value with the result sum and average from the array.
I'm stuck and couldn't print the index and the value to the multiple textbox below process button.
I'm expecting the output will look like this:
Here's the code which I'd been successful write so far:
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i];
}
boxSum.Text = Convert.ToString(sum);
}
}
}
Please, help me.
Here is the code for you (boxAvg is for average)
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i-1];
}
//Refer your list box here to add newly added values to the list
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum / count); //calculate the average
}
}
}
Given that the array already has data :
private void Display()
{
var columnHeader1 = "Index Value\n";
multilineTextBox1.Text =
columnHeader1 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5}"));
boxSum.Text = vArray.Sum();
boxAvg.Text = vArray.Average();
var columnHeader2 = "Index Value Histogram\n";
multilineTextBox2.Text =
columnHeader2 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5} {new String('*', x)}"));
}
String.Join(separator, string[]), To join each row with a Carriage return/Line feed.
.Select((x,i)=> (...), To get each elment of the array an its index.
$"", For the easy string interpolation
{i+1,5}, To display the index i padded on 5 char.
new String('*', x)}, To create a string of N time the same char.
Console demo
so I wrote some C# code and I am trying to test it incrementally, do to something that would take a while to explain, but bottom line, I'm new to c# and not understanding the online compiler error messages. Here is the error message I get when I try and compile, but the strings look good to me.
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
string[] solutionSetArray = new string[12];
string ret = "";
string delimeter = "|";
int tempPos = 0;
int counter = 0;
int successFlag = 0;
int patternLength = 5;
for (int index = 0; index < solutionSet.Length; index++)
{
if (solutionSet[index] == delimeter)
{
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
tempPos = index + 1;
counter++;
}
if (solutionSet.Length - index == 1)
{
solutionSetArray[solutionSetArray.Length-1] = solutionSet.Substring(tempPos, solutionSet.Length);
}
}
for (int i = 0; i < patternLength; i++)
{
Random rnd = new Random();
int randIndex = rnd.Next(solutionSetArray.Length);
if (i != patternLength - 1)
{
ret += solutionSetArray[randIndex] + "|";
successFlag++;
}
else
{
ret += solutionSetArray[randIndex];
}
}
if (successFlag == patternLength - 1)
{
Console.WriteLine(ret);
}
else
{
Console.WriteLine("ERROR");
}
The error (which, according to the message, is on line 1, column 11) is being caused by your very first line of code, which begins string.
I can't tell the context from just your post, but my guess is that you are declaring solutionSet in a block that is not inside of a class or function. You should enclose your code in a class or method, e.g.
public class MyClass
{
static public void Main()
{
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
//Rest of code goes here
}
}
By the way, if you're trying to convert solutionSet to an array, you can just write
var solutionSetArray = solutionSet.Split("|");
the problem with your code is
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
after 6 iterations tempPos=34 and index=37 which is running out of bounds of solutionSet. I would suggest to use var solutionSetArray = solutionSet.Split("|"); and also use LinqPad which can be easy for you to debug if possible,.
I have read a file of integers into an array and I have to turn that one array into 3 separate heaps. Here is my current code but I am having trouble with a percolating down method. I have managed to create an array with the first integer n and create a single array.
For now I have only implemented the program to read from the file and based on the first value (n) read in the n values listed in the file into an array - I'm not quite sure how to make a min heap from that single array as I need 3 heaps. Example of the file is:
12 4 2 10 3 10 2 3 4 2 11 1 4 10
So 12 is n number of values in the array and 4 is # of values in each heap therefore 3 heaps.
public class realheap{
private static final int DEFAULT_CAPACITY = 10;
private int[] heap1;
private int size;
private int maxSize;
private static final int START = 1;
private static int numofval;
private static int valinheap;
public realheap(int[] array){
heap1 = new int[valinheap+1];
heap1[0] = Integer.MIN_VALUE;
size = array.length;
buildHeap();
}
public void buildHeap(){
for(int k = size/2; k > 0; k--)
{
percolatingDown(k);
}
}
public void percolatingDown(int k){
int temp = heap1[k];
int child;
for(; 2*k <= size; k = child)
{
child = 2*k;
if(child != size &&
heap1[child].compareTo(heap1[child + 1]) > 0) child++;
if(tmp.compareTo(heap[child]) > 0) heap[k] = heap[child];
else
break;
}
heap[k] = tmp;
}
/*
public static void loadFile(String file) {
try {
Scanner sc = new Scanner(new File(file));
numofval = sc.nextInt();
valinheap = sc.nextInt();
int[] ar1 = new int[numofval+1];
ar1[0] = 3;
// 3 arrays to load textfile data into arrays will be later transformed to heaps
while(sc.hasNextInt()){
// for (int i=1;i<valinheap+1;i++){
//ar1[i] = sc.nextInt(); }
for (int i=1;i<numofval+1;i++){
ar1[i] = sc.nextInt();
}
}
sc.close();
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
*/
//locates parent of index
private int getParent(int index){
return index/2;
}
//locates index of left
private int getLeftChild(int index){
return 2*index;
}
//locates the index
private int getRightChild(int index){
return (2*index)+1;
}
private void swap(int index1,int index2){
int temp = heap1[index1];
heap1[index1] = heap1[index2];
heap1[index2] = temp;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String files;
Scanner input= new Scanner(System.in);
System.out.println("Please enter the name of the file");
files=input.next();
input.close();
try {
Scanner sc = new Scanner(new File(files));
numofval = sc.nextInt();
valinheap = sc.nextInt();
int k = 1;
int[] ar1 = new int[numofval+1];
// 3 arrays to load textfile data into arrays will be later transformed to heaps
while(sc.hasNext()){
// for (int i=1;i<valinheap+1;i++){
//ar1[i] = sc.nextInt(); }
ar1[k] = sc.nextInt();
k++;
}
for (int i=1;i<numofval+1;i++){
System.out.println(ar1[i]);
}
sc.close();
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
I am creating a word list of possible uppercase letters to prove how insecure 8 digit passwords are this code will write aaaaaaaa to aaaaaaab to aaaaaaac etc. until zzzzzzzz using this code:
class Program
{
static string path;
static int file = 0;
static void Main(string[] args)
{
new_file();
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789+-*_!$£^=<>§°ÖÄÜöäü.;:,?{}[]";
var q = alphabet.Select(x => x.ToString());
int size = 3;
int counter = 0;
for (int i = 0; i < size - 1; i++)
{
q = q.SelectMany(x => alphabet, (x, y) => x + y);
}
foreach (var item in q)
{
if (counter >= 20000000)
{
new_file();
counter = 0;
}
if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(item);
Console.WriteLine(item);
/*if (!(Regex.IsMatch(item, #"(.)\1")))
{
sw.WriteLine(item);
counter++;
}
else
{
Console.WriteLine(item);
}*/
}
}
else
{
new_file();
}
}
}
static void new_file()
{
path = #"C:\" + "list" + file + ".txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
}
}
file++;
}
}
The Code is working fine but it takes Weeks to run it. Does anyone know a way to speed it up or do I have to wait? If anyone has a idea please tell me.
Performance:
size 3: 0.02s
size 4: 1.61s
size 5: 144.76s
Hints:
removed LINQ for combination generation
removed Console.WriteLine for each password
removed StreamWriter
large buffer (128k) for file writing
const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789+-*_!$£^=<>§°ÖÄÜöäü.;:,?{}[]";
var byteAlphabet = alphabet.Select(ch => (byte)ch).ToArray();
var alphabetLength = alphabet.Length;
var newLine = new[] { (byte)'\r', (byte)'\n' };
const int size = 4;
var number = new byte[size];
var password = Enumerable.Range(0, size).Select(i => byteAlphabet[0]).Concat(newLine).ToArray();
var watcher = new System.Diagnostics.Stopwatch();
watcher.Start();
var isRunning = true;
for (var counter = 0; isRunning; counter++)
{
Console.Write("{0}: ", counter);
Console.Write(password.Select(b => (char)b).ToArray());
using (var file = System.IO.File.Create(string.Format(#"list.{0:D5}.txt", counter), 2 << 16))
{
for (var i = 0; i < 2000000; ++i)
{
file.Write(password, 0, password.Length);
var j = size - 1;
for (; j >= 0; j--)
{
if (number[j] < alphabetLength - 1)
{
password[j] = byteAlphabet[++number[j]];
break;
}
else
{
number[j] = 0;
password[j] = byteAlphabet[0];
}
}
if (j < 0)
{
isRunning = false;
break;
}
}
}
}
watcher.Stop();
Console.WriteLine(watcher.Elapsed);
}
Try the following modified code. In LINQPad it runs in < 1 second. With your original code I gave up after 40 seconds. It removes the overhead of opening and closing the file for every WriteLine operation. You'll need to test and ensure it gives the same results because I'm not willing to run your original code for 24 hours to ensure the output is the same.
class Program
{
static string path;
static int file = 0;
static void Main(string[] args)
{
new_file();
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789+-*_!$£^=<>§°ÖÄÜöäü.;:,?{}[]";
var q = alphabet.Select(x => x.ToString());
int size = 3;
int counter = 0;
for (int i = 0; i < size - 1; i++)
{
q = q.SelectMany(x => alphabet, (x, y) => x + y);
}
StreamWriter sw = File.AppendText(path);
try
{
foreach (var item in q)
{
if (counter >= 20000000)
{
sw.Dispose();
new_file();
counter = 0;
}
sw.WriteLine(item);
Console.WriteLine(item);
}
}
finally
{
if(sw != null)
{
sw.Dispose();
}
}
}
static void new_file()
{
path = #"C:\temp\list" + file + ".txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
}
}
file++;
}
}
your alphabet is missing 0
With that fixed there would be 89 chars in your set. Let's call it 100 for simplicity. The set you are looking for is all the 8 character length strings drawn from that set. There are 100^8 of these, i.e. 10,000,000,000,000,000.
The disk space they will take up depends on how you encode them, lets be generous - assume you use some 8 bit char set that contains the these characters, and you don't put in carriage returns, so one byte per char, so 10,000,000,000,000,000 bytes =~ 10 peta byes?
Do you have 10 petabytes of disk? (10000 TB)?
[EDIT] In response to 'this is not an answer':
The original motivation is to create the list? The shows how large the list would be. Its hard to see what could be DONE with the list if it was actualised, i.e. it would always be quicker to reproduce it than to load it. Surely whatever point could be made by producing the list can also be made by simply knowing it's size, which the above shows how to work it out.
There are LOTS of inefficiencies in you code, but if your questions is 'how can i quickly produce this list and write it to disk' the answer is 'you literally cannot'.
[/EDIT]
I am using a source meter which sweeps current and measures voltage and finally export all I-V data through rs232.
I write them into a textfile with the format as following;
I1,V1,I2,V2,I3,V3...
I split all "commas" with the "split" function but I don't know how I can keep I-V couples into an array and then I want to calculate each resistance of each I-V by simple I/V calculation.
Any help would be greatly appreciated.
public class Sample
{
public static void Main() {
using (StreamReader reader = new StreamReader("myfilefile.txt")) {
string line = null;
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(',');
}
}
}
}
You could do something like this:
for (int j = 0; j < values.Length; j += 2) {
double i = double.Parse(values[j]);
double v = double.Parse(values[j+1]);
double r = v / i;
}
If you can assume that you always have pairs (and thus an even number of elements in values) you can do this:
// your line
string[] values = line.Split(',');
// my addition
for(int pair=0; pair<values.Length; pair=pair+2)
{
string iValue = values[pair];
string vValue = values[pair+1];
Double i;
Double v;
bool iOk = Double.TryParse(iValue, out i);
bool vOk = Double.TryParse(vValue, out v);
if (iOk && vOk)
{
Double r = i/v;
Console.WriteLine("{0} (R) = {1} (I) / {2} V ",r, i, v);
}
else
{
Console.WriteLine("{0} or {1} is not parseable", iValue, vValue);
}
}