2013-07-31 26 views
3

我有一個列表,我需要找到並提取緊鄰新列表的所有數字。算法檢查列表中相似性的數字關閉

比如我有一個列表:

1,5,10,8,11,14,15,11,14,1,4,7,5,9

,所以如果我想提取所有接近3的數字(只有3,差距必須是3,因此11,14是正確的,11,13不是)。我怎樣才能設計這個,而不用硬編碼整個事物呢?

的結果應該是這樣的: 8,11,14,11,14,1,4,7

這看起來並不太難,但我是那種堅持,所有我能想出with是一個循環,它檢查循環中的n + 1成員,如果它大於n乘3,並將n + 1成員包括在新列表中,但是我不知道如何包含n成員而不使其出現在新列表兩次,如果有一串需要的數字。

有什麼想法?

+2

這可能是值得炫耀你已經嘗試了什麼。你介意解決方案的語言是什麼? – doctorlove

+0

我不明白你的問題,爲什麼在輸出中是「1」? –

+0

我也不明白,爲什麼在輸出列表中不是15? – Fabinout

回答

2

只需遍歷列表,檢查下一個和上一個元素,並保存當前元素,如果它與任一元素相差3。在Python,這是

>>> l = [1,5,10,8,11,14,15,11,14,1,4,7,5,9] 
>>> # pad with infinities to ease the final loop 
>>> l = [float('-inf')] + l + [float('inf')] 
>>> [x for i, x in enumerate(l[1:-1], 1) 
... if 3 in (abs(x - l[i-1]), abs(x - l[i+1]))] 
[8, 11, 14, 11, 14, 1, 4, 7] 
0

這是一個循環:

public List<int> CloseByN(int n, List<int> oldL) 
{ 
    bool first = true; 
    int last = 0; 
    bool isLstAdded = false; 
    List<int> newL = new List<int>(); 
    foreach(int curr in oldL) 
    { 
     if(first) 
     { 
     first = false; 
     last = curr; 
     continue; 
     } 
     if(curr - last == n) 
     { 
     if(isLstAdded == false) 
     { 
      newL.Add(last); 
      isLstAdded = true; 
     } 
     newL.Add(curr); 
     } 
     else 
     { 
     isLstAdded = false; 
     } 
     last = curr; 
    } 
    return newL; 
} 

測試您的輸入,並得到了你的輸出

1

在Matlab中

list = [1,5,10,8,11,14,15,11,14,1,4,7,5,9] 

然後

list(or([diff([0 diff(list)==3]) 0],[0 diff(list)==3])) 

回報

8 11 14 11 14  1  4  7 

對於那些不瞭解Matlab diff(list)的人返回list中元素的第一個(正向)差異。表達式[0 diff(list)]用前導0填充第一個差異,以使結果與原始list的長度相同。其餘的應該是顯而易見的。

總而言之:挑選差異和落後差異,選擇差異爲3的元素。

1

一個簡單的C++以下代碼:

假設ar是初始整數數組和標記是boolean array

for(int i=1;i<N;i++){ 
    if(ar[i]-ar[i-1]==3){ 
     mark[i]=1; 
     mark[i-1]=1; 
    } 
} 

現在打印的有趣的數字,

for(int i=0;i<N;i++){ 
    if(mark[i]==1)cout<<ar[i]<<" "; 
} 

的在實現背後的想法是,如果它與前一個的差異是3或者差異的話,我們將其標記爲有趣的n並且它的下一個數字是3.

0

和Haskell的版本:

f g xs = dropWhile (null . drop 1) $ foldr comb [[last xs]] (init xs) where 
    comb a [email protected](b:bs) 
    | abs (a - head b) == g = (a:head bbs) : bs 
    | otherwise = 
     if null (drop 1 b) then [a] : bs else [a] : bbs 

輸出:

*Main> f 3 [5,10,8,11,14,15,11,14,1,4,7,5,9] 
[[8,11,14],[11,14],[1,4,7]] 

*Main> f 5 [5,10,8,11,14,15,11,14,1,4,7,5,9] 
[[5,10]]