I have data in txt like this:
flea,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
frog,0,0,1,0,0,1,1,1,1,1,0,0,4,0,0,0,5
frog,0,0,1,0,0,1,1,1,1,1,1,0,4,0,0,0,5
I need to count the number of zeros in a chosen column, for example in the first column there are 3 zeros.
Here is my code so far:
//data patch
string[] tekst = File.ReadAllLines(#"C:\zoo.txt");
//full of array
string[] tablica = tekst;
for(int s=0;s<tablica.Length;s++)
{
Console.WriteLine(tablica[s]);
}
//----------------Show all of array---------------------------//
//----------------Giv a number of column-----------------////
Console.WriteLine("Podaj kolumne");
int a = Convert.ToInt32(Console.ReadLine());
//Console.WriteLine("Podaj wiersz");
//int b = Convert.ToInt32(Console.ReadLine());
int n = tablica.Length;
int m = tablica[a].Split(',').Length;
string[,] liczby = new string[n, m];
for (int j = 0; j < n; j++)
{
int suma = 0;
for (int i = 0; i < m; i++)
{
//somethink should be here
}
}
Any ideas for solving this?
try:
//data patch
string[] tekst = File.ReadAllLines(#"C:\zoo.txt");
//full of array - you allready have a string[], no need for a new one
//string[] tablica = tekst;
for(int s=0;s<tekst.Length;s++)
{
Console.WriteLine(tekst[s]);
}
//----------------Show all of array---------------------------//
//----------------Giv a number of column-----------------////
// try to use names with some meaning for variables, for example instead of "a" use "column" for the column
Console.WriteLine("Podaj kolumne");
int column = Convert.ToInt32(Console.ReadLine());
// your result for zeros in a given column
int suma = 0;
// for each line in your string[]
foreach ( string line in tekst )
{
// get the line separated by comas
string[] lineColumns = line.Split(',');
// check if that column is a zero, remember index is base 0
if ( lineColumns[column-1] == "0" )
suma++;
}
Console.WriteLine(suma);
EDIT: Just make sure to validate that the column they ask for, really exist in your array, AND if you do not consider the first column as the one with the name, adjust this part
lineColumns[column] // instead of lineColumns[column-1]
Related
I have an comma separated string like this:
string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#";
This is basically the data from an csv file where I am using reader to read from file.
In the above string ',' represents the data delimeter while '#' represents EOL of the file.
myString = myString.TrimEnd('#'); //Removing extra # in the end.
//Result of above 1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,
I want to convert the above into multidimentional array, loop through it reading value of each row data and create my own json.
So I started with the below code. This would result me with row and column count.
int rowCount = result.TrimEnd('#').Split('#').Count();
int colCount = result.TrimEnd('#').Split('#')[0].TrimEnd(',').Split(',').Length;
//Defining my object which I want to fill.
JObject myObject = new JObject();
Below I want to loop through row and column getting data value from each row and column
for (int row = o ; row <= rowCount; row++)
{
for (int col = 0; col <= colCount; col++)
{
//So here I want to do something like:
var rowValue = multiArray[row][col];
//After getting the row value below is the logic to add to my object
if(col == 0)
{
myObject.Add("first", rowValue);
}
else if(col == colCount)
{
myObject.Add("last", rowValue);
}
else
{
myObject.Add(col, rowValue);
}
}
}
So my question is how can I create the multidimentional array "multiArray" in my code.
Example of my json:
{
"first": 1
"1": a,
"2": b,
"last": C1
},
{
"first": 2
"1": c,
"2": d,
"last": C2
}
The following code creates and fills your multi-dimensional array, but there is a problem with your data. Because of the extra commas your json will not look like your sample json.
string myString = "1,a,b,C1,,#2,d,e,C2,,#3,f,g,C3,,#4,h,i,C4,,#".TrimEnd('#');
var rows = myString.Split('#');
var rowCount = rows.Length;
var columnCount = rows[0].Split(',').Length;
string[,] multiArray = new string[rowCount, columnCount];
for (int i = 0; i < rowCount; i ++)
{
var values = rows[i].Split(',');
for (int j = 0; j < columnCount && j < values.Length; j++)
{
multiArray[i,j] = values[j];
}
}
The results I get from this are that there is a 4x6 array with only 4 values in each row.
I have a text file that is being read in and then stored in a string[] which I then then convert into an int[], my bubblesort then should sort it but it doesn't because the values from the text files are decimals. So my question is how do I convert either the string[] or int[] to something that can accept decimal values, such as a double[] if there is such a thing. Thanks.
Code:
string[] sh1OpenData = File.ReadAllLines("SH1_Open.txt");
...
else if(input2.ToLower() == "open") //----
{
int[] intSh1OpenData = new int[sh1OpenData.Length];
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToInt32(sh1OpenData[x]);
}
Console.WriteLine("\n");
Console.WriteLine("Unsorted");
for (int i = 0; i < intSh1OpenData.Length; i++)
{
Console.Write(intSh1OpenData[i] + " ");
Console.WriteLine(" ");
}
int temp = 0;
for (int write = 0; write < intSh1OpenData.Length; write++)
{
for (int sort = 0; sort < intSh1OpenData.Length - 1; sort++)
{
if (intSh1OpenData[sort] > intSh1OpenData[sort + 1])
{
temp = intSh1OpenData[sort + 1];
intSh1OpenData[sort + 1] = intSh1OpenData[sort];
intSh1OpenData[sort] = temp;
}
}
}
Console.WriteLine("\n\n\nSORTED");
for (int i = 0; i < intSh1OpenData.Length; i++)
Console.Write(intSh1OpenData[i] + "\n");
}
You should not be using int to do comparisons on string. Use String.Compare(return 0 if equal, -1 if less than, or 1 if greater than) or List.Sort() to sort string array
Pretty simple with LINQ
var asDouble = sh1OpenData.Select(x => Double.Parse(x)).OrderBy(x => x).ToArray();
This will give you a sorted (ascending order) array of Double.
Note: this assumes that all of sh1OpenData can be parsed as a Double, and will throw an exception if not.
The only changes that you will need to make are listed below:
double[] intSh1OpenData = new double[sh1OpenData.Length]; // double[] instead of int[]
for (int x = 0; x < sh1OpenData.Length; x++)
{
intSh1OpenData[x] = Convert.ToDouble(sh1OpenData[x]); // Convert to Double
}
also change the declaration of your temp variable to double temp;
Something that you could read through since you mentioned that you are new to programming:
C# Sort Arrays and Lists Examples
MSDN: List.Sort Method
What I am doing is reading in from a text file, and then storing the contents in a 2D array, but my array is off by one at each row and column. Maybe this is simple and I am just not seeing it?
The contents of my text file:
0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,1707,0007,
0007,0007,0007,0007,0401
When my array is returned, the value 17 is located at [3,3]...it should be [4,4]. Below is my code. I've spent to much time on this already, could someone please help?
public int[,] Generate(string inputFilePath)
{
if (File.Exists(inputFilePath))
{
Dictionary<string, int> counts = GetRowAndColumnCounts(inputFilePath);
int rowCount = counts["row_count"];
int columnCount = counts["column_count"];
returnArray = new int[rowCount, columnCount];
using (StreamReader sr = File.OpenText(inputFilePath))
{
string s = "";
string[] split = null;
for (int i = 0; (s = sr.ReadLine()) != null; i++)
{
split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < columnCount; j++)
{
returnArray[i, j] = int.Parse(split[j].Substring(0,2));
}
}
}
}
else
{
// throw new FileDoesNotExistException("Input file does not exist");
}
return returnArray;
}
Array indexes start at 0. So index 3 is the 4. element.
http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
C# arrays are zero indexed; that is, the array indexes start at zero.
On my array, on line 40, my boundaries are outside of the array, but I am not sure how to format this since this is my first program with a multi dimensional array. Please help me. Thanks! (Line 40 is array[i, 0] = randomArray.Next(0, 100);)
namespace Exercise6
{
class Program
{
static void Main(string[] args)
{
OtherClass aTable = new OtherClass(); //instantiate class
Console.WriteLine("How many rows do you want your two-dimensional array to be?");
aTable.SRows = Console.ReadLine(); //reads input for how many rows that the user would like
aTable.IntRows = int.Parse(aTable.SRows); //convert rows to int
Console.WriteLine("Thanks you! How many columns would you like your two-dimensional arry to be?");
aTable.SColumns = Console.ReadLine(); //reads input for how many columns that the user would like
aTable.IntColumns = int.Parse(aTable.SColumns); //convert columns to int
//set two dimensional array based upon the size that the user has requested
int[ , ] array = new int[aTable.IntColumns, aTable.IntRows];
Random randomArray = new Random(); //call to random class to ask for random numbers
for (int i = 0; i <= aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
//both arrays here are overloaded. See this site to see if can get help. Site is below after last close loop
for (int y = 0; y <= aTable.IntRows; y++) // columns
{
array[y, y] = randomArray.Next(0, 100);
}
Console.WriteLine(array);
}
}
}
namespace Exercise6
{
class OtherClass
{
private string sRows;
public string SRows { get; set; }
private int intRows;
public int IntRows { get; set; }
private string sColumns;
public string SColumns { get; set; }
private int intColumns;
public int IntColumns { get; set; }
}
}
Change loop condition to i < aTable.IntColumns
You loop starts from 0 and goes to value of aTable.IntColumns - 1
and code becomes
for (int i = 0; i < aTable.IntColumns; i++)
{
array[i, 0] = randomArray.Next(0, 100);
}
Since arrays are zero based, you can't go up to the max value:
// This line is incorrect
for (int i = 0; i <= aTable.IntColumns; i++)
That line should be:
for (int i = 0; i < aTable.IntColumns; i++)
That will let it go from 0 to aTable.IntColumns-1, which are the valid indices for for an array of aTable.IntColumns length. The same is true of the rows.
C# arrays used zero-relative offsets as their indices. That means that for an array of length n, the domain of its index i is 0 <= i <= n-1. A 100-element array has an index that ranges from 0-99. If you are trying to fill an m*n array with random values.
If your assignment is fill the array with random values (as seems likely), you'll need to do something like this:
for ( int i=0 ; i < aTable.IntRows ; i++ ) // rows
{
for ( int j= 0 ; i < aTable.IntColumns ; j++ )
{
array[i,j] = randomArray.Next(0,100); // for every value in each row, insert a random number
}
}
You might also note that your comments don't match your code: you are iterating over rows and checking the column limit and vice-versa.
The error is in for loop:
for (int i = 0; i < aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
i < aTable.IntColumns should be the stopping criteria
I have a list of string arrays:
List<string[]> parsedRaw = new List<string[]>();
This list contains lines read in from a CSV, where parsedRaw[3][5] would be the fifth item read off the third line of the CSV.
I know that I can find the number of rows in the list with:
parsedRaw.Count
But, given a row, how can I find the number of elements in that row? I'm trying to implement a test before entering a loop to read from the list, in order to avoid an "Index was outside the bounds of the array" error, where the loop is:
for (k = 0; k < nBytes; k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
I'm encountering the error on a row in the CSV that has fewer elements than the others. Before entering this loop, I need to check whether parsedRaw[i] has at least "StartInt + nBytes" elements.
Thanks for any suggestions!
A row is just a string array string[], so you can find its size using the Length property of the array.
foreach (string[] row in parsedRaw) {
for (int i = 0 ; i != row.Length ; i++) {
// do something with row[i]
}
}
The number of elements in a given row is determined by
parsedRaw[theRowIndex].Length
To fix your for loop you need to constrain the StartInt + k value to be less than the minimum of nBytes and the row length
for (k = 0; (k < nBytes) && (k + StartInt < parsedRaw[i].Length); k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
Try
List<string[]> parsedRaw = new List<string[]>();
parsedRaw.Add(new string[] {"test1", "test2"});
parsedRaw.Add(new string[] { "test1", "test2", "test3" });
int totalSize = 0;
for (int i = 0; i < parsedRaw.Count(); i++)
{
int rowSize = 0;
for (int k = 0; k < parsedRaw[i].Count(); k++)
{
rowSize += parsedRaw[i][k].Length;
}
totalSize += rowSize;
}