能提供一个double类型的结合,提供一个分类个数 实现分组的函数
public List<Crowd> Compute(List<double> list, int count) 这种类型的函数
public static List<Crowd> Compute(List<double> list, int count) { var crowds = new List<Crowd>(count); list.Sort(); var step = list.Count() / (count * 2); for (var i = 0; i < count; i++) { crowds.Add(new Crowd()); crowds[i].Center = list[step + step*2*i]; } while (crowds.Sum(crowd => crowd.Change) > 0.01) { //Empty List and refresh Center crowds.ForEach( crowd => { if (!crowd.List.Any()) return; crowd.RefreshCenter(); crowd.List.Clear(); }); foreach (var num in list) { var index = 0; var minDistance = double.MaxValue; for (var i = 0; i < count; i++) { var distance = Math.Abs(crowds[i].Center - num); if (!(distance < minDistance)) continue; index = i; minDistance = distance; } crowds[index].List.Add(num); } } return crowds; } /// <summary> /// 集群 /// </summary> public class Crowd { public List<double> List { get; set; } public double Average { get { return List.Average(); } } public double Center { get; set; } public double Change { get; private set; } public Crowd() { Change = double.MaxValue; List = new List<double>(); } public void RefreshCenter() { Change = Math.Abs(Average - Center); Center = Average; } }