Advertisement
yahorrr

Untitled

Sep 20th, 2022
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System;
  2.  
  3. namespace FilterTask
  4. {
  5.     public static class ArrayExtension
  6.     {
  7.         /// <summary>
  8.         /// Returns new array of elements that contain expected digit from source array.
  9.         /// </summary>
  10.         /// <param name="source">Source array.</param>
  11.         /// <param name="digit">Expected digit.</param>
  12.         /// <returns>Array of elements that contain expected digit.</returns>
  13.         /// <exception cref="ArgumentNullException">Thrown when array is null.</exception>
  14.         /// <exception cref="ArgumentException">Thrown when array is empty.</exception>
  15.         /// <exception cref="ArgumentOutOfRangeException">Thrown when digit value is out of range (0..9).</exception>
  16.         /// <example>
  17.         /// {1, 2, 3, 4, 5, 6, 7, 68, 69, 70, 15, 17}  => { 7, 70, 17 } for digit = 7.
  18.         /// </example>
  19.         public static int[] FilterByDigit(int[]? source, int digit)
  20.         {
  21.             int length = source.Length;
  22.             int[] result = new int[length];
  23.             int k = 0;
  24.             for (int i = 0; i < length; i++)
  25.             {
  26.                 int dump = Math.Abs(source[i]);
  27.                 do
  28.                 {
  29.                     if (dump % 10 == digit)
  30.                     {
  31.                         result[k] = source[i];
  32.                         k++;
  33.                         break;
  34.                     }
  35.  
  36.                     dump /= 10;
  37.                 }
  38.                 while (dump > 0);
  39.             }
  40.  
  41.             Array.Resize(ref result, k);
  42.  
  43.             return result;
  44.         }
  45.     }
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement