-
-
Save unilecs/cafa43ee7cffa0620cbb9281fd7b101f to your computer and use it in GitHub Desktop.
Задача: Непростая сортировка - 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
public class Program | |
{ | |
public class CustomSort : IComparer<int> | |
{ | |
// Кастомная сортировка по след.правилу: | |
// число X меньше числа Y тогда и только тогда, | |
// когда сумма его чисел меньше суммы чисел Y. | |
public int Compare(int x, int y) | |
{ | |
return SumDigits(x).CompareTo(SumDigits(y)); | |
} | |
} | |
public static int SumDigits(int number) | |
{ | |
int sum = 0; | |
while (number > 0) | |
{ | |
sum += number % 10; | |
number = number / 10; | |
} | |
return sum; | |
} | |
public static void SortArrayBySumDigits(int[] numbers) | |
{ | |
Array.Sort(numbers, new CustomSort()); // сортируем массив по нужному правилу: CustomSort | |
int[] sumDigitsArr = numbers.Select(x => SumDigits(x)).ToArray(); | |
Console.WriteLine(string.Join(", ", numbers)); | |
Console.WriteLine(string.Join(", ", sumDigitsArr)); | |
} | |
public static void Main() | |
{ | |
Console.WriteLine("UniLecs\n"); | |
SortArrayBySumDigits(new int[] { 19, 22, 30 }); | |
Console.WriteLine(); | |
SortArrayBySumDigits(new int[] { 13, 23, 30 }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment