2013-07-25 44 views
0

有沒有更好的方法(速度不需要,簡潔和簡單想要)在較少的代碼行中實現以下內容? (下面的實施例)選擇一個相對於另一個數字的數字

// Example // 
/* 
* Get Divisor For Number of Iterations - To Display Progress 
*/ 
int fGetDivisor(int iMaxIters) { 
    int iDiv = 500; // init 
    if (iMaxIters >= 100000) 
    iDiv = 20000; 
    else if (iMaxIters > 20000) 
    iDiv = 10000; 
    else if (iMaxIters > 5000) 
    iDiv = 2000; 
    else if (iMaxIters > 2000) 
    iDiv = 1000; 

    return iDiv; 
} 
+0

是不是有你的代碼'5000'和'10000'錯誤? –

+0

與條件相同的問題。第一個是'> ='和其他'>'。它想要嗎? –

+0

它看起來對我很好,但你可能是對的。我看不出什麼是錯誤的。也許作業可能是更好的選擇,但我看不到一個實際的錯誤。感謝您的回答。 –

回答

2

隨着a ? b : c

int fGetDivisor(int iMaxIters) => 
    iMaxIters >= 100000 ? 20000 : 
    iMaxIters > 20000 ? 10000 : 
    iMaxIters > 5000 ? 2000 : 
    iMaxIters > 2000 ? 1000 : 
          500 ; 

或者與Map<int,int>具有條件只在一個地方:

import 'dart:collection'; 

int fGetDivisor(int iMaxIters) { 
    final map = new LinkedHashMap<int,int>() 
    ..[99999] = 20000 
    ..[20000] = 10000 
    ..[ 5000] = 2000 
    ..[ 2000] = 1000 
    ; 
    for (final step in map.keys) { 
    if (iMaxIters > step) return map[step]; 
    } 
    return 500; 
} 
+0

是的,我覺得呢? b:c可能是要走的路,所以我可能會打勾表示謝意。它簡短,可讀,簡單,毫無疑問足夠快。我正在尋找更通用的東西,所以我可以單獨發佈。並不是說這是一件大事,但優雅的代碼無處不在。 –

1

一般用於這種類型的代碼我喜歡使用鍵列表和值列表。該firstWhere方法可以幫助我們在這裏還有:

int fGetDivisor(int iMaxIters) { 
    var keys = [99999, 20000, 5000, 2000]; 
    var vals = [20000, 10000, 2000, 1000]; 

    var key = keys.firstWhere((e) => iMaxIters > e, orElse:() => null); 
    return key == null ? 500 : vals[keys.indexOf(key)]; 
} 

這種方法還可以方便地添加新值對證。

+0

謝謝,這可能會在別處有用。 –

1
int fGetDivisor(int iMaxIters) => 
    [[999999, 20000], [20000, 10000], [5000, 2000], [2000, 1000]] 
    .firstWhere((x) => iMaxIters > x[0], orElse:() => [0, 500])[1]; 
+0

謝謝,我可能會在其他地方使用。 –

2

坦率地說,我認爲那些firstWhere使它更復雜。

這是最簡單的我能想出:

int fGetDivisor(int iMaxIters) { 
    if (iMaxIters >= 100000) return 20000; 
    if (iMaxIters > 20000) return 10000; 
    if (iMaxIters > 5000) return 2000; 
    if (iMaxIters > 2000) return 1000; 
    return 500; 
} 
+0

感謝您的建議。 –

相關問題