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);
Related
I have a string[] with values like
string[] s = { "saravanan", "Karthick", "Jackson", "saravanan" };
I want to see below output
saravanan occures 2 times
Karthick occures 1 times
Jackson occures 1 times
How can I do this without using List or Dictionary
This is what I have tried so far:
int i, j;
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"}
Console.WriteLine("Number of Times occured Each Values");
for (i = 0; i < s.Length; i++)
{
int count = 0;
for (j = 0; j < s.Length; j++)
{
if (s[i] == (s[j]))
{
count++;
}
}
Console.WriteLine(s[i]+"is count="+count);
}
That code produces this output:
Number of Times occured Each Values
saravananis count=2
Karthickis count=1
Jacksonis count=1
saravananis count=2
Usually, we solve such problems (querying) via Linq
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
var result = string.Join(Environment.NewLine, s
.GroupBy(item => item)
.Select(chunk => $"{chunk.Key} occures {chunk.Count()} times"));
Console.Write(result);
In case of nested loops (your current code) we should not print out the same name several times. Let's introduce bool appeared if name has been appeared before
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
for (i = 0; i < s.Length; i++) {
int count = 0;
bool appeared = false;
for (j = 0; j < s.Length; j++) {
if (s[i] == (s[j])) {
// Names are same. Do we have the name before?
if (j < i) {
// If yes we have no need to loop any more
appeared = true;
break;
}
count++;
}
}
// if name has been appeared already we shouldn't print it out
if (!appeared)
Console.WriteLine(s[i] + "is count=" + count);
}
Since you don't want "saravanan" to appear twice in your output. Then you could use an empty string as a sentinel value. When you find matches that increase the count, blank out that element and have checks in place to skip the element when you run across it later.
using System;
public class Program
{
public static void Main()
{
string[] s = { "saravanan","KArthick","Jackson","saravanan" };
for (int i = 0; i < s.Length; i++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < s.Length; j++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
if (s[i] == s[j])
{
count++;
// Clear the element to indicate the element as already been counted
s[j] = string.Empty;
}
}
Console.WriteLine("{0} occurs {1} times", s[i], count);
}
}
}
Result
saravanan occurs 2 times
KArthick occurs 1 times
Jackson occurs 1 times
Fiddle Demo
you can use linq group option like this:
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"};
Console.WriteLine("Number of Times occured Each Values");
var groupArray = s.GroupBy(x => x);
foreach (var group in groupArray)
{
Console.WriteLine(group.Key + "is count=" + group.Count());
}
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]));
}
I have made this code to get from 2a3b to aabbb. This also has to apply when no numbers are given. Like aa2b => aabb.
The program is fully working but my problem is, it takes in alot of space. I think it is my split but my array will be like this if the input is 2a2b:
2
NULL
NULL
a
2
NULL
NULL
b
Does someone know what i'm doing wrong? Is it my split?
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
string[] array = new string[20];
int count = 1;
array = Regex.Split(value, "(\\d{0,2})");
while (count < array.Length)
{
int num;
if (array[count] != "")
{
bool isNumeric = int.TryParse(array[count], out num);
if (!isNumeric)
{
test = test + string.fill(array[count], intNumber);
test = test + array[count];
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
count++;
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
How about using a simple Regex.Replace?
string input = "2a3bcccc";
string output = Regex.Replace(
input,
#"(\d+)(\w)",
m => new String(m.Groups[2].Value[0],int.Parse(m.Groups[1].Value)));
result : aabbbcccc
A simpler way to resolve your problem is to get rid of regex, the array creation would be like:
char[] array = value.ToArray();
The code, with the minor corrections due to the array and some improvements being a char array (intead of a string array):
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
foreach (char c in value.ToArray())
{
int num;
bool isNumeric = int.TryParse(c.ToString(), out num);
if (!isNumeric)
{
test = test + new string(c, intNumber);
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
}
Quick test program works like a charm without using a regex.
const string value = "aa2b";
var result = "";
for (var i = 0; i < value.Length; i++)
{
int num;
if (Int32.TryParse(value.Substring(i, 1), out num))
{
for (var j = 0; j < num; j++)
{
result += value.Substring(i + 1, 1);
}
i++;
}
else
{
result += value.Substring(i, 1);
}
}
textBox1.AppendText("woord:" + result);
I generally try to avoid Regex, unless there is a complex pattern I need to verify.
Here is my solution to your problem:
string k = Console.ReadLine();
string t = "";
int count = 0, next;
for (int i = 0; i < k.Length; i++)
{
while (int.TryParse(k[i].ToString(), out next)) // Find the count of the next letter
{
count = count * 10 + next; // If count had a 2, and the next character is 3 (means we need to calculate 23), simply multiply the previous count by 10, and add the new digit
i++; // Move to the next character
}
t += new String(k[i], count > 0 ? count : 1); // Add the new sequence of letters to our string
count = 0; // Clear the current count
}
Console.WriteLine(t);
You can optimize the above, by using the StringBuilder class, but I think it's enough to understand the general solution first, rather than trying to find optimizations.
Let's say you have the string "This is a test"
I pass it to method zee, like ("This is a test", 1)
and want "test This is a";
I pass it to method zee, like ("This is a test", 2)
and want "a test This is";
the number can exceed the total words in variable. If it does it should loop around.
I started with....
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
ArrayList list = new ArrayList();
list.AddRange(origString.Split(' '));
// not sure here -
for (int c = i; c < (list.Count + i); c++)
{
sb.AppendFormat("{0} ", list[c]);
}
return sb.ToString();
}
for(int j=0; j < list.length; j++){
int idx = (j + i) % list.length;
sb.AppendFormat("{0} " , list[idx]);
}
Mostly like Brent Arias's solution, but I think a for loop is more readable, less likely to go infinite.
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
List<string> list = new List<string>();
list.AddRange(origString.Split(' '));
for (int j = 0; j < list.Count; j++)
{
int idx = (j + i) % list.Count;
sb.AppendFormat("{0} ", list[idx]);
}
return sb.ToString();
}
This is how I'd solve it.
private static string f(string s, int start)
{
var arr=s.Split(' ');
start %= arr.Length;
var res=arr.Skip(arr.Length - start).ToList();
res.AddRange(arr.Take(arr.Length - start));
return string.Join(" ", res);
}
I tried writing a one liner with linq but I don't see how to combine 2 lists. Union and Join aren't what I need.
This is how I'd solve it using strings.
public static string zee(string origString, int i)
{
string[] splitStr = origString.Split(' ');
string newStr = "";
// Not sure what you meant by wrap around but this should
// do the trick.
i %= splitStr.Length;
for (int j = (splitStr.Length - i); j < splitStr.Length; j++)
newStr += splitStr[j] + " "; // Add spaces taken by split :(
for (int j = 0; j < (splitStr.Length - i); j++)
newStr += splitStr[j] + " ";
return
newStr;
}
Here's an abomination trying to cram as much into one line as possible:
static string zee(string sentence, int wordCount)
{
var words = sentence.Split(' ');
return string.Join(" ", new[] { words.Skip(words.Count() - wordCount), words.Take(words.Count() - wordCount) }.SelectMany(w => w).ToArray());
}
I havn't tried it, but I think this would do it:
i %= list.Length;
int index = i;
do {
index %= list.Length;
sb.AppendFormat("{0} ", list[index]);
while (++index != i);
static string rearrange(string phase,int index)
{
string[] words = phase.Split(' ');
string[] newwords = new string[words.Length];
int pointer = index;
for (int i = 0; i < words.Length;i++ )
{
if(pointer>=words.Length)
{
pointer = 0;
}
newwords[i] = words[pointer];
pointer++;
}
return string.Join(" ", newwords);
}
Sounds like a homework question to me, but here is an efficient use of the .Net framework:
private static string [] SplitWords(string s, int startWord)
{
string[] words = s.Split(' ');
List<string> output = new List<string>();
output.AddRange(words.Skip(startWord).ToArray());
output.AddRange(words.Take(startWord).ToArray());
return output.ToArray();
}
There is absolutely no error checking in this function so you will have to modify it for production code but you get the idea.
public string SetStart(int startAt)
{
const string sentence = "this is a test so it is";
var words = sentence.Split(' ');
var x = (startAt > words.Count()) ? startAt%words.Count() : startAt;
return string.Join(" ", words.Skip(x).Concat(words.Take(x)));
}
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