how to normalize the complex numbers in c#?when i have saved the text file of complex number in notepad.then i want to use these complex numbers in my c# code.And can be read text file of complex number in c#?
Current code used:
using (TextReader reader = File.OpenText("a.txt"))
{
var lineCount1 = File.ReadLines("a.txt").Count();
x1 = new double[lineCount1, 512];
for (int i = 0; i < lineCount1; i++)
{
for (int j = 0; j < 512; j++)
{
string line = reader.ReadLine();
string[] bits = line.Split(' ');
x1[i, j] = double.Parse(bits[j]);
}
}
}
its not working.!!! error in last line.
Perhaps you should have something like this:
static void Main(string[] args)
{
var lines = File.ReadAllLines("a.txt");
var complexes = new Complex[lines.Length];
for (int i = 0; i < complexes.Length; i++)
{
complexes[i] = Parse(lines[i]);
}
}
private static Complex Parse(string s)
{
var split = s.Split(new char[' '], StringSplitOptions.RemoveEmptyEntries); // I guess string is something like "12 54". If you have "12 + 54i" you'l get an exception here
return new Complex(double.Parse(split[0]), double.Parse(split[1]));
}
Related
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]);
}
}
}
Basically, I am trying to split an array and want to pass its value into another array.
But, I am not able to do it.It is givin an error:
Cannot implicitly convert type String[] to string"
StreamReader EmployeeFile = new StreamReader(#"C:\Users\user\Desktop\FoodDeliverySystem\Employee_details.txt");
String ReadEmployeeData = EmployeeFile.ReadToEnd();
String[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for (int k = 0; k < 5; k++)
{
for (int l = 0; l < 5; l++)
{
Console.WriteLine("test");
String[,] ReadEmployeeDataByLineByCategorie = new string[k, l];
ReadEmployeeDataByLineByCategorie[k,l] = ReadEmployeeDataByLine[l].Split(',');
}
}
Since you can't be sure of how many of those values you're gonna have in each category of yours, you should use jagged arrays
That should do:
var readEmployeeDataByLine = new StreamReader(#"C:\pathToFile.txt").ReadToEnd().Split(';');
var readEmployeeDataByLineByCategorie = new string[readEmployeeDataByLine.Length][];
for (int i = 0; i < readEmployeeDataByLineByCategorie.Length; i++)
readEmployeeDataByLineByCategorie[i] = readEmployeeDataByLine[i].Split(',');
ReadEmployeeDataByLineByCategorie[k,l] is a string
while ReadEmployeeDataByLine[l].Split(',') is a string[]
string[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for(int i = 0;i< ReadEmployeeDataByLine.Length;i++)
{
string split = ReadEmployeeDataByLine[l].Split(',');
for(int j=0; j<split.Length;j++)
ReadEmployeeDataByLineByCategorie[i,j] = split[j]
}
i have text file consist of data like:
1,2
2,3
3,4
4,5
Now I want to save the data into an array. So i do split:
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
}
however my data save in string[] while I have a GlobalDataClass array declared as double[,]. Something like this:
static class GlobalDataClass
{
public static double[,] Array = new double[4, 2];
}
I need to assign the data to the GlobalDataClass:
GlobalDataClass.Array = data;
So my question is how to convert the string[] to double[,]?
Since you have a 2-d array, you'd need to iterate over each line and extract the values, then assign it into the proper position. You can use Select and double.Parse to convert the string values to double.
using (var reader = new StreamReader("file.txt"))
{
string line;
for (var count = 0; count < 4; ++count)
{
var data = reader.ReadLine()
.Split(',')
.Select(v => double.Parse(v))
.ToArray();
GlobalDataClass.Array[count,0] = data[0];
GlobalDataclass.Array[count,1] = data[1];
}
}
Now if your array was really double[][], then you could do something more like:
GlobalDataClass.Array = File.ReadAllLines("file.txt")
.Select(l => l.Split(',')
.Select(v => double.Parse(v))
.ToArray())
.ToArray();
Note: I think it's like a really bad idea to make it a global variable. There's probably a much better way to handle this.
I think that the best way is to use Array.ConvertAll.
Example:
string[] strs = new string[] { "1.00", "2.03" };
Array.ConvertAll(strs, Double.Parse);
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
int counter =0 ;
while((line = file.ReadLine()) != null)
{
var lineData= line.Split(',');
GlobalDataClass.Array[counter,0] = double.Parse(lineData[0]);
GlobalDataClass.Array[counter,1] = double.Parse(lineData[1]);
counter++;
}
Try This:
String [] words;
int lineCount=0;
String [] Lines=File.ReadAllLines(#"C:\Data.txt");
for (int i=0;i<Lines.Length;i++)
{
words = Lines[i].Split(',');
for (int j = 0; j < 2; j++)
{
GlobalDataClass.Array[i,j] = Convert.ToDouble(words[j].Trim());
}
}
I am using some part of your code to show you how you do this task.
int mCount = 0;
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
GlobalDataClass.Array[mCount , 0] = Double.Parse(data[0]);
GlobalDataClass.Array[mCount , 1] = Double.Parse(data[1]);
mCount += 1;
}
double[] doubleArray = strArray.Select(s => Double.Parse(s)).ToArray();
int k = 0;
for (int i = GlobalDataClass.Array.GetLowerBound(0); i <= GlobalDataClass.Array.GetUpperBound(0); i++)
{
for (int j = GlobalDataClass.Array.GetLowerBound(1); j <= GlobalDataClass.Array.GetUpperBound(1); j++)
{
double d = doubleArray[k];
GlobalDataClass.Array.SetValue(d, i, j);
k++;
}
}
If the number of lines can vary:
var lines = File.ReadAllLines("file.txt");
var data = new double[lines.Length, 2];
for (var i = 0; i < lines.Length; i++)
{
var temp = lines[i].Split(',');
data[i,0] = double.Parse(temp[0]);
data[i,1] = double.Parse(temp[1]);
}
GlobalDataClass.Array = data;
..or, if the number of lines is a constant value:
using (var sr = new StreamReader("file.txt"))
{
var i = 0;
var len = GlobalDataClass.GetLength(0);
while (sr.Peak() >= 0 && i < len)
{
var temp = sr.ReadLine().Split(',');
GlobalDataClass.Array[i,0] = double.Parse(temp[0]);
GlobalDataClass.Array[i,1] = double.Parse(temp[1]);
i++;
}
}
I have tried several time but couldn’t find the way to solve my problem. Here my txt file shown in below.
695
748
555
695
748
852
639
748
I put the for loop to read the data and put them in to array. So now I want to filter repeat numbers from the input txt data. How can I have a count of repeated data.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
for (int i = 0; i < n; i++)
{
res[i] = line[i].Substring(x,x+8);
Console.WriteLine(res[i]);
}
Console.ReadLine();
}
You use GroupBy()
var result = res.GroupBy(x => x);
foreach(var g in result)
{
Console.WriteLine(g.Key + " count: " + g.Count());
}
Somehow you have to keep track of things you have seen before.
One way to do that is to place the numbers in a list the first time you see them. If a given number is already in the list, filter it out on the latter occurrences.
Here's an example with the list. Note that your code to fetch a substring of the input crashes.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
List<string> observedValues = new List<string>();
for (int i = 0; i < n; i++)
{
string consider = line[i]; // This code crashes: .Substring(x, x + 8);
if (!observedValues.Contains(consider))
{
observedValues.Add(consider);
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
Another method is to pre-sort the input so that duplicates are adjacent.
Example:
(Note, you may want to remove white space in the input prior to sorting. Leading white space will break this code).
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
string previous = null;
Array.Sort(line); // Ensures that equal values are adjacent
for (int i = 0; i < n; i++)
{
string consider = line[i].Trim(); // Note leading whitespace will break this.
if (consider != previous)
{
previous = consider;
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
So now I want to filter repeat numbers from the input txt data.
if all you need is filter out duplicates you can use this:
String[] line = File.ReadAllLines("C:/num.txt");
var filteredLines = line.Distinct();
foreach (var item in filteredLines)
Console.WriteLine(item);
I need a C# function that takes 2 strings as an input and return an array of all possible combinations of strings.
private string[] FunctionName(string string1, string string2)
{
//code
}
The strings input will be in the following format:
string1: basement
string2: a*fa
Now what I need is all combinations of possible strings using the characters in String2 (ignoring the * symbols), and keeping them in the same character position like this:
baaement, baaefent, baaefena, basefent, basemena, etc.
EDIT:
This is not homework. I need this function for a piece of a program I am doing.
The following is the code I have so far but it has some bugs.
static List<string> combinations = new List<string>();
static void Main(string[] args)
{
//include trimming of input string
string FoundRes = "incoming";
string AltRes = "*2*45*78";
List<int> loc = new List<int>();
string word = "";
for (int i = 0; i < AltRes.Length; i++)
{
if (AltRes[i] != '*')
{
loc.Add(i);
word += AltRes[i];
}
}
generate(word);
string[] aaa = InsertSymbol(FoundRes, loc.ToArray(), AltRes, combinations);
Console.WriteLine("input string: " + FoundRes);
Console.WriteLine("Substitute string: " + AltRes);
Console.WriteLine("============Output============");
for (int j = 0; j < aaa.Length; j++)
{
Console.WriteLine(aaa[j]);
}
Console.ReadKey();
}//
private static void generate(string word)
{
// Add this word to combination results set
if (!combinations.Contains(word))
combinations.Add(word);
// If the word has only one character, break the recursion
if (word.Length == 1)
{
if (!combinations.Contains(word))
combinations.Add(word);
return;
}
// Go through every position of the word
for (int i = 0; i < word.Length; i++)
{
// Remove the character at the current position
// call this method with the String
generate(word.Substring(0, i) + word.Substring(i + 1));
}
}//
private static string[] InsertSymbol(string orig, int[] loc, string alternative, List<string> Chars)
{
List<string> CombinationsList = new List<string>();
string temp = "";
for (int i = 0; i < Chars.Count; i++)
{
temp = orig;
for (int j = 0; j < Chars[i].Length; j++)
{
string token = Chars[i];
if (alternative.IndexOf(token[j]) == loc[j])
{
temp = temp.Remove(loc[j], 1);
temp = temp.Insert(loc[j], token[j].ToString());
// int pos = sourceSubst.IndexOf(token[j]);
// sourceSubst = sourceSubst.Remove(pos, 1);
// sourceSubst = sourceSubst.Insert(pos, ".");
}
else
{
temp = temp.Remove(alternative.IndexOf(token[j]), 1);
temp = temp.Insert(alternative.IndexOf(token[j]), token[j].ToString());
}
}
CombinationsList.Add(temp);
}
return CombinationsList.ToArray();
}//
It does sound like homework. As a suggestion, I would ignore the first parameter and focus on getting all possible permutations of the second string. What's turned off, what's turned on, etc. From that list, you can easily come up with a method of swapping out characters of the first string.
On that note, I'm in the uncomfortable position of having a function ready to go but not wanting to post it because of the homework implication. I'd sure love for somebody to review it, though! And technically, there's two functions involved because I just happened to already have a generic function to generate subsets lying around.
Edit: OP says it isn't homework, so here is what I came up with. It has been refactored a bit since the claim of two functions, and I'm more than open to criticism.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string original = "phenomenal";
string pattern = "*xo**q*t**";
string[] replacements = StringUtility.GetReplacementStrings(original, pattern, true);
foreach (string replacement in replacements)
Console.WriteLine(replacement);
Console.Read();
}
public static class StringUtility
{
public static string[] GetReplacementStrings(string original, string pattern, bool includeOriginal)
{
// pattern and original might not be same length
int maxIndex = Math.Max(original.Length, pattern.Length);
List<int> positions = GetPatternPositions(pattern, maxIndex, '*');
List<int[]> subsets = ArrayUtility.CreateSubsets(positions.ToArray());
List<string> replacements = GenerateReplacements(original, pattern, subsets);
if (includeOriginal)
replacements.Insert(0, original);
return replacements.ToArray();
}
private static List<string> GenerateReplacements(string original, string pattern, List<int[]> subsets)
{
List<string> replacements = new List<string>();
char[] temp = new char[original.Length];
foreach (int[] subset in subsets)
{
original.CopyTo(0, temp, 0, original.Length);
foreach (int index in subset)
{
temp[index] = pattern[index];
}
replacements.Add(new string(temp));
}
return replacements;
}
private static List<int> GetPatternPositions(string pattern, int maxIndex, char excludeCharacter)
{
List<int> positions = new List<int>();
for (int i = 0; i < maxIndex; i++)
{
if (pattern[i] != excludeCharacter)
positions.Add(i);
}
return positions;
}
}
public static class ArrayUtility
{
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
}
}
since it's hopw work I'd only suggest some way to solve the problem rather than writing the code.
if you loop the second parameter every time you hit a letter you'll have to options either use the letter from the first argument or the letter from the second. collect all these optins together with the index. keep a list of the parts from the first argument that will never change. iterate thorugh those two lists to created all the possible permutations
Decimal to Binary converted code is stolon copied from here.
static void Main()
{
string string1 = "basement";
string string2 = "**a*f**a";
string[] result = GetCombinations(string1, string2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static string[] GetCombinations(string string1, string string2)
{
var list = new List<List<char>> { new List<char>(), new List<char>() };
var cl = new List<char>();
List<string> result = new List<string>();
for (int i = 0; i < string1.Length; i++)
{
if (string2[i] == '*')
{
cl.Add(string1[i]);
}
else
{
list[0].Add(string1[i]);
list[1].Add(string2[i]);
}
}
int l = list[0].Count;
for (int i = 0; i < (Int64)Math.Pow(2.0,l); i++)
{
string s = ToBinary(i, l);
string ss = "";
int x = 0;
int y = 0;
for (int I = 0; I < string1.Length; I++)
{
if (string2[I] == '*')
{
ss += cl[x].ToString();
x++;
}
else
{
ss += (list[int.Parse(s[y].ToString())][y]);
y++;
}
}
result.Add(ss);
}
return result.ToArray<string>();
}
public static string ToBinary(Int64 Decimal, int width)
{
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
var d = width - BinaryResult.Length;
if (d != 0) for (int i = 0; i < d; i++) BinaryResult = "0" + BinaryResult;
return BinaryResult;
}
which password cracker do you want to program? :)
how about
if string2 contains '*'
foreach(char ch in string1)
replace first * with ch,
execute FunctionName
else
print string2