英文:
Sort only the odd elements of an array
问题
I want to sort only the odd elements of an array, leaving the even elements unchanged.
I have created the below using LINQ queries, but get an error on this line:
.Select(x => x.value % 2 == 1 ? x.value : dictionary[x.index])
The error is due to there not being an item in the dictionary with key '2'. I.e. the dictionary[x.index] term in the if statement is being evaluated when the criteria for the if statement is false (i.e. when x.value is even).
public class Kata
{
public static int[] SortArray(int[] array)
{
var dictionary = array
.Select((value, index) => new { value, index })
.Where(x => x.value % 2 == 1)
.OrderBy(x => x.value)
.ToDictionary(x => x.index, x => x.value);
var output = array
.Select((value, index) => new { value, index })
.Select(x => x.value % 2 == 1 ? x.value : dictionary[x.index])
.ToArray();
return new int[1];
}
}
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Kata.SortArray(new int[] { 5, 3, 2, 8, 1, 4 }));
}
}
英文:
I want to sort only the odd elements of an array, leaving the even elements unchanged.
I have created the below using LINQ queries, but get an error on this line:
.Select(x => x.value % 2 == 1 ? x.value : dictionary[x.index])
The error is due to there not being an item in the dictionary with key '2'. I.e. the dictionary[x.index] term in the if statement is being evaluated when the criteria for the if statement is false (i.e. when x.value is even).
public class Kata
{
public static int[] SortArray(int[] array)
{
var dictionary = array
.Select((value, index) => new { value, index })
.Where(x => x.value % 2 == 1)
.OrderBy(x => x.value)
.ToDictionary(x => x.index, x => x.value);
var output = array
.Select((value, index) => new { value, index })
.Select(x => x.value % 2 == 1 ? x.value : dictionary[x.index])
.ToArray();
return new int[1];
}
}
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Kata.SortArray(new int[] { 5, 3, 2, 8, 1, 4 }));
}
}
答案1
得分: 1
你可以提取奇数项,对它们进行排序,最后将它们放回:
int[] array = new int[] { 5, 3, 2, 8, 1, 4};
// 提取并排序奇数项
using var odd = array
.Where(item => item % 2 != 0)
.OrderBy(item => item)
.GetEnumerator();
for (int i = 0; i < array.Length; ++i)
if (array[i] % 2 != 0 && odd.MoveNext())
array[i] = odd.Current;
请注意,检查奇数应该是 item % 2 != 0
,而不是 item % 2 == 1
,因为余数 %
在负数 item
上返回 -1
。
英文:
You can extract odd items, sort them, and finally put them back:
int[] array = new int[] { 5, 3, 2, 8, 1, 4};
// odd items extracted and sorted
using var odd = array
.Where(item => item % 2 != 0)
.OrderBy(item => item)
.GetEnumerator();
for (int i = 0; i < array.Length; ++i)
if (array[i] % 2 != 0 && odd.MoveNext())
array[i] = odd.Current;
Please, note that checking for odd should be item % 2 != 0
, not item % 2 == 1
, since remainder %
returns -1
on negative item
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论