更改数组中索引的值,将索引从旧索引向右移动,同时保留左侧所有索引

时间:2015-05-12 09:02:23

标签: c# arrays indexoutofboundsexception

我有一个数组,我有一个新值,我希望在索引中插入一个新的值,它将小于它左边的索引,并且大于右边的索引。我只关心10个索引,超出索引[9]的旧值将被销毁。

我尝试用这种方式完成它:

private double[] scores = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1};

public void newScore(double score){

    for (int i = 0; i < scores.Length; i++){

        if (score > this.scores[i]){
            Array.Copy(this.scores, i, this.scores, i + 1, this.scores.Length - i);
            this.scores[i] = score;
            break;
        }
    }
}

newScore(0.75);

//Desired result: {1.0, 0.9, 0.8, 0.75, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2};

我的目标是在0.8和0.7之间插入0.75,而所有小于0.75的值向右移动,score[9]的旧值消失。

我遇到了Array.Copy();方法的问题。有没有更好的方法来完成我想要做的事情,或者我犯了一个我找不到的简单错误?

我已经搜索了其他解决方案,但我找到的解决方案是将所有索引向右或向左移动,而不是仅将值小于插入的值。

3 个答案:

答案 0 :(得分:1)

this.scores.Length - i替换为this.scores.Length - i - 1

你的样本中有一个错误:0.10 = 0.1,分数很差。

原始得分数列为{ 1.0 ,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1}

答案 1 :(得分:1)

如果您不必拥有数组,我会将代码更改为:

    private List<double> scores = new List<double> { 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1 };

    public void newScore(double score) {
        scores.Add(score);
        scores = scores.OrderByDescending(o => o).Take(scores.Count - 1).ToList();
    }

答案 2 :(得分:0)

您的初始数组错误。第一个值应为1.0,而不是0.1。

我会这样解决。

public void newScore(double score)
{
    var result = new double[this.scores.Length + 1];
    for (int i = 0; i < this.scores.Length; i++)
    {
        if (score > scores[i])
        {
            Array.Copy(this.scores, 0, result, 0, i);
            Array.Copy(this.scores, i, result, i + 1, this.scores.Length - i);
            result[i] = score;
            break;
        }
    }

    scores = result;
}