As much as I tried to find a similar version in the question here, I couldn't find something.. so I am asking your help.
After reading some numbers from a textfile (now in string format), I split them in rows and columns and add them to a 2d-array (in string format as well). Now I want to convert everythinh in integers so that I can play with sorting the numbers out later.
Here is my code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ArrayProgram
{
class Program
{
int number = 0;
int i = 0;
int k = 0;
string strnum;
public void onetohundredints()
{
StreamWriter writer = new StreamWriter("numberstored.txt");
for (i = 0; i < 10; i++)
{
for (k = 0; k < 10; k++)
{
number++;
Console.Write(number + " ");
strnum = number.ToString();
writer.Write(strnum + " ");
}
Console.WriteLine();
writer.WriteLine();
}
writer.Close();
}
public void readints()
{
StreamReader reader = new StreamReader("numberstored.txt");
string data = reader.ReadToEnd();
reader.Close();
string[,] dataarray = new string[10,10];
int[] numbers = new int[100];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
dataarray[i, j] = numbersperrow[j];
}
}
}
public static void Main(string[] args)
{
Program prog = new Program();
prog.onetohundredints();
prog.readints();
Console.ReadKey();
}
}
}
After I insert the number into the 2d-array, how do I convert all of it in integers?
If you don't have a particular reason to have an array of strings, you can just save you data as int in the first place. Just change your inner for loop to do:
var parsed = int.TryParse(numbersperrow[j], out dataarray[i, j]);
if (!parsed)
{
// Error
}
While that should work, I would suggest to re-write your ReadData method to look similar to the sample below.
public int[,] ReadData(string filePath, int xDimension, int yDimension)
{
var results = new int[xDimension, yDimension];
var lines = File.ReadLines(filePath);
for (var i = 0; i < allLines.Count(); i++)
{
var values = lines[i].Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (var j = 0; j < values.Count(); j++)
{
var parsed = int.TryParse(values[j], out results[i, j]);
if (!parsed) { }
}
}
return results;
}
You're putting everything into a string array. That array can only hold strings, not numbers. If you want to make the 2d array hold numbers, define it as int[,] dataarray = new int[10,10]; Next, in the final loop, simply do dataarray[i, j] = Convert.ToInt32(numbersperrow[j]);
Edit: You can use int.TryParse(numbersperrow[j], out value) if you aren't sure that numbersperrow[j] will be a number. Value will return false if the conversion is not successful.
I am happy to say that both solutions work. I now have my numbers in my 2d array. But now I wish to play with them. Let's say that I want the numbers printed on the screen in reverse order.
Having this correct solution:
int numbers;
int[,] dataarray = new int[10,10];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
numbers = int.Parse(numbersperrow[j]);
dataarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
I know that I have to make a double for loop. But how do I write a succesful syntax for the numbers to be printed properly?
I also tried this:
int[,] reversedarray = new int[10, 10];
reversedarray[i, j] = Array.Reverse(dataarray[i,j]);
but the dataarray[i,j] becomes red and the error "cannot convert from int to system.Array occurs... what am I missing?
I also tried this...
for (i = 10; i <= dataperlines.Count(); i--)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (j =10; j <= numbersperrow.Count(); j--)
{
numbers = int.Parse(numbersperrow[j]);
reversedarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
But I have an IndexOutOfRange exception coming from
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
I understood that since I splitted the columns into rows too, it is unecessary to write it again, but I am stuck. I tried simplifying the code since I have my 2darray with its elements and I my tries were fallacious. Any more suggestions?
Related
I have a program to print all possible combinations from a string array. The printing is done fine on the screen. However, When I add the same to a list, all list members reflect the last generated combination. So, I am not sure what is happening. Please see the code below.
class Program
{
static List<string[]> list = new List<string[]>();
static void combinationUtil(string[] arr, string[] data,
int start, int end,
int index, int r)
{
// Current combination is
// ready to be printed,
// print it
if (index == r)
{
list.Add(data);
for (int j = 0; j < r; j++)
{
Console.Write(data[j] + " ");
}
Console.WriteLine("");
return;
}
// replace index with all
// possible elements. The
// condition "end-i+1 >=
// r-index" makes sure that
// including one element
// at index will make a
// combination with remaining
// elements at remaining positions
for (int i = start; i <= end &&
end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i + 1,
end, index + 1, r);
}
}
// The main function that prints
// all combinations of size r
// in arr[] of size n. This
// function mainly uses combinationUtil()
static void printCombination(string[] arr,
int n, int r)
{
// A temporary array to store
// all combination one by one
string[] data = new string[r];
// Print all combination
// using temprary array 'data[]'
combinationUtil(arr, data, 0,
n - 1, 0, r);
}
// Driver Code
static public void Main()
{
string[] arr = { "string-1", "string-2", "string-3", "string-4" };
int r = 2;
int n = arr.Length;
printCombination(arr, n, r);
foreach (var item in list)
{
Console.WriteLine(item[0]+" "+item[1]);
}
}
}
Following is the output
I found a way to do this. But, I am not sure if this is the only and best way to do this. If you have any other way of doing this better, please answer. Following is how I did this.
list.Add(new string[2] { data[0], data[1] });
Here is a solution using List. Note the string[] uniquePair = new string[2]; prior to each list.Add().
class Program
{
static List<string[]> list = new List<string[]>();
// Driver Code
static public void Main()
{
string[] arr = { "string-1", "string-2", "string-3", "string-4" };
int r = 2;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
string[] uniquePair = new string[2];
uniquePair[0] = arr[i];
uniquePair[1] = arr[j];
list.Add(uniquePair);
}
}
foreach (string[] pair in list)
{
Console.WriteLine($"{ pair[0] } + { pair[1] }");
}
Console.ReadKey(true);
}
}
Output:
string-1 + string-2
string-1 + string-3
string-1 + string-4
string-2 + string-3
string-2 + string-4
string-3 + string-4
I need to create an 2D array from a text file.
my text file looks like this
Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2
and so on
I want my multidimensional array to make something like this
array = {{name1,id1,class1,status1},{name2,id2,class2,status2}}
I have seen other post related to it but non seems to be helping thats why posting again
I assume that all of the lines have the same format. We can simply iterate through the lines as below:
string[] lines = File.ReadAllLines(filename);
int len0 = lines.Length;
int len1 = lines[0].Split(':').Length;
string[,] array = new string[len0, len1];
for (int i= 0; i < len0; i++)
{
string line = lines[i];
string[] fields = line.Split(':');
if (fields.Length != len1)
continue; // to prevent error for the lines that do not meet the formatting
for(int j = 0; j < len1; j++)
{
array[i,j] = fields[j];
}
}
Going to a jagged array is pretty easy. Going from a jagged array to a 2D array just requires some assumptions: like that all rows have the same number of items and that you know how many rows and columns there are when you create the array.
string.Split will help you create the jagged array. And a straightforward loop will help you create the multi-dimensional array.
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
string input = #"Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2";
var jagged = input
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Split(':').ToArray())
.ToArray();
var multi = new string[jagged.Length, jagged[0].Length];
for (int i = 0; i < jagged.Length; ++i) {
for (int j = 0; j < jagged[0].Length; ++j) {
multi[i, j] = jagged[i][j];
Console.WriteLine("[{0},{1}] = {2}", i, j, multi[i, j]);
}
}
}
}
It is better to use a List object like code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
List<List<string>> data = new List<List<string>>();
StreamReader reader = new StreamReader(FILENAME);
string line = "";
while ((line = reader.ReadLine()) != null)
{
List<string> lineArray = line.Split(new char[] { ':' }).ToList();
data.Add(lineArray);
}
reader.Close();
}
}
}
I have a problem with converting string array (previously loaded from .txt file) to integer one. File has got 100 random numbers, they load without any problem, I just need to convert them to integers to make them sortable with 3 types of sorting. I've tried many thing that were said here, but none of them seem to work. All the time I'm getting an error saying that it can't be converted.
Here is my loading from the file code:
string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
int[] numb= new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
And after some options to choose I'm using switch to pick one:
switch (a)
{
case 1:
Console.WriteLine("1. Bubble.");
//int[] tab = numb;
babel(path);
for (int z = 0; z < path.Length; z++)
{
Console.Write(path[z] + ", ");
}
break;
I've got bubble sorting method in my program too, don't think it is necessary to post it here.
If anyone can help me here, I'd be really grateful.
#Amy - I've tried this:
numb[i] = path[i].Convert.toInt32(); - it doesn't work.
What I want to achieve is to change every number in this array to int, I think it should be involved here:
{
Console.WriteLine(path[i]);
}
This conversion works.
#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Length; i++)
{
Console.WriteLine(numb[i]);
}
It is better to use TryParse instead of parse. Also it is easier to work with List, than with array.
using System;
using System.Collections.Generic;
namespace StringToInt
{
class Program
{
static void Main(string[] args)
{
String[] path = { "1", "2", "3", "a", "b7" };
List<int> numb = new List<int>();
foreach (string p in path)
{
if (int.TryParse(p, out int result))
{
numb.Add(result);
}
}
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Count; i++)
{
Console.WriteLine(numb[i]);
}
}
}
}
I can't imagine this wouldn't work:
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
I think your issue is that you are using File.ReadLines, which reads each line into a single string. Strings have no such ToArray function.
I'm not really sure what's wrong with the implementation I have. How would I fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectionSort
{
class Program
{
static void algorithm(int[] to_sort)
{
int bufor;
for (int i = 0; i < to_sort.Length; i++)
{
for (int j = i + 1; j < to_sort.Length; j++)
{
if (to_sort[i] >= to_sort[j])
{
bufor = to_sort[i];
to_sort[i] = to_sort[j];
to_sort[j] = bufor;
}
}
}
}
static void Main(string[] args)
{
int[] to_sort = new int[100];
Console.WriteLine("");
for (int i = 1; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.WriteLine("");
algorithm(to_sort);
Console.WriteLine("\n");
Console.WriteLine("Sorted list:");
for (int i = 0; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.Read();
}
}
}
This produces the following output:
Original list: 00000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
Sorted list: 000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
It looks like my array (int[] to_sort) was empty, am I right? How can I get this:
Original list: 123456789....100
Sorted list: 123456789...100
Perhaps you originate from the C++ world where initializing an array does not mean the array is "cleaned" (the data that happened to be located at the allocated memory remains untouched), but in C# if you initialize an array like:
int[] to_sort = new int[100];
It means you construct an array where every element is set to default(T) with T the type. For an int that is 0 (for objects it is null, etc.). So you just constructed an array filled with zeros.
You can however for instance fill it with random numbers like:
Random rand = new Random();
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = rand.Next(0,1000);
}
EDIT
Based on your comment, you want to fill it with the positions, you can do this like:
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = i+1;
}
I think the easiest and shortest way you can initialize an array of sequential numbers is like this:
int[] to_sort = Enumerable.Range(1, 100).ToArray();
What you have will just allocate the array and fill it with the default value for int, which is 0:
int[] to_sort = new int[100];
I would like to create an array of an array from a text file...
There are 20000 line with 21 strings in each line separated by ',' .
I would like to read each line and make it into an array , each line being a new array within.
So I wanted to create the jagged array by starting it like this:
string[][] SqlArray = new string[200000][21];
But it gives: ERROR MESSAGE : Invalid rank specifier: expected ',' or ]
How would I create this array or initialize it?
I will be populating the data in the array like this:
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
for (int i = 0; i < workingArray.Length; i++)
{
for (int k = 0; k < 20; k++)
{
SqlArray[i][k] = workingArray[k];
}
}
}
Thank you
That type of initialization only works in Java. You must declare an array of arrays then initialize each in a loop.
string[][] SqlArray = new string[21][];
for(int index = 0; index < SqlArray.Length; index++)
{
SqlArray[index] = new string[2000000];
}
Alternatively, you can use a non-jagged array. It will probably work for what you need.
string[,] SqlArray = new string[21 , 2000000];
It can be accessed like so:
SqlArray[2,6264] = x;
To anyone who is interested this is how I ended up implementing it:
TextReader readIn = File.OpenText("..\\..\\datafile.txt");
string[][] SqlArray = new string[rowNumCreate][];
int e = 0;
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
SqlArray[e] = new string[valuesInRow +1];
for (int k = 0; k < workingArray.Length; k++)
{
SqlArray[e][k] = workingArray[k];
}
e++;
}
The file being read is a simple mock database set as a flat file that was auto-generated to test an algorithm that I am implementing, which works with jagged arrays; hence instead of working with a data base I just created this for ease of use and to increase and decrease size at will.
Here is the code to build the text file:
Random skill_id;
skill_id = new Random();
// int counter =0;
string seedvalue = TicksToString();
int rowNumCreate = 200000;
int valuesInRow = 20;
string lineInFile = seedvalue;
string delimiter = ",";
for (int i = 0; i < rowNumCreate; i++)
{
for (int t = 0; t < valuesInRow; t++)
{
int skill = skill_id.Next(40);
string SCon = Convert.ToString(skill);
lineInFile += delimiter + SCon;
}
if (rowNumCreate >= i + 1)
{
dataFile.WriteLine(lineInFile);
lineInFile = "";
string userPK = TicksToString();
lineInFile += userPK;
}
}
dataFile.Close();
public static string TicksToString()
{
long ms = DateTime.Now.Second;
long ms2 = DateTime.Now.Millisecond;
Random seeds;
seeds = new Random();
int ran = seeds.GetHashCode();
return string.Format("{0:X}{1:X}{2:X}", ms, ms2, ran).ToLower();
}
I am still a student so not sure if the code is A-grade but it works :)