July 29, 2016
LINQ - blogs to read:
Notes:
1. Initialize an array
int[] a =
Enumerable.Repeat(-1,10).ToArray();
int[] b =
Enumerable.Range(0,10).ToArray();
int[] c =
Enumberable.Range(0,10).Select(i=>100+10*i).ToArray();
Enumerable.Repeat, Range,
no for loops
necessary, using LINQ
2. Iterate over multiple arrays in a single loop
foreach(var x in array1)
DoSomthing(x);
foreach(var x in array2)
DoSomething(x);
LINQ
foreach(var x in
array1.Concat(array2))
DoSomething(x);
LINQ operates at the enumerator level (?), it will not allocate a new array to hold elements of array1 and array2. So, space-efficient.
3. Generate a random sequence
Random rand = new Random();
var randomSeq =
Enumerable.Repeat(0,N).Select(i=>rand.Next());
lazy nature of LINQ, the sequence is not pre-computed and stored in an array, but instead random numbers are generated on-demand, as you
iterate over
randomSeq.
Generate a strign with the repeating pattern "ABCABCABC..." of length N.
string str = new string(Enumerable.Range(0,N).Select(i => (char)('A' + i%3)).ToArray());
string values = string.Join(string.Empty, Enumerable.Repeat(pattern, N).ToArray());
5. Convert sequences or collections
IEnumerable<string> strEnumerable = ...;
List<string> strList = ...;
var objList = strList.Cast<object>().ToList();
6. Convert a value to a sequence of length 1
IEnumerable<int> seq = Enumerable.Repeat(myValue, 1);
7. Iterate over all subsets of a sequence
For small input, three problems:
subset sum
NP-complete problems -
solve easily by iterating over all subsets of some sequence:
4. Generate a string
Generate a strign with the repeating pattern "ABCABCABC..." of length N.
string str = new string(Enumerable.Range(0,N).Select(i => (char)('A' + i%3)).ToArray());
string values = string.Join(string.Empty, Enumerable.Repeat(pattern, N).ToArray());
5. Convert sequences or collections
IEnumerable<string> strEnumerable = ...;
IEnumerable<object>
objEnumerable = strEnumerable.Cast<object>();
List<string> strList = ...;
List<object>
objList = new List<object>(strLsit.Cast<object>());
var objList = strList.Cast<object>().ToList();
6. Convert a value to a sequence of length 1
IEnumerable<int> seq = Enumerable.Repeat(myValue, 1);
7. Iterate over all subsets of a sequence
For small input, three problems:
subset sum
boolean
satisfiability
knapsack problem
NP-complete problems -
solve easily by iterating over all subsets of some sequence:
No comments:
Post a Comment