2017-12-02 10 views
-1

入力印刷最小値が最高値

[1,5,3,7,2,10,15,9] 

出力

[1,15,2,10,3,9,5,7] 

ロジックは

[1st smallest value, 1st highest value, 2nd smallest value, 2nd highest value, ...]がどのようにC#でこれを実装するのですか?

+0

?あなたはどこにいらっしゃいますか? – Zephire

答えて

2

別の解決策:

public static IEnumerable<T> SmallestGreatestSequence<T>(
    this IEnumerable<T> source) 
{ 
    var ordered = source.OrderBy(i => i).ToList(); 
    var ascendingIndex = 0; 
    var descendingIndex = ordered.Count - 1; 

    while (ascendingIndex < descendingIndex) 
    { 
     yield return ordered[ascendingIndex++]; 
     yield return ordered[descendingIndex--]; 
    } 

    if (ascendingIndex == descendingIndex) 
     yield return ordered[ascendingIndex]; 
} 

そして、あなたはこのようにそれを使用したい:あなたがこれまで持っている何

var someArray = new[] { 1, 5, 3, 7, 2, 10, 15, 9 }; 
var sortedArray = someArray.SmallestGreatestSequence().ToArray(); 
0

私は、これはSQLやMySQL関連のある方法を見て、しかし、最初のタグをC#であるとして、ここではそのためのソリューションですしないでください。

var inputSorted = input.OrderBy(i => i).ToArray(); 
var output = new List<int>(); 

//go with index to the half of the array 
for (int i = 0; i < inputSorted.Length/2; i++) 
{ 
    //add the i-th lowest number 
    output.Add(inputSorted[i]); 
    //add the i-th highest number 
    output.Add(inputSorted[inputSorted.Length - i - 1]); 
} 

//if the length of the array is odd, add the single left out number 
if (inputSorted.Length % 2 == 1) 
{ 
    output.Add(inputSorted[inputSorted.Length/2]); 
} 
+0

名前 'input'は現在のコードで終了しません。 このエラーをどのようにしてこのプログラムを削除しますか?初心者ですので気にしないでください。 –

1

あなたはLINQベースのソリューションに満足している場合、下記のオプションかもしれない。

var input = new int[] { 1, 5, 3, 7, 2, 10, 15, 9, 6 }; 

var sorted = input 
    .OrderBy(z => z) 
    .ToList(); 

var zippedInOrder = sorted.Take(input.Length/2) 
         .Zip(
          Enumerable.Reverse(sorted).Take(input.Length/2), 
          (a, b) => new int[] { a, b }); 

var inOrder = zippedInOrder.SelectMany(z => z); 

if (input.Length % 2 == 1) 
{ 
    // Add the 'middle' element (sort order wise) 
    inOrder = inOrder.Concat(new List<int> { sorted[input.Length/2] }); 
} 

var finalInOrder = inOrder.ToList(); 

// To test 
Console.WriteLine(string.Join(",", finalInOrder)); 

コードが入力データをソートし、次いで低い数値をとり、Zipは多数でそれらをです。次にSelectManyを使用してデータを単一のIEnumerableに投影します。 Concatは、残りの中間アイテムを追加するために使用されます(Lengthが奇数だった場合)。