how to deal with file of numbers c# - c#

I have file contain numbers like these
123.4 23.7 89.2 ...
45.8
...
8 columns and 1024 rows, and I want to read this file row by row and put each row in array of double to get the minimum number from this row and put this minimum number in array with size 1024 .
I tried this code in c# ...
static void Main(string[] args)
{
string line;
double[] row = new double[8];
double[] minimum = new double[1024];
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
for (int k = 0; k < 1024; k++)
{
while ((line = file.ReadLine()) != null )
{
string[] numbers = new string[8];
int numCount = 0;
for (int i = 0; i < line.Length; i++)
{
if (line[i] != ' ')
{
numbers[numCount] = "";
while (line[i] != ' ')
{
numbers[numCount] += line[i];
i++;
}
numCount++;
}
}
for (int i = 0; i < 8; i++)
{
row[i] = Convert.ToDouble(numbers[i]);
}
double min = row[0];
for (int j = 0; j < 8; j++)
{
if (row[j] <= min)
min = row[j];
}
minimum[k] = min;
}
}
Console.WriteLine("The array contain:");
for (int i = 0; i < 1024; i++)
Console.WriteLine(minimum[i]);
file.Close();
// Suspend the screen.
Console.ReadLine();
}

There are several methods that can simplify your code - File.ReadLines, String.Split and LINQ Select. Resulting code could look similar to:
var listOfArraysOfDouble = File.ReadLines(fileName)
.Select(row =>
row.Split((string[]) null, StringSplitOptions.RemoveEmptyEntries)
.Select(columnValue => double.Parse(columnValue))
.ToArray()
);

Related

C# return string in Sine-Wave format

I'm trying to create a function which will return string in Triangle Sine-Wave format:
but currently, my format is only in Wave format:
Code below:
public static void printWave(string str)
{
int height = 3;
// Get length of the string
int len = str.Length;
// Create a 2d character array
char[,] matrixArray = new char[height, len];
char[] charArray = str.ToCharArray();
// for counting the
// rows of the ZigZag
int row = 0;
bool down = true;
for (int i = 0; i < len; i++)
{
// put characters
// in the matrix
matrixArray[row, i] = charArray[i];
// You have reached the bottom
if (row == height - 1)
down = false;
else if (row == 0)
down = true;
if (down)
row++;
else
row--;
}
// Print the Zig-Zag String
for (int i = 0; i < height; i++)
{
for (int j = 0; j < len; j++)
{
Console.Write(matrixArray[i, j] + " ");
}
Console.Write("\n");
}
}
Can you please help me modify my code to it will return triangle sin wave format?
We can use 3 separate StringBuilders to append to depending on our boolean top and a simple even value comparison. A quick TL;DR is that anything at an even index goes in the middle row, and then we flip between appending to the top or bottom row:
public static void printWave(string str)
{
//for use to determine top or bottom StringBuilder
bool top = true;
//will be used to generate each row of the output
StringBuilder topString = new StringBuilder();
StringBuilder middleString = new StringBuilder();
StringBuilder bottomString = new StringBuilder();
//iterate through paramter string
for (int i = 0; i < str.Length; i++)
{
//if char is at an even index, it goes in the middle StringBuilder, blank spaces in top and bottom builders
if (i%2 == 0)
{
topString.Append(" ");
middleString.Append(str[i]);
bottomString.Append(" ");
}
//if not even index, determine top or bottom row
else
{
//simply check our boolean and then flip it after use
if (top)
{
topString.Append(str[i]);
middleString.Append(" ");
bottomString.Append(" ");
top = false;
}
else
{
topString.Append(" ");
middleString.Append(" ");
bottomString.Append(str[i]);
top = true;
}
}
}
//write each row of strings on new lines
Console.WriteLine(topString.ToString());
Console.WriteLine(middleString.ToString());
Console.WriteLine(bottomString.ToString());
}
For a variable height:
public static void printWave(string str)
{
//height we want the wave to reach
int height = 5;
//determine "middle" row
int startingRow = height / 2;
int currentRow = startingRow; //this one is for modifying inside loop
bool up = true;
//2D array to hold the rows
char[,] arr = new char[height, str.Length];
for (int i = 0; i < str.Length; i++)
{
for (int j = 0; j < height; j++)
{
if (j == currentRow)
{
arr[j, i] = str[i];
}
else
arr[j, i] = ' ';
}
//could probably break this into more digestible pieces if time to think about it
if (up)
{
if (currentRow == 0)
{
up = false;
currentRow++;
}
else
{
currentRow--;
}
}
else
{
if (currentRow == height - 1)
{
up = true;
currentRow--;
}
else
{
currentRow++;
}
}
}
for (int k = 0; k < height; k++)
{
for (int l = 0; l < str.Length; l++)
{
Console.Write(arr[k, l]);
}
Console.WriteLine();
}
}
Examples of height = 5 and height = 6 output:
And finally, height = 7
This version works, but it's hard-coded to just the 3 rows like the question shows. If larger waves are needed, or especially if the size of the wave depends on the input string, then this may be hard to adjust to the requirements.
public static void PrintWave(string str)
{
printWithRowLogic(str, (i) => (i - 1) % 4 == 0);
Console.WriteLine();
printWithRowLogic(str, (i) => i % 2 == 0);
Console.WriteLine();
printWithRowLogic(str, (i) => (i - 3) % 4 == 0);
}
private static void printWithRowLogic(string str, Func<int, bool> checkLogic)
{
for (int i = 0; i < str.Length; i++)
Console.Write(checkLogic(i) ? str[i] : ' ');
}

I want to read a table from text file and assign each column to an array

i want to store each row in a different array. below is the code i tried.
but it doesn't not work, it only splits the last line and store values in "valueperline" array
first 11 rows are source text. file and screen shot of console
using System;
using System.Collections.Generic;
using System.IO;
namespace BBS_optimize
{
class Program
{
static void Main()
{
int i = 0; int j = 0; int k =0; string[] valueperline = new string[0]; string[] lines = new string [0];
lines = File.ReadAllLines("Table1.txt");
for (i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (j = 0; j<lines.Length; j++)
{ valueperline = lines[j].Split('\t');
}
for (k = 0; k < 44; k++)
{ Console.WriteLine(valueperline[k]);
}
}
}
}
Use array:
string[,] ParseFromFile (string fileName)
{
// Assume that your table have 10 cols and 100 rows
string[,] result = new string[10,100];
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
string[] row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries);
result[i] = row;
}
return result;
}
Use List:
List<List<string>> ParseFromFile (string fileName)
{
// Your list
List<List<string>> result = new List<List<string>>();
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
List<string> row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(row);
}
return result;
}
below is a solution:
static void Main(string[] args)
{
List<List<string>> lst = new List<List<string>>();
string[] lines = new string[0];
lines = File.ReadAllLines("tableX.txt");
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (int j = 0; j < lines.Length; j++)
{
var line = lines[j].Split(' ').ToList();
lst.Add(line);
}
foreach (var item in lst)
{
for (int k = 0; k < item.Count; k++)
{
Console.WriteLine(item[k]);
}
}
}

Converting this MatLab iterating code to C#. Outputs from matlab and c# are different

I am trying to convert this code:
function [C] = cumulativeMaxV2(A)
cols = size(A,2);
bscans = size(A,3);
C = zeros(size(A));
for col = 1:cols
for bscan = 1:bscans
aline = A(:,col,bscan);
for i = 1:length(aline)
if i == 1
C(i,col,bscan)=0;
else
C(i,col,bscan) = max(A(1:i-1, col,bscan));
end
end
end
end
My C# code is below:
static double[,,] CumulativeMax(double[,,] A)
{
int cols = 304; //A.GetLength(1);
int bscans = 304; //A.GetLength(2);
double[,,] C = new double[160, 304, 304];
Console.Write("Processing... ");
using (var progress = new ProgressBar())
{
for (int col = 0; col < cols; col++)
{
for (int bscan = 0; bscan < bscans; bscan++)
{
double[] aline = new double[160];
for (int i = 0; i < 160; i++)
aline[i] = A[i,col,bscan];
for (int i = 0; i < aline.GetLength(0); i++)
{
if (i == 0)
C[i,col,bscan] = 0d;
else if (i == 1)
{
double[] temp = new double[i];
for (int x = 0; x < i; x++)
temp[x] = A[x,col,bscan];
C[i,col,bscan] = temp.Max();
}
else
{
double[] temp = new double[i - 1];
for (int x = 0; x < i - 1; x++)
temp[x] = A[x,col,bscan];
C[i,col,bscan] = temp.Max();
}
}
}
progress.Report((double)col/cols);
}
}
Console.WriteLine("Done.");
return C;
}
Outputs from MatLab do not match those from the C# code.
Any pointers to where the bugs are in my C# code would be great. I'm not very good with MatLab.
I think this may be due to how MatLab's max function deals with infinity and NaNs.

Read text from a text file to a string multidimensional array

So I ran into a problem, I have a big text in a TXT file and I need to read it into a multidimensional array, without using LINQ.
Example:
Hello(a11) my(a12) friend(a13).
My(a21) name(a22) is(a23) David(a24),
I(a31) am(a32) from(a33) England(a34).
What I have done so far:
String input = File.ReadAllText( "..\\..\\Analize.txt" );
int i = 0, j = 0;
string[,] result = new string[10, 10];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = string(col.Trim());
j++;
}
i++;
}
For the others who said his code "works just fine - true if his text is not dynamic size - but if there are more lines then 10, or more words then 10 in this particular example there will be an IndexOutOfRangeException !
If you do know anything about your file this is maybe the best for not running into exceptions:
string[] lines = File.ReadAllLines("C:/temp/test.txt");
int sizex = lines.Length;
int sizey = 1;
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
sizey = sizey < splitline.Length ? splitline.Length : sizey;
}
String[,] multillines = new string[sizex,sizey];
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
for (int j = 0; j < splitline.Length; j++)
{
multillines[i, j] = splitline[j];
}
}
Your code as it is works just fine. Not sure what your problem is. But if this:
Hello(a11)
means that this word has to sit on position [1,1] then all you have to change is the counting start from 0 to 1
int i = 1, j = 1;
Try this:
String input ="Hello(a11) my(a12) friend(a13)";
int i = 0, j = 0;
int[,] result = new int[10, 10];
foreach (var row in input.Split(' '))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = int.Parse(col.Trim());
j++;
}
i++;
}
Console.WriteLine(result[3,9]);

C# program that returns morse code for numbers not working

I'm trying to make a program that: When given a 4 digit number (for example, 1001) it sums the digits of that number, for 1001 this is 1 + 0 + 0 + 1 = 2, than it finds all sequences of 6 numbers from 1 to 6 (including permutations, i.e. 1*1*1*1*1*2 is different than 2*1*1*1*1*1) whose product is that number.
The result should be printed on the console in the following format: each sequence of 6 numbers, with their Morse representation, separated with a single pipe: 1 is .---- , 2 is ..---: .----|.----|.----|.----|..---|, on a new row the next permutation: .----|.----|.----|..---|.----| and so on.
The problem is, my solution doesn't show the correct answers, not even the correct number of them.
Here's my code (and please, if possible, tell me where my mistake is, and not some one line hack solutions to the problem with LINQ and regex and God knows what):
string n = Console.ReadLine();
string[] digitsChar = new string[n.Length];
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
int morseProduct = digits.Sum();
Console.WriteLine(morseProduct);
List<int> morseCodeNumbers = new List<int>();
for (int i = 1; i < 6; i++)
{
for (int j = 1; i < 6; i++)
{
for (int k = 1; i < 6; i++)
{
for (int l = 1; i < 6; i++)
{
for (int m = 1; i < 6; i++)
{
for (int o = 1; o < 6; o++)
{
int product = i * j * k * l * m * o;
if (product == morseProduct)
{
morseCodeNumbers.Add(i);
morseCodeNumbers.Add(j);
morseCodeNumbers.Add(k);
morseCodeNumbers.Add(l);
morseCodeNumbers.Add(m);
morseCodeNumbers.Add(o);
}
}
}
}
}
}
}
int numberOfNumbers = morseCodeNumbers.Count;
string[] morseCodes = new string[] { "-----", ".----", "..---", "...--", "....-", "....." };
for (int i = 0; i < numberOfNumbers; i++)
{
int counter = 0;
if (i % 5 == 0)
{
Console.WriteLine();
counter = 0;
}
if (counter < 5)
{
int index = morseCodeNumbers[i];
Console.Write(morseCodes[index] + "|");
counter++;
}
A lot of your for-loop conditions refer to i instead of j,k,l and m. The same for the increment part. For example:
for (int j = 1; i < 6; i++)
should be
for (int j = 1; j < 6; j++)
Furthermore if the range is from 1 to 6 you need to change < to <=, see:
for (int i = 1; i <= 6; i++)
You don't need to convert the string to a string array to get the int array of digits btw, so while this is correct:
for (int i = 0; i < 4; i++)
{
digitsChar[i] = n[i].ToString();
}
int[] digits = new int[digitsChar.Length];
for (int i = 0; i < 4; i++)
{
digits[i] = Convert.ToInt32(digitsChar[i]);
}
you could it do like that (sry for LINQ):
var digits = n.Select(c=>(int)char.GetNumericValue(c) ).ToArray();

Categories

Resources