2017-04-16 57 views
1

我想找到這個元素的最接近值之間的範圍。 元素之間的增量值。這將是正數,因爲它的模數。如何找到數組中每個元素的最近值?

class Element { 


double DeltaValue; 


double ElementValue; 


public Element(double n) { 

ElementValue = n; 

} 

static void Main() { 


list<Element> ListElements = new list<Elements>; 


ListElements.Add(3); 

ListElements.Add(10); 

ListElements.Add(43); 

ListElements.Add(100); 

ListElements.Add(30); 

ListElements.Add(140); 

for(int i = 0; i < ListElements.Count; i++) { 

ListElements[i].DeltaValue = //and problem is here 


//example as for ListElements[2].DeltaValue will be 13; because 43-30=13; 

} 

//示例如ListElements [2] .DeltaValue將爲13;因爲43-30 = 13;

+1

你有沒有想過對數組進行排序? –

+1

@ Sidias-Korrado不,我從來沒有使用過它 – ldn

回答

2

只需按升序對數組排序,並且當前元素的前一個元素和下一個元素之間的最小差異將解決您的問題。在這裏爲最後一個元素,你可以看看它以前的元素的區別。

1

應通過以下能夠與LINQ做一個行:

public static int GetClosestVal(this int[] values, int place) 
{ 
    return values.OrderBy(v => Math.Abs(v - values[place])).ToArray()[1]; 
} 

下輸出30

var testArray = new [] {3, 10, 43, 100, 30, 140}; 
Console.Write(testArray.GetClosestVal(2)); 

從根本上說您是按每個項目和之間的絕對差值選擇項目,然後抓住第二個項目的名單,因爲第一個將始終是項目本身(因爲nn = 0)

因此,排序的名單應該是[43, 30, 20, 3, 100, 140]

0

我不知道,我是否理解你的問題的權利。如果我有,然後將下面的代碼片段可以幫助你:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Elements ListElements = new Elements(); 

     ListElements.ElementValue.Add(3); 

     ListElements.ElementValue.Add(10); 

     ListElements.ElementValue.Add(43); 

     ListElements.ElementValue.Add(100); 

     ListElements.ElementValue.Add(30); 

     ListElements.ElementValue.Add(140); 


     ListElements.CreateDeltaValues(); 


     for (int i = 0; i < ListElements.DeltaValue.Count; i++) 
     { 

      Console.WriteLine("ListElement["+i+"]: " + ListElements.DeltaValue[i]); 


      //example as for ListElements[2].DeltaValue will be 13; because 43-30=13; 

     } 
     Console.ReadKey(); 
    } 
} 

public class Elements 
{ 
    public List<double> DeltaValue = new List<double>(); 
    public List<double> ElementValue = new List<double>(); 

    public void CreateDeltaValues() 
    { 
     this.ElementValue.Sort(); 

     for (int i = 1; i < this.ElementValue.Count; i++) 
     { 
      var deltaValue = this.ElementValue[i] - this.ElementValue[i-1]; 
      this.DeltaValue.Add(deltaValue); 
     } 
    } 
} 

這是一個控制檯應用程序,但是這個代碼也應該適用於其他應用程序的模型。

此代碼生成以下的輸出:

enter image description here

如果這個答案有幫助你,請投我的答案!

+1

當然是肖恩,但我剛剛開始,沒有足夠的repts upvote;) – ldn

+0

你可以標記我的答案是正確的。你只需要點擊下方和上方的鉤子。 –

+0

因爲你是新人,你應該做這個小遊覽。它會幫助你更好地理解stackoverflow。 http://stackoverflow.com/tour,你將會在你完成遊覽後賺取一些東西。你只需要3分鐘就可以完成這次巡演。 –

相關問題