1

c# で整数の配列 (文字列として扱う方が良い場合があります) に対して次のことを行うための最良の解決策は何ですか?

例 1:

配列は次のもので構成されます:

440 - 441 - 442 - 443 - 444 - 445 - 446 - 447 - 448 - 449 - 51 - 9876

結果は次のようになります:

44 - 51 - 9876 

適用されるルール 441 から 449 は 44 に置き換えられます。これは、0 ~ 9 の完全なセットがあるためです。

例 2

配列は次のもので構成されます:

440 - 441 - 442 - 443 - 444 - 445 - 446 - 447 - 448 - 449 - 40 - 41 - 42 - 43 - 45 - 46 - 47 - 48 - 49

結果は次のようになります:

4 - 51 - 9876 

適用されるルール : 最初に 3 つの文字列 (すべて 44 で始まる文字列) が 44 に削減され、次に同じルールによって 40 から 49 が 4 に削減されます。

4

3 に答える 3

2

怠け者で LINQ だけを使用するのはどうですか?

int[] arr1 = { 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 51, 9876 };

// This is just one reduction step, you would need loop over it until
// no more reduction is possible.
var r = arr1.GroupBy(g => g / 10).
        SelectMany(s => s.Count() == 10 ? new int[] {s.Key} : s.AsEnumerable());
于 2012-11-21T22:50:40.267 に答える
0

10 分岐のインデックス ツリーを作成し、各ノードの子の数を記録します。次に、ツリーをブラウズし、子番号が 10 のノードで停止します。

于 2012-11-22T09:30:01.440 に答える
0

並べ替えられたデータ構造を使用するが、並べ替えを節約するソリューションを次に示します。

擬似コード:

numbers //your array of number
sortedSet //a sorted data structure initially empty

function insertSorted (number) {
  sortedSet.put(number) //simply add the number into a sorted structure
  prefix = number / 10 //prefix should be int to truncate the number

  for (i=0;i<10;i++){
    if ( ! sortedSet contains (prefix * 10 + i) )
      break; //so i != 10, not all 0-9 occurrences of a prefix found
  }
  if ( i== 10 ) {//all occurrences of a prefix found
    for (i=0;i<10;i++){
      sortedSet remove (prefix*10 + i)
    }
    insertSorted(prefix) //recursively check if the new insertion triggered further collapses
  }
}

最後に、次のように呼び出します。

foreach number in numbers
  insertSorted (number)
于 2012-11-21T17:02:51.233 に答える