How to access the string array elements for search? - c#

I have a text file that include of numbers and I save it in a string array.
one line of my text file is this:
2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21
every line save in one of indexes of string array.
now how can i access array elements as int type and search and calculate in all of array?
this is my array:
string [] lines = File.ReadAllLines(txtPath.Text);
for example I want to return indexes of array that include number'14' in all of array .

This is the easiest and clearest way to solve it. I commented so you can better understand what happens in the entire program.
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
int integerNumber;
// checking if the string lineElements[j] is a number (because there also this case 114:275:5)
if (int.TryParse(lineElements[j], out integerNumber))
{
// if it is we check if the number is 14, in that case we add that index to the indexes list
if (integerNumber == 14)
{
indexes.Add(j);
}
}
}
}
// Printing out lines and indexes:
foreach (int key in dict.Keys)
{
Console.WriteLine(string.Format("LINE KEY: {0}", key));
foreach (int index in dict[key])
{
Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
}
Console.WriteLine("------------------");
}
Console.ReadLine();
}
}
UPDATE 1:
As you requested:
special thanks for your clear answering.if i want to do search for all of my array elements what can i do? it means instead of only
number'14' i want to print indexes of all numbers that appear in
indexes
If you want to print all the indexes you should Console.WriteLine(j), that is the index of the inner for cycle, instead of checking the number value if (integerNumber == 14).
So, this is the program:
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
// printing all indexes of the current line
Console.WriteLine(string.Format("Element index: {0}", j));
}
}
Console.ReadLine();
}
}
UPDATE 2:
As you requested:
if i want to search my line till first " : " apper and then search next line, what can i do?
You need to break the for cycle when you are on the element with :
class Program
{
static void Main(string[] args)
{
// this is your array of strings (lines)
string[] lines = new string[1] {
"2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
};
// this dictionary contains the line index and the list of indexes containing number 14
// in that line
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
// iterating over lines array
for (int i = 0; i < lines.Length; i++)
{
// creating the list of indexes and the dictionary key
List<int> indexes = new List<int>();
dict.Add(i, indexes);
// splitting the line by space to get numbers
string[] lineElements = lines[i].Split(' ');
// iterating over line elements
for (int j = 0; j < lineElements.Length; j++)
{
// I'm saving the content of lineElements[j] as a string
string element = lineElements[j];
// I'm checking if the element saved as string contains the string ":"
if (element.Contains(":"))
{
// If it does, I'm breaking the cycle, and I'll continue with the next line
break;
}
int integerNumber;
// checking if the string lineElements[j] is a number (because there also this case 114:275:5)
if (int.TryParse(lineElements[j], out integerNumber))
{
// if it is we check if the number is 14, in that case we add that index to the indexes list
if (integerNumber == 14)
{
indexes.Add(j);
}
}
}
}
// Printing out lines and indexes:
foreach (int key in dict.Keys)
{
Console.WriteLine(string.Format("LINE KEY: {0}", key));
foreach (int index in dict[key])
{
Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
}
Console.WriteLine("------------------");
}
Console.ReadLine();
}
}
As you can see, if you run this piece of code and compare it with the first version, in output you'll get only the index of the first 14 occurrence, because the second one is after the string with :.

First you must get all conttent of file in the string array format:
public string[] readAllInFile(string filepath){
var lines = File.ReadAllLines(path);
var fileContent = string.Join(' ',lines);//join all lines of file content in one variable
return fileContent.Split(' ');//each word(in your case each number) in one index of array
}
and in usage time you can do like this:
var MyFileContent = readAllInFile(txtPath.Text);
int x= Convert.ToInt32(MyFileContent[2]);
IEnumerable<int> numbers = MyFileContent.Select(m=> int.Parse(m);)
var sumeOf = numbers.sum();
you can use linq to have more tools on collections.

var linesAsInts = lines.Select(x => x.Split(' ').Select(int.Parse));
var filteredLines = linesAsInts.Where(x => x.Contains(14));

// define value delimiters.
var splitChars = new char[] { ' ', ':' };
// read lines and parse into enumerable of enumerable of ints.
var lines = File.ReadAllLines(txtPath.Text)
.Select(x => x.Split(splitChars)
.Select(int.Parse));
// search in array.
var occurences = lines
.Select((line,lineIndex) => line
.Select((integer, integerIndex) => new { integer, integerIndex })
.Where(x => x.integer == 10)
.Select(x => x.integerIndex));
// calculate all of array.
var total = lines.Sum(line => line.Sum());

Related

Iterate a List<string> 12 by 12 and get the items

I have a generic list of strings, but I know from 12 to 12 items I have a Record. I Also have a Model that want to populate.
My primary code
for (int r = 2; r <= rows; r++)
{
for (int c = 3; c <= cols; c++)
{
try
{
list.Add(usedRange.Cells[r, c].Value2.ToString());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
foreach (string item in list)
{
}
So in foreach (string item in list) I know 12 the 24 then 36 my record is there
The problem is this peace of code
foreach (string item in list)
{
p.LastName = item
}
I need a for in order to populate my Model with all 12 items, I'm stuck
You can also get item each 12 elements with a for by index like this:
for (var i = 0; i < list.Count; i+=12)
var p.LastName = list[i];
If you want to have your list in chunks of 12 elements, you can use the Chunk Linq extension which is new in C# 10. An equivalent is available in the library MoreLinq if you don't use C# 10, it has a different name: Batch.
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Creating a list of chunks containing 12 elements
var ChunkedElements = MyList
.Chunk(12);
// Using the chunked list.
foreach (var chunk in ChunkedElements)
{
// Do what you want with the 12 elements
Console.WriteLine("New Chunk");
foreach(var e in chunk)
{
Console.WriteLine(e);
}
}
Output:
New Chunk
0
1
2
3
4
5
6
7
8
9
10
11
New Chunk
12
13
14
15
16
17
18
19
20
21
22
23
New Chunk
24
25
26
27
28
29
30
31
32
33
34
35
New Chunk
36
37
38
39
40
41
42
43
44
45
46
47
New Chunk
48
49
50
51
52
53
54
55
56
57
58
59
New Chunk
60
61
62
63
64
65
66
67
68
69
70
71
New Chunk
72
73
74
75
76
77
78
79
80
81
82
83
New Chunk
84
85
86
87
88
89
90
91
92
93
94
95
New Chunk
96
97
98
99
If you only want every 12th element, here is a Linq alternative to the classical for loops. It is not better or worst, but can be useful depending on the context.
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Filtering the list to get only the 12th elements
var FilteredElements = MyList
.Where((e, i) => i % 12 == 0);
// Using the filtered list
foreach (var e in FilteredElements)
{
// Here do what you want with each element.
Console.WriteLine(e);
}
Output:
0
12
24
36
48
60
72
84
96
Explanation:
.Where((e, i) => i % 12 == 0) is where the work is done. The linq extension method Where has an overload that takes as argument a Func<TSource, Int32, bool>. See the doc. The second parameter is the index of the element of the collection.
So .Where((e, i) => i % 12 == 0) keeps only the elements of the collection for which the index i is divisible by 12 (i % 12 == 0). Hence the result containing only multiples of 12.
For now is like this but I'll change it to a smother approach.
for (var i = 0; i < list.Count; i += 13)
{
p.Add(new Participants()
{
LastName = list[0+i],
FirstName = list[1 + i],
AddressType = list[2 + i],
Email = list[3 + i],
Company = list[4 + i],
Phone = list[5 + i],
Street = list[6 + i],
ZipCode = list[7 + i],
City = list[8 + i],
Country = list[9 + i],
Percent = list[10 + i],
Points = list[11 + i],
Passed = list[12 + i],
});
}

Split Array into 2D based on 2 parameters C#

I have a text file which I have split up into a string array based on new line.
string[] arr = s.Split('\n');
Now, I need to further categorize this into a 2-dimensional array wherein each column is a new "transaction".
So the text file basically contains info about bank transactions, an example being given below:
21......
22....
23.....
31....
32.....
31.....
32.....
21....
21.....
22....
The beginning of the numbers signify a new tx record which begins at a new line. I want to make it into a 2D array wherein each column is grouped as one tx beginning from 21 until it comes across the next 21 (so the record before it).
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].StartsWith("21"))
{
indices[i] = i;
}
}
I tried to write the code above to check for array element beginning with 21 and then storing the index but it ends up storing all the indices.
Any help will be appreciated!
What you'd need to do is
string[] arr = s.Split('\n');
List<List<string>> listOfLists = new List<List<string>>(); //dynamic multi-dimensional list
//list to hold the lines after the line with "21" and that line
List<string> newList = new List<string>();
listOfLists.Add(newList);
for(int i = 0; i < arr.Length; i++)
{
if(arr[i].StartsWith("21"))
{
if(newList.Count > 0)
{
newList = new List<string>(); //make a new list for a column
listOfLists.Add(newList); //add the list of lines (one column) to the main list
}
}
newList.Add(arr[i]); //add the line to a column
}
If I understand you right, you can try regular expressions (i.e. instead of splitting, extract transactions):
using System.Linq;
using System.Text.RegularExpressions;
...
string line = "21 A 22 B 23 C 31 D 32 E 31 F 32 G 21 H 21 I 22 J";
var result = Regex
.Matches(line, "21 .*?((?=21 )|$)")
.OfType<Match>()
.Select(match => match.Value)
.ToArray(); // <- let's materialize as na array
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
21 A 22 B 23 C 31 D 32 E 31 F 32 G
21 H
21 I 22 J

C# solution for number of ways to choose 2 numbers from different groups of numbers

The problem I'm trying to solve is like this.
I'm given N, telling me the range of numbers is 0, 1, ..., N-2, N-1.
I'm also given pairings, telling me that those number pairs are in the same "group".
Ex:
N=6, 0 and 1 are paired, 1 and 4 are paired, and 2 and 3 are paired, and I know that the remaining numbers are in their own groups.
Then I know the groupings are {0, 1, 4}, {2, 3}, {5}.
The number of ways to choose two numbers from different groups among these groups is 11 and that's the number I'm trying to solve for. These choices are:
{0,2},
{0,3},
{0,5},
{1,2},
{1,3},
{1,5},
{4,2},
{4,3},
{4,5},
{2,5},
{3,5}
Can someone help figure out where my logic is wrong? Because I'm failing larger test cases and passing smaller ones.
My code:
static int Combinations(int N, int K)
{
decimal result = 1;
for (int i = 1; i <= K; i++)
{
result *= N - (K - i);
result /= i;
}
return (int)result;
}
/// <summary>
/// Given a set of n numbers 0, 1, ..., n-1 and a list of pairs
/// of the numbers from the set where each pair (i,j) means that
/// number i and j are in the same group, find the number of ways
/// to choose 2 numbers that are not in the same group.
/// </summary>
static int PoliticallyCorrectPairs(int n, Tuple<int, int>[] pairs)
{
// Create a map that from each number to a number representing
// the group that it is in. For example, if n = 5 and
// pairs = { (0, 1), (2, 3), (0, 4) }, then the map will look
// like
// 0 -> 1
// 1 -> 1
// 2 -> 2
// 3 -> 2
// 4 -> 1
// indicating that 0,1,4 belong to one group and 2,3 to the other.
int[] gmap = new int[n];
int k = 1;
foreach(Tuple<int, int> pair in pairs)
{
int i = pair.Item1,
j = pair.Item2;
// If both i and j are already in groups, combine those into a
// single group if it isn't already.
if (gmap[i] != 0 && gmap[j] != 0)
{
if(gmap[i] != gmap[j])
{
for(int m = 0; m < n; ++m)
if(gmap[m] == gmap[j])
gmap[m] = gmap[i];
}
}
else if(gmap[j] != 0) // j is in a group and i isn't
gmap[i] = gmap[j]; // add i to j's group
else if(gmap[i] != 0) // i is in a group and j isn't
gmap[j] = gmap[i]; // add j to i's group
else
gmap[i] = gmap[j] = k++; // Put both in same new group.
}
// Those not assigned to a group each end up in a group alone.
for(int i = 0; i < gmap.Length; ++i)
if(gmap[i] == 0)
gmap[i] = k++;
// Get the group sizes as an array.
int[] gcnts = gmap.GroupBy(x => x).Select(g => g.Count()).ToArray();
// Total number of ways to choose pairs of numbers.
int totalCombinations = Combinations(n, 2);
// Number of pairs from previous count that are in the same group.
int impossibleCombinations = gmap.GroupBy(x => x)
.Select(g => g.Count())
.Where(count => count > 1)
.Sum(count => Combinations(count, 2));
return totalCombinations - impossibleCombinations;
}
For example, I am passing
[TestMethod]
public void Sample1()
{
int N = 5;
Tuple<int, int>[] pairs = new Tuple<int, int>[]
{
Tuple.Create(0, 1),
Tuple.Create(2, 3),
Tuple.Create(0, 4)
};
Assert.AreEqual(6, PoliticallyCorrectPairs(N, pairs));
}
but failing
[TestMethod]
public void TestCase2()
{
int N = 100;
Tuple<int, int>[] pairs =
#"0 11
2 4
2 95
3 48
4 85
4 95
5 67
5 83
5 42
6 76
9 31
9 22
9 55
10 61
10 38
11 96
11 41
12 60
12 69
14 80
14 99
14 46
15 42
15 75
16 87
16 71
18 99
18 44
19 26
19 59
19 60
20 89
21 69
22 96
22 60
23 88
24 73
27 29
30 32
31 62
32 71
33 43
33 47
35 51
35 75
37 89
37 95
38 83
39 53
41 84
42 76
44 85
45 47
46 65
47 49
47 94
50 55
51 99
53 99
56 78
66 99
71 78
73 98
76 88
78 97
80 90
83 95
85 92
88 99
88 94"
.Split('\n')
.Select(line =>
{
int[] twofer = line.Split(' ').Select(s => int.Parse(s)).ToArray();
return Tuple.Create(twofer[0], twofer[1]);
})
.ToArray();
Assert.AreEqual(3984, PoliticallyCorrectPairs(N, pairs));
}
Any idea where I'm going wrong?
The problem is in the combining part:
if(gmap[i] != gmap[j])
{
for(int m = 0; m < n; ++m)
if(gmap[m] == gmap[j]) // here
gmap[m] = gmap[i];
}
When m hits j, the gmap[j] is replaced with gmap[i], hence the rest of the elements are checked against gmap[i].
Simply put the replaced value into local variable:
if(gmap[i] != gmap[j])
{
int g = gmap[j];
for(int m = 0; m < n; ++m)
if(gmap[m] == g)
gmap[m] = gmap[i];
}

How to remove a duplicate number from an array?

Hi I'm working on this simple program that takes 5 numbers from user as long as the numbers are greater than 10 and less than 100. My goal is to remove duplicates numbers an ONLY show the NOT DUPLICATE numbers. Let's say if I enter 23 , 23, 40, 56 , 37 I should only output 40 , 56 , 37. Please help me on this. Thanks in advance. Here's my code:
static void Main(string[] args)
{
int[] arr = new int[5];
for (int i = 0; i < 5; i++)
{
Console.Write("\nPlease enter a number between 10 and 100: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number > 10 && number <= 100)
{
arr[i] = number;
}
else {
i--;
}
}
int[] arr2 = arr.Distinct().ToArray();
Console.WriteLine("\n");
for (int i = 0; i < arr2.Length; i++)
{
Console.WriteLine("you entered {0}", arr2[i]);
}
Console.ReadLine();
}
One way is to group the elements based on input number and filter groups whose count is 1
int[] arr2 = arr.GroupBy(e=>e)
.Where(e=>e.Count() ==1)
.Select(e=>e.Key).ToArray();
Demo
I think you are looking for this:
int[] arr2 = arr.GroupBy(x => x)
.Where(dup=>dup.Count()==1)
.Select(res=>res.Key)
.ToArray();
Input Array : 23 , 23, 40, 56 , 37
Output Array : 40 , 56 , 37
How it Works:
arr.GroupBy(x => x) => give a collection of {System.Linq.GroupedEnumerable<int,int,int>} where x.Key gives you the unique elements.
.Where(dup=>dup.Count()==1)=> Extracts the the KeyValuePairs that contains Values count exactly equal to 1
.Select(res=>res.Key) => will collects the Keys from the above result
In your case, perhaps a combination of LINQ methods would be needed:
int[] arr2;
int[] nodupe = arr2.GroupBy(x => x).Where(y => y.Count() < 2).Select(z => z.Key).ToArray();

Check if string contains a successive pair of numbers

I have one list. I want check if list[i] contains string "6 1". But this code thinks 6 13 24 31 35 contains "6 1". Its false.
6 13 24 31 35
1 2 3 6 1
stringCheck = "6 1";
List<string> list = new List<string>();
list.Add("6 13 24 31 35");
list.Add("1 2 3 6 1");
for (int i=0; i<list.Count; i++)
{
if (list[i].Contains(stringCheck)
{
// its return me two contains, but in list i have one
}
}
But this code thinks 6 13 24 31 35 contains "6 1". Its false. […]
List<string> list = new List<string>();
list.Add("6 13 24 31 35");
list.Add("1 2 3 6 1");
No, it's true because you are dealing with sequences of characters, not sequences of numbers here, so your numbers get treated as characters.
If you really are working with numbers, why not reflect that in the choice of data type chosen for your list?:
// using System.Linq;
var xss = new int[][]
{
new int[] { 6, 13, 24, 31, 35 },
new int[] { 1, 2, 3, 6, 1 }
};
foreach (int[] xs in xss)
{
if (xs.Where((_, i) => i < xs.Length - 1 && xs[i] == 6 && xs[i + 1] == 1).Any())
{
// list contains a 6, followed by a 1
}
}
or if you prefer a more procedural approach:
foreach (int[] xs in xss)
{
int i = Array.IndexOf(xs, 6);
if (i >= 0)
{
int j = Array.IndexOf(xs, 1, i);
if (i + 1 == j)
{
// list contains a 6, followed by a 1
}
}
}
See also:
Finding a subsequence in longer sequence
Find sequence in IEnumerable<T> using Linq

Categories

Resources