我正在尝试将一段简单的数学转换为Linq。
我想将几个数字的质因数捆绑到一个集合中。考虑以下整数。
8 = 2 * 2 * 2
12 = 2 * 2 * 3可以被8和12整除的最小数字是24,所以我希望结果组包含
{ 2, 2, 2, 3 }如果我使用Concat,结果是{2,2,2,2,3}-如果我使用Union,结果是{2,3} -不正确
是否有一个内置的Linq集合操作函数,可以识别它需要保持项目的最大出现次数(即,如果已经有足够的数量来满足,则不添加另一个;如果没有,则添加另一个)
发布于 2013-06-06 17:24:08
嗯,它不是任何现有的函数,因为我不认为存在这样的函数,但非常简单的代码能够处理这一点:
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();输出:2 2 2 3
发布于 2013-06-06 18:00:36
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;
}
}https://stackoverflow.com/questions/16957418
复制相似问题