finding all possible sum of two arrays element - c#

I have two arrays and i am trying to get all possible sum of each element with other element of two array and index of each element
int[] width = new int[2] {10,20 };
int[] height = new int[2] {30,40 };
result should like this (value / indexes)
10 width0
10+20 width0+width1
10+30 width0+height0
10+40 width0+height1
10+20+30 width0+width1+height0
10+20+40 width0+width1+height1
10+20+30+40 width0+width1+height0+height1
And so for each element in two array
I tried using permutation but I get other output

It is more easy to get all combinations from one array than two arrays. And as we see, you need to store indices and array names along with the value of the elements in collections. So, in my opinion the best option is to combine these two arrays in one dictionary, where the key will be the value of the numbers and the value will be [ArrayName + Index of item] (f.e width0, height1 and so on....)
So, let's combine these arrays in one dictionary:
int[] width = new int[2] { 10, 20 };
int[] height = new int[2] { 30, 40 };
var widthDictionary = width.ToList().Select((number, index) => new { index, number })
.ToDictionary(key => key.number, value => string.Format("width{0}", value.index));
var heightDictionary = height.ToList().Select((number, index) => new { index, number })
.ToDictionary(key => key.number, value => string.Format("height{0}", value.index));
// And here is the final dictionary
var totalDictionary = widthDictionary.Union(heightDictionary);
Then add this method to your class: (source)
public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
Then send your dictionary as an argument to this method and project this collection as you want with the help of the Select() method:
var sumOfCombinations = GetPowerSet(totalDictionary.ToList())
.Where(x => x.Count() > 0)
.Select(x => new
{
Numbers = x.Select(pair => pair.Key).ToList(),
DisplayValues = x.Select(pair => pair.Value).ToList()
})
.ToList();
And at the end you can display expected result as this:
sumOfCombinations.ForEach(x =>
{
x.Numbers.ForEach(number => Console.Write("{0} ", number));
x.DisplayValues.ForEach(displayValue => Console.Write("{0} ", displayValue));
Console.WriteLine();
});
And, the result is:

This is a play off of #Farhad Jabiyev's answer.
Declares a class called IndexValuePair. and uses foreach on widthList and heightList. to populate the 'Index' property of item instance.
Note: Index is a string.
Class & Static Function
public class IndexValuePair
{
public string Index {get;set;}
public int Value {get;set;}
}
public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
Main (Console)
static void Main(string[] args)
{
int[] width = new int[2] { 10, 20 };
int[] height = new int[2] { 30, 40 };
var wholeList = width.Select(val => new IndexValuePair() { Index = "width", Value = val }).ToList();
var heightList = height.Select(val => new IndexValuePair() { Index = "height", Value = val }).ToList();
var iteration = 0;
wholeList.ForEach(ivp => { ivp.Index = ivp.Index + count; count = iteration + 1; });
iteration = 0;
heightList.ForEach(ipv => { ivp.Index = ivp.Index + count; count = iteration + 1; });
wholeList.AddRange(heightList);
var sumOfCombinations = GetPowerSet(wholeList).Where(x => x.Count() > 0)
.Select(x => new { Combination = x.ToList(), Sum = x.Sum(ivp => ivp.Value) }).ToList();
StringBuilder sb = new StringBuilder();
sumOfCombinations.ForEach(ivp =>
{
ivp.Combination.ForEach(pair => sb.Append(string.Format("{0} ", pair.Value)));
sb.Append(string.Format("= {0} = ", x.Sum));
ivp.Combination.ForEach(pair=> sb.Append(string.Format("{0} + ", pair.Index)));
sb.Length -= 3;
Console.WriteLine(sb);
sb.Clear();
});
var key = Console.ReadKey();
}

Related

Merge first list with second list based on standard deviation of second list C#

Given 2 datasets (which are both a sequence of standard deviations away from a number, we are looking for the overlapping sections):
var list1 = new decimal[] { 357.06, 366.88, 376.70, 386.52, 406.15 };
var list2 = new decimal[] { 370.51, 375.62, 380.72, 385.82, 390.93 };
I would like to perform a merge with items from List2 being placed closest to items of List1, within a certain range, i.e. merge List2 element within 5.10 (standard deviation) of List1 element:
357.06
366.88 => 370.51
376.70 => 375.52, 380.72
386.52 => 390.93
406.15
The idea is to cluster values from List2 and count them, in this case element with value 376.70 would have the highest significance as it has 2 close neighbors of 375.52 and 380.72 (where as 366.88 and 386.52 have only 1 match, and the remaining none within range).
Which C# math/stats libraries could be used for this (or would there be a better way to combine statistically)?
If this is more of a computer science or stats question apologies in advance will close and reopen on relevant SO site.
Assuming that list2 is sorted (if not, put Array.Sort(list2);) you can try Binary Search:
Given:
var list1 = new decimal[] { 357.06m, 366.88m, 376.70m, 386.52m, 406.15m };
var list2 = new decimal[] { 370.51m, 375.62m, 380.72m, 385.82m, 390.93m };
decimal sd = 5.10m;
Code:
// Array.Sort(list2); // Uncomment, if list2 is not sorted
List<(decimal value, decimal[] list)> result = new List<(decimal value, decimal[] list)>();
foreach (decimal value in list1) {
int leftIndex = Array.BinarySearch<decimal>(list2, value - sd);
if (leftIndex < 0)
leftIndex = -leftIndex - 1;
else // edge case
for (; leftIndex >= 1 && list1[leftIndex - 1] == value - sd; --leftIndex) ;
int rightIndex = Array.BinarySearch<decimal>(list2, value + sd);
if (rightIndex < 0)
rightIndex = -rightIndex - 1;
else // edge case
for (; rightIndex < list1.Length - 1 && list1[rightIndex + 1] == value + sd; ++rightIndex) ;
result.Add((value, list2.Skip(leftIndex).Take(rightIndex - leftIndex).ToArray()));
}
Let's have a look:
string report = string.Join(Environment.NewLine, result
.Select(item => $"{item.value} => [{string.Join(", ", item.list)}]"));
Console.Write(report);
Outcome:
357.06 => []
366.88 => [370.51]
376.70 => [375.62, 380.72]
386.52 => [385.82, 390.93]
406.15 => []
Something like this should work
var list1 = new double[] { 357.06, 366.88, 376.70, 386.52, 406.15 };
var list2 = new double[] { 370.51, 375.62, 380.72, 385.82, 390.93 };
double dev = 5.1;
var result = new Dictionary<double, List<double>>();
foreach (var l in list2) {
var diffs = list1.Select(r => new { diff = Math.Abs(r - l), r })
.Where(d => d.diff <= dev)
.MinBy(r => r.diff)
.FirstOrDefault();
if (diffs == null) {
continue;
}
List<double> list;
if (! result.TryGetValue(diffs.r, out list)) {
list = new List<double>();
result.Add(diffs.r, list);
}
list.Add(l);
}
It uses MinBy from MoreLinq, but it is easy to modify to work without it.
In fact, you don't need extra libs or something else. You can use just LINQ for this.
internal class Program
{
private static void Main(string[] args)
{
var deviation = 5.1M;
var list1 = new decimal[] { 357.06M, 366.88M, 376.70M, 386.52M, 406.15M };
var list2 = new decimal[] { 370.51M, 375.62M, 380.72M, 385.82M, 390.93M };
var result = GetDistribution(list1.ToList(), list2.ToList(), deviation);
result.ForEach(x => Console.WriteLine($"{x.BaseValue} => {string.Join(", ", x.Destribution)} [{x.Weight}]"));
Console.ReadLine();
}
private static List<Distribution> GetDistribution(List<decimal> baseList, List<decimal> distrebutedList, decimal deviation)
{
return baseList.Select(x =>
new Distribution
{
BaseValue = x,
Destribution = distrebutedList.Where(y => x - deviation < y && y < x + deviation).ToList()
}).ToList();
}
}
internal class Distribution
{
public decimal BaseValue { get; set; }
public List<decimal> Destribution { get; set; }
public int Weight => Destribution.Count;
}
I hope it was useful for you.

What should i do to get a valid test result (string[]) instead of an WhereEnumerableIterator<string>[] for a method using Linq?

The problem is this:
with given integers a and b, return all the possible combinations in the form
±1±2±3±...±a = b
this is my method for it
public static IEnumerable<string> AllCombinationsWithAAndSumOfB(int a, int b)
{
List<string> list= new List<string>();
Func<string, List<string>> newList = y =>
{
var list = new string[2];
list[0] = y + "+";
list[1] = y + "-";
return list.ToList();
};
Func<int, List<string>> AddingToTheLists = x =>
{
list = list.SelectMany(y => newList(y)).ToList();
return list;
};
Func<char, string, int> CharToInt = (x, g) =>
{
return x == '-' ? -(g.IndexOf(x) + 1) : g.IndexOf(x) + 1;
};
return Enumerable.Range(1, a).SelectMany(AddingToTheLists).Where(x => x.Length == a && x.Sum(y => CharToInt(y, x)) <= b);
}
Now, i'm trying to run a test. This is the test.
[Fact]
public void AllCombinationsWithAAndSumOfBWork()
{
string[] list= { "++-", "+-+", "-+-", "--+", "---" };
var result = AllCombinationsWithAAndSumOfB(3, 0);
Assert.Equal(list, result);
}
The problem is the result of the test:
Result Message:
Assert.Equal() Failure
Expected: String[] ["++-", "+-+", "-+-", "--+", "---"]
Actual: WhereEnumerableIterator<String> []
What should i do to stop getting the result WhereEnumerableIterator [] ?
I'm thinking you want all possible combinations of additions and subtractions for a by-one sequentially increasing ordered list, that is of a length, of integers that sum up to b.
For example: If a = 3, and b = 0, then all combinations of additions and subtractions of each of the integers in the following ordered list: 1, 2, 3 should sum to 0.
If so, then the algorithm can be as follows:
public static IEnumerable<string> AllCombinationsWithAAndSumOfB(int a, int b)
{
var numbers = Enumerable.Range(1, a);
var signCombos = Enumerable
.Range(0, Convert.ToInt32("".PadLeft(a, '1'), 2) + 1)
.Select(e => Convert.ToString(e, 2).PadLeft(a, '0').Replace('0', '-').Replace('1', '+'));
var calc = new DataTable();
return signCombos.Select(
signCombo => new
{
signCombo = signCombo,
formula = String.Join("", signCombo.ToCharArray().Zip(numbers, (s, n) => $"{s}{n}"))
})
.Where(si => ((int)calc.Compute(si.formula, null)) == b)
.Select(si => si.signCombo);
}
This returns
--+
++-
Because:
-1 -2 +3 = 0
+1 +2 -3 = 0

How to convert a multi-dimensional array to a dictionary?

I have a n-by-3 array I wish to convert to a Dictionary<string,string[]> where the first column is the key and the rest of the column as an array for the value.
For example:
Key = arr[0,0], Value = new string[2] {arr[0,1], arr[0,2]}.
I'm aware of ToDictionary but I don't know how to set the value part.
arr.ToDictionary(x=>arr[x,0],x=>new string[2]{arr[x,1],arr[x,2]});
//This doesn't work!!!
How can I set it up correctly?
Multidimensional arrays are a continuous block of memory, so you kind of have to treat them like a single array. Try this:
var dict = arr.Cast<string>()
.Select((s, i) => new { s, i })
.GroupBy(s => s.i / arr.GetLength(1))
.ToDictionary(
g => g.First().s,
g => g.Skip(1).Select(i => i.s).ToArray()
);
With explanations:
// First, cast it to an IEnumerable<string>
var dict = arr.Cast<string>()
// Use the Select overload that lets us get the index of the element,
// And we capture the element's index (i), along with the element itself (s)
// and put them together into an anonymous type [1]
.Select((s, i) => new { s, i })
// .GetLength(dimension) is a method on multidimensional arrays to
// get the length of a given dimension (pretty self-explanatory)
// In this case, we want the second dimension, or how wide each
// row is: [x,y] <- we want y
// Divide the element index (s.i) by that length to get the row index
// for that element
.GroupBy(s => s.i / arr.GetLength(1))
// Now we have an Grouping<int, IEnumerable<anonymous{string,int}>>
.ToDictionary(
// We don't care about the key, since it's the row index, what we want
// is the string value (the `s` property) from first element in the row
g => g.First().s,
// For the value, we want to skip the first element, and extract
// the string values (the `s` property), and then convert to an array
g => g.Skip(1).Select(i => i.s).ToArray()
);
[1]: See here for documentation on anonymous types.
Sometimes not using linq is easier to read and faster:
var dict = new Dictionary<string, string[]>();
for (int i = 0; i < arr.GetLength(0); i++)
dict[arr[i, 0]] = new string[] { arr[i, 1], arr[i, 2] };
But when you feel like you REALLY need to use linq:
Enumerable.Range(0, arr.GetLength(0))
.ToDictionary(i => arr[i, 0], i => new string[] {arr[i, 1], arr[i, 2]});
This is the simplest approach I can come up with:
var arr = new int[4, 3]
{
{ 1, 2, 3 },
{ 3, 5, 7 },
{ 5, 8, 11 },
{ 7, 11, 15 },
};
var dict = arr.Cast<int>().Buffer(3).ToDictionary(x => x[0], x => x.Skip(1).ToArray());
That gives me:
You just need to NuGet "System.Interactive" to get the Buffer operator.
Or use this implementation:
public static IEnumerable<T[]> Buffer<T>(this IEnumerable<T> source, int count)
=>
source
.Select((t, i) => new { t, i })
.GroupBy(x => x.i / count)
.Select(x => x.Select(y => y.t).ToArray());
I guess your approach was right ,my only doubt is that your array is static or not?
arr.Select((value, index) => new { value, index }) .ToDictionary(x => x.index, x => new string[2]{x.value[x.index][1],x.value[x.index][2]}));
Note: I couldn't execute and check the code ! Sorry.
I had done using Integer. Please Change for your requirements.
public static void Main()
{
int row=0 , col=0;
int[,] array = new int[,]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
int flag=0;
for (int i = 0; i < array.Rank; i++)
{
if(flag==0)
{
row= array.GetLength(i);
flag=1;
}
else
{
col= array.GetLength(i);
}
}
Dictionary<int,int[,]> dictionary = new Dictionary<int, int[,]>();
for(int i=0;i<row;i++)
{
dictionary.Add(array[i,0],new int[, ]{{array[i,1]},{array[i,2]}});
}
Console.WriteLine(dictionary[4].GetValue(0,0));
}

Remove the repeating items and return the order number

I want to remove the repeating items of a list.I can realize it whit Distinct() easily.But i also need to get the order number of the items which have been removed.I can't find any function in linq to solve the problem and finally realize it with the following code:
public List<string> Repeat(List<string> str)
{
var Dlist = str.Distinct();
List<string> repeat = new List<string>();
foreach (string aa in Dlist)
{
int num = 0;
string re = "";
for (int i = 1; i <= str.LongCount(); i++)
{
if (aa == str[i - 1])
{
num = num + 1;
re = re + " - " + i;
}
}
if (num > 1)
{
repeat.Add(re.Substring(3));
}
}
return repeat;
}
Is there any other way to solve the problem more simple? Or is there any function in linq I missed?Any advice will be appreciated.
This query does exactly the same as your function, if I'm not mistaken:
var repeated = str.GroupBy(s => s).Where(group => group.Any())
.Select(group =>
{
var indices = Enumerable.Range(1, str.Count).Where(i => str[i-1] == group.Key).ToList();
return string.Join(" - ", group.Select((s, i) => indices[i]));
});
It firstly groups the items of the original list, so that every item with the same content is in a group. Then it searches for all indices of the items in the group in the original list, so that we have all the indices of the original items of the group. Then it joins the indices to a string, so that the resulting format is similiar to the one you requested. You could also transform this statement lambda to an anonymous lambda:
var repeated = str.GroupBy(s => s).Where(group => group.Any())
.Select(group => string.Join(" - ",
group.Select((s, i) =>
Enumerable.Range(1, str.Count).Where(i2 => str[i2 - 1] == group.Key).ToList()[i])));
However, this significantly reduces performance.
I tested this with the following code:
public static void Main()
{
var str = new List<string>
{
"bla",
"bla",
"baum",
"baum",
"nudel",
"baum",
};
var copy = new List<string>(str);
var repeated = str.GroupBy(s => s).Where(group => group.Any())
.Select(group => string.Join(" - ",
group.Select((s, i) =>
Enumerable.Range(1, str.Count).Where(i2 => str[i2 - 1] == group.Key).ToList()[i])));
var repeated2 = Repeat(str);
var repeated3 = str.GroupBy(s => s).Where(group => group.Any())
.Select(group =>
{
var indices = Enumerable.Range(1, str.Count).Where(i => str[i-1] == group.Key).ToList();
return string.Join(" - ", group.Select((s, i) => indices[i]));
});
Console.WriteLine(string.Join("\n", repeated) + "\n");
Console.WriteLine(string.Join("\n", repeated2) + "\n");
Console.WriteLine(string.Join("\n", repeated3));
Console.ReadLine();
}
public static List<string> Repeat(List<string> str)
{
var distinctItems = str.Distinct();
var repeat = new List<string>();
foreach (var item in distinctItems)
{
var added = false;
var reItem = "";
for (var index = 0; index < str.LongCount(); index++)
{
if (item != str[index])
continue;
added = true;
reItem += " - " + (index + 1);
}
if (added)
repeat.Add(reItem.Substring(3));
}
return repeat;
}
Which has the followin output:
1 - 2
3 - 4 - 6
5
1 - 2
3 - 4 - 6
5
1 - 2
3 - 4 - 6
5
Inside your repeat method you can use following way to get repeated items
var repeated = str.GroupBy(s=>s)
.Where(grp=>grp.Count()>1)
.Select(y=>y.Key)
.ToList();

Linq Union/UnionAll/Concat

I'm trying to convert a simple piece of Math to Linq.
I want to bundle together the prime factors for several numbers into one collection.
Consider the following integers.
8 = 2 * 2 * 2
12 = 2 * 2 * 3
The smallest number divisible by both 8 & 12 is 24, so I'd like the resultant group to contain
{ 2, 2, 2, 3 }
If I use Concat the result is {2,2,2,2,2,3} - not correct
If I use Union the result is {2,3} - not correct
Is there a built in Linq Set Manipulation function which will recognise that it needs to keep the maximum number of occurences of an item (i.e. not add another if there are already enough there to satisfy if & add another if there aren't)
Well, it's not any existing function, as I don't think such exists, but pretty simple code is capable of handling this:
var listA = new List<int> {2, 2, 2};
var listB = new List<int> {2, 2, 3};
var grouppedA = listA.GroupBy(i => i).Select(g => new { key = g.Key, count = g.Count()});
var grouppedB = listB.GroupBy(i => i).Select(g => new { key = g.Key, count = g.Count()});
var result = grouppedA
.Union(grouppedB)
.GroupBy(g => g.key)
.SelectMany(g => Enumerable.Repeat(g.Key, g.Max(h => h.count)));
foreach (int i in result)
{
Console.Write(i + " ");
}
Console.ReadKey();
Output:
2 2 2 3
using System;
using System.Collections.Generic;
public class Sample {
public static void Main(String[] args) {
var n8 = toFactors(8);
var n12 = toFactors(12);
var uf = unionFactors(n8, n12);//LCM
printFactors(uf);
}
public static void printFactors(Dictionary<long, int> factors){
Console.Write("{ ");
foreach(var factor in factors.Keys){
for(int i=0;i<factors[factor];++i)
Console.Write( factor + " ");
}
Console.WriteLine("}");
}
public static Dictionary<long, int> unionFactors(Dictionary<long, int> af, Dictionary<long, int> bf){
Dictionary<long, int> uf = new Dictionary<long, int>();
foreach(var kv in af){
uf.Add(kv.Key, kv.Value);//copy
}
foreach(var kv in bf){
if(uf.ContainsKey(kv.Key)){
if(kv.Value > uf[kv.Key])//max
uf[kv.Key] = kv.Value;
} else {
uf.Add(kv.Key, kv.Value);
}
}
return uf;
}
public static Dictionary<long, int> toFactors(long num){
var factors = new Dictionary<long, int>();
long n = num, i = 2, sqi = 4;
while(sqi <= n){
while(n % i == 0){
n /= i;
if(factors.ContainsKey(i)){
factors[i] += 1;
} else {
factors.Add(i, 1);
}
}
sqi += 2 * (i++) + 1;
}
if(n != 1 && n != num){
if(factors.ContainsKey(i)){
factors[i] += 1;
} else {
factors.Add(i, 1);
}
}
if(factors.Count == 0)
factors.Add(num, 1);//prime
return factors;
}
}

Categories