Рекурсивный перебор элементов массива любой размерности - C#

Узнай цену своей работы

Формулировка задачи:

Так долго вожусь и все равно ничего :
Листинг программы
  1. public static void _ForEach<T>(this Array a , Func<T,T> act){
  2. int[] indices = new int[a.Rank];
  3. a._For(i =>a.SetValue( act((T)a.GetValue(i)) , i),ref indices , 0);
  4. }
  5. public static void _For(this Array a , Action<int[]> act ,ref int[] indices, int j = 0 ){
  6. act(indices);
  7. try{indices[j]++;} catch(IndexOutOfRangeException) { //Этот алгоритм пропускает 1 и 1 2 и 2 ,я это восполняю
  8. for (UInt32 i = 0; i < a.Rank; i++) {
  9. for ( UInt32 i_ = 0; i_ < indices.Rank ;i_++) indices[i_] = (int)i;
  10. act(indices);
  11. }
  12. return;
  13. }
  14. if (indices[j] < a.GetLength(j)-1) a._For(act,ref indices,j);
  15. else a._For(act,ref indices,++j);
  16. }
Очень уродливый код и безысходность , спасайте.

Решение задачи: «Рекурсивный перебор элементов массива любой размерности»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApp1
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.  
  14.             int[,,,] a =
  15.             {
  16.                 {
  17.                     {
  18.                         {1,2,3 },
  19.                         {4,5,6 },
  20.                         {7,8,9 }
  21.                     },
  22.                     {
  23.                         {10,11,12},
  24.                         {13,14,15},
  25.                         {16,17,18}
  26.                     }
  27.                 },
  28.                 {
  29.                     {
  30.                         {19,20,21 },
  31.                         {22,23,24 },
  32.                         {25,26,27 }
  33.                     },
  34.                     {
  35.                         {28,29,30},
  36.                         {31,32,33},
  37.                         {34,35,36}
  38.                     }
  39.                 }
  40.             };
  41.             ForEach(a, Console.WriteLine);
  42.             Console.ReadKey();
  43.         }
  44.  
  45.         static void ForEach(Array a, Action<object> act, int index = 0)
  46.         {
  47.             if (a == null || index < 0 || index >= a.Length) return;
  48.             int[] ind = new int[a.Rank];
  49.             FillIndArray(a, index, 0, ind);
  50.             act(a.GetValue(ind));
  51.             if (index < a.Length - 1) ForEach(a, act, index + 1);
  52.         }
  53.  
  54.  
  55.         private static void FillIndArray(Array a, int index, int dimension, int[] result)
  56.         {
  57.             int d, r;
  58.             d = Math.DivRem(index, a.GetLength(dimension), out r);
  59.             result[dimension] = r;
  60.             if (dimension < a.Rank - 1)
  61.             {
  62.                 FillIndArray(a, d, dimension + 1, result);
  63.             }
  64.         }
  65.     }
  66. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

13   голосов , оценка 4.077 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы