Didn't quite know what to title this question so please feel free to edit.
I have a list of strings where all elements are strings with a length of 40.
What I want to do is split the list elements at character 20 and push the last part of the now divided string to the next element in the list, appending all other elements in the list.
E.g.
list[0] = 0011
list[1] = 2233
list[2] = 4455
^split here
// new list results in:
list[0] = 00
list[1] = 11
list[3] = 22
list[4] = 33
list[5] = 44
list[6] = 55
How can this be achieved?
list = list.SelectMany(s => new [] { s.Substring(0, 20), s.Substring(20, 20) })
.ToList();
list = list.SelectMany(x=>new[]{x.Substring(0, 20), x.Substring(20)}).ToList();
Not sure why you want to do that, but it's quite simple with linq:
List<string> split = list.SelectMany(s => new []{s.Substring(0, 2), s.Substring(2)}).ToList();
If you must work with the existing array:
const int elementCount = 3;
const int indexToSplit = 2;
string[] list = new string[elementCount * 2] { "0011", "0022", "0033", null, null, null };
for (int i = elementCount; i > 0; --i)
{
var str = list[i-1];
var left = str.Substring( 0, indexToSplit );
var right = str.Substring( indexToSplit, str.Length - indexToSplit );
var rightIndex = i * 2 - 1;
list[rightIndex] = right;
list[rightIndex - 1] = left;
}
foreach( var str in list )
{
Console.WriteLine( str );
}
Related
Is it possible to iterate nested if statements with a new value with every single iteration? I am trying to build a 1-dimensional cellular automata (for homework, I cannot deny it) and I'm completely new to C# as the following code will no doubt assure. I have tried to create this program using the most straightforward, basic, DIY methods available and have run myself into a rut.
I've got a string of 1's and 0's of length 8, say
string y;
y = "11110000";
I want to break this set up in 8 substring sets of 3 with each set comprising of a value in y together with a single value on either side of it. So counting from 0, the 3rd set would be 110, the 7th would be 001. However substrings will only provide the 1st to 6th set as I can't loop them around y to my liking so I defined the following-
y1=y.Substring(7,1)+y+y.Substring(0,1);
Using y1 I was able to get out all the substrings necessary. These were defined pretty basically as follows-
string a0, a1, a2, a3, a4, a5, a6, a7;
a0 = y1.Substring(0, 3);
a1 = y1.Substring(1, 3);
a2 = y1.Substring(2, 3);
a3 = y1.Substring(3, 3);
a4 = y1.Substring(4, 3);
a5 = y1.Substring(5, 3);
a6 = y1.Substring(6, 3);
a7 = y1.Substring(7, 3);
The rules for the next generation of cellular automata are up to the user in this program- that is to say the user can choose whether or not a substring, say 111->0 or 1 for all iterations. I used (an awful lot of) if tables in the following way for each substring
{
if (a0=="000")
{
Console.Write(a);
}
else if (a0=="001")
{
Console.Write(b);
}
else if (a0 =="010")
{
Console.Write(c);
}
else if (a0 == "011")
{
Console.Write(d);
}
else if (a0 == "100")
{
Console.Write(e);
}
else if (a0 == "101")
{
Console.Write(f);
}
else if (a0 == "110")
{
Console.Write(g);
}
else if (a0 == "111")
{
Console.Write(h);
}
}
where a,b,c,d,e,f,g,h are ints and are rules chosen by the user. So say for instance the user decides that each set 000 should result in a 1 value, then a=1. b corresponds to {0,0,1}, c to {0,1,0} and so on. However the fairly obvious problem with this method is that I end up with only 1 generation in ints that I can't get at. I'd love to replace y1 with this new generation (converted into a string). If this isn't possible let me know!
This link might also clear things up a bit
and here's how you COULD have gotten an A+ :D
private static int[,] HipPriestsHomework()
{
string y = "11110000";
Console.WriteLine(y);
var rules = new[]
{
new {pattern = 0, result = 0},
new {pattern = 1, result = 1},
new {pattern = 2, result = 1},
new {pattern = 3, result = 1},
new {pattern = 4, result = 1},
new {pattern = 5, result = 0},
new {pattern = 6, result = 0},
new {pattern = 7, result = 0},
};
Dictionary<int, int> rulesLookup = new Dictionary<int, int>();
foreach(var rule in rules)
{
rulesLookup.Add(rule.pattern, rule.result);
}
int numGenerations = 10;
int inputSize = y.Length;
int[,] output = new int[numGenerations, inputSize];
int[] items = new int[y.Length];
for(int inputIndex = 0; inputIndex< y.Length; inputIndex++)
{
string token = y.Substring(inputIndex, 1);
int item = Convert.ToInt32(token);
items[inputIndex] = item;
}
int[] working = new int[items.Length];
items.CopyTo(working, 0);
for (int generation = 0; generation < numGenerations; generation++)
{
for (uint y_scan = 0; y_scan < items.Length; y_scan++)
{
int a = items[(y_scan - 1) % items.Length];
int b = items[y_scan % items.Length];
int c = items[(y_scan + 1) % items.Length];
int pattern = a << 2 | b << 1 | c;
var match = rules[pattern];
output[generation, y_scan] = match.result;
working[y_scan] = match.result;
Console.Write(match.result);
}
working.CopyTo(items, 0);
Console.WriteLine();
}
return output;
}
I have a list of numbers as below:
var mylist = new List<double> {1, 5, 8, 10, 12};
How can I get the number after a specific number. I want an LINQ expression that receives for example 8 and gives me 10;
You can use the following:
double result = mylist.SkipWhile(n => n != 8).Skip(1).First();
This should also work if you do not have duplicate numbers.
int index = mylist.IndexOf(8);
if (index != -1)
{
double result = index == mylist.Count - 1 ? mylist[index] : mylist[index + 1];
}
This should work,
var mylist = new List<double> { 1, 5, 8, 10, 12 };
double p = 8;
var result = mylist.Where(x => x > p).Take(1).SingleOrDefault();
how i find elements contains a value.
List<int> primes = new List<int>(new int[] { 19, 23,2, 29,23 });
int index = primes.IndexOf(2);
label1.Text = index.ToString();
for (int i = index+1; i < primes.Count; )
{
index = primes.IndexOf(2, i );
label1.Text += "-" + index.ToString();
i = index+1;
}
Output:
1-2-3-4
Something like this?
List<int> primes = new List<int>(new int[] { 19, 23, 2, 29, 23 });
label1.Text = String.Join("-", primes.Select((i, inx) => new { i, inx })
.Where(x => x.i.ToString().Contains("2"))
.Select(x => x.inx));
Label's text will be 1-2-3-4
List<int> primes = new List<int>(new int[] { 19, 23,2, 29,23 });
for (int i = 0; i < primes.Count; i++)
{
if (primes[i].ToString().Contains("2"))
label1.Text = label1.Text += "-" + i;
}
label1.Text = label1.Text.Substring(1, label1.Text.Length - 1); // this line just removes the dath at the start of the label1.Text
this code should do the job but the label1.Text will be 1-2-3-4 cause 2nd 3rt 4th and 5th elements have 2 inside of it or are equal to two
to check list for values
primes.Contains(2)
to know indexes for each element can do
var foo = primes.Select((x, i) => new { x, i }).ToLookup(x => x.x, x => x.i);
this will group elements and their respective indexes
I'll keep this simple. My dataset is as follows:
Array 1:
James
Bob
Jim
Array 2:
0
1
2
I want to create a new array by joining the two arrays so they produce something like the following:
James 0
James 1
James 2
Bob 0
Bob 1
Bob 2
Jim 0
Jim 1
Jim 2
How can it be done in C#. I've came into this problem before, I remember using extension methods but I have no idea what area of Set Theory this falls under.
You're looking for a cross product:
from a in a1
from b in a2
select new { a, b }
You would use a cross join (Cartesian product):
var result = from x in array1
from y in array2
select string.Format("{0} {1}", x, y);
See it live: http://ideone.com/1TdKGy
You need Cartesian Join or Cross Join. One more way to do it using SelectMany:
var arr1 = new string [] {"James","Bob","Jim"};
var arr2 = new int [] { 1, 2, 3};
var query = arr1.SelectMany(x => arr2, (x, y) => new { x, y });
foreach(var item in query)
{
Console.WriteLine(item);
}
This is another way to go:
string[] names = { "James", "Bob", "Jim" };
int[] numbers = { 0, 1, 2 };
string[] result = new string[names.Length * 3];
for (int i = 0, y = 0 ; i < result.Length; i+=3,y++)
{
result[i] = names[y] + numbers[0].ToString();
result[i + 1] = names[y] + numbers[1].ToString();
result[i + 2] = names[y] + numbers[2].ToString();
}
I have a list of lists that I have created from a "tab" delimited string. Instead of a 2d array i use list of lists as I dont know the size to create the array.
It will be something like,
0 0
16.0000 0
15.0000 15.0000
0 15.0000
2.7217 5.6904
3.7217 5.6904
I now want to find the maximum and minimum from each of the columns.
So if you take the above example,
maximum would be : 16.0000 15.0000
and minimum would be : 0 0
for (int i = 0; i < size[0]; i++)
{
// Create size[0] x size[1] array
obstVertex.Add(new List<double>());
for (int y = 0; y < size[1]; y++)
{
obstVertex[i].Add(Convert.ToDouble(split[i+(y*size[0])]));
}
}
How can I find the maximum or the minimum value using linq ???
Thanks in advance
List<List<double>> myList;
myList.Add(new List(new double[] { 0, 16, 15, 0, 2.7217, 3.7217 }));
myList.Add(new List(new double[] { 0, 0, 15, 15, 5.6904, 5.6904 }));
List<double> maxList = myList.Select(l => l.Max()).ToList();
List<double> minList = myList.Select(l => l.Min()).ToList();
Try the following:
class Program
{
static void Main(string[] args)
{
var l = new List<List<double>>() {new List<Double>() {0, 16.0000, 15.0000, 0, 2.7217, 3.7217},
new List<Double>() {0, 0, 15.0000, 15.0000, 5.6904, 5.6904}};
int i = 1;
var result = from sublist in l
select new { min = sublist.Min(), max = sublist.Max(), index = i++ };
foreach (var r in result)
Console.WriteLine(String.Format("Index: {0} Min: {1} Max: {2}",r.index, r.min, r.max));
Console.ReadKey();
}
}
It will get the min- and max-value for each sub-list in the list of lists.
I assume obstVertex is declared like this:
List<List<double>> obstVertex;
Then you can do this
var minima = Enumerable.Range(0, obstVertex[0].Count - 1)
.Select (colIndex => obstVertex.Select(row => row[colIndex]).Min())
to get all the minimum values of each column.
static void Main(string[] args)
{
List<List<double>> lists = new List<List<double>>() {
new List<double>(){0 , 0 } ,
new List<double>(){16.0000 , 0 } ,
new List<double>(){16.0000 , 15.0000 } ,
new List<double>(){0 , 15.0000 } ,
new List<double>(){2.7217 , 5.6904 } ,
new List<double>(){3.7217 , 5.6904 }
};
var r = new {
col1_max = (from x in lists select x[0]).Max(),
col1_min = (from x in lists select x[0]).Min(),
col2_max = (from x in lists select x[1]).Max(),
col2_min = (from x in lists select x[1]).Min(),
};
Console.WriteLine(string.Format("col1_max = {0}\r\ncol1_min = {1}\r\ncol2_max = {2}\r\ncol3_max = {3}", r.col1_max , r.col1_min , r.col2_max , r.col2_min));
Console.Read();
}