# 求问同色球不相临的排序算法

0

```            var balls = new List<ball>()
{
new ball() {Id=1,color="red" },
new ball() {Id=2,color="red" },
new ball() {Id=3,color="red" },
new ball() {Id=4,color="green" },
new ball() {Id=5,color="green" },
new ball() {Id=6,color="green" },
new ball() {Id=7,color="black" },
new ball() {Id=8,color="black" },
new ball() {Id=9,color="black" }
};

//怎么样将balls排序成result？？
var result = new List<ball>()
{
new ball() {Id=1,color="red" },
new ball() {Id=4,color="green" },
new ball() {Id=7,color="black" },
new ball() {Id=2,color="red" },
new ball() {Id=5,color="green" },
new ball() {Id=8,color="black" },
new ball() {Id=3,color="red" },
new ball() {Id=6,color="green" },
new ball() {Id=9,color="black" },
};```

0

```            var r = (from b in balls
where b.color == "red"
orderby b.Id
select b).ToList() ;
var g = (from b in balls
where b.color == "green"
orderby b.Id
select b).ToList() ;
var k = (from b in balls
where b.color == "black"
orderby b.Id
select b).ToList() ;
List<ball> result = new List<ball>();
for (int i = 0; i < r.Count; i++)
{
result.Add(r[i]);
result.Add(g[i]);
result.Add(k[i]);
}```

plcly | 园豆：206 (菜鸟二级) | 2016-05-25 09:25

@丶飘零丶:

```var balls = new List<ball>()
{
new ball() {Id=1,color="red" },
new ball() {Id=2,color="red" },
new ball() {Id=3,color="red" },
new ball() {Id=4,color="green" },
new ball() {Id=5,color="green" },
new ball() {Id=6,color="green" },
//new ball() {Id=7,color="black" },
//new ball() {Id=8,color="black" },
new ball() {Id=9,color="black" }
};
var c = (from b in balls group b.color by b.color into g select g.Key).ToList();
List<List<ball>> colorList = new List<List<ball>>();
foreach (var cc in c)
{
colorList.Add((from b in balls where b.color == cc.ToString() select b).ToList());
}
int maxLength = 0;
foreach (var n in colorList)
{
if (n.Count > maxLength)
{
maxLength = n.Count;
}
}
List<ball> result = new List<ball>();
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < c.Count; j++)
{
if (i < colorList[j].Count)
{
result.Add(colorList[j][i]);
}
}
}```

@plcly: 这个依然不能解决当同一色的太多的时候尾数的问题。

@丶飘零丶: 这个我已经去掉了最后两个排序了，结果是1492536，你需要的结果是什么，不如你提供一个复杂的，用这段程序试一下，哪里不一样

@plcly:

```            var balls = new List<Ball>()
{
new Ball() {Id=1,color="red" },
new Ball() {Id=2,color="red" },
new Ball() {Id=3,color="red" },
new Ball() {Id=3,color="red" },
new Ball() {Id=3,color="red" },
new Ball() {Id=3,color="red" },
new Ball() {Id=3,color="red" },
new Ball() {Id=4,color="black" },
new Ball() {Id=5,color="black" },
new Ball() {Id=6,color="black" },
new Ball() {Id=7,color="green" },
new Ball() {Id=8,color="green" },
new Ball() {Id=9,color="green" }
};```
View Code

0

int ballsIndex=0;

for(int i=0;i<colorCount;i++)

{

for(int j = i;j<balls.Count;j+= colorCount)

{

result[j]=balls[ballsIndex];

ballsIndex++;

}

}

您需要登录以后才能回答，未注册用户请先注册