Рекурсивный перебор элементов массива любой размерности - C#
Формулировка задачи:
Так долго вожусь и все равно ничего :
Очень уродливый код и безысходность , спасайте.
Листинг программы
- public static void _ForEach<T>(this Array a , Func<T,T> act){
- int[] indices = new int[a.Rank];
- a._For(i =>a.SetValue( act((T)a.GetValue(i)) , i),ref indices , 0);
- }
- public static void _For(this Array a , Action<int[]> act ,ref int[] indices, int j = 0 ){
- act(indices);
- try{indices[j]++;} catch(IndexOutOfRangeException) { //Этот алгоритм пропускает 1 и 1 2 и 2 ,я это восполняю
- for (UInt32 i = 0; i < a.Rank; i++) {
- for ( UInt32 i_ = 0; i_ < indices.Rank ;i_++) indices[i_] = (int)i;
- act(indices);
- }
- return;
- }
- if (indices[j] < a.GetLength(j)-1) a._For(act,ref indices,j);
- else a._For(act,ref indices,++j);
- }
Решение задачи: «Рекурсивный перебор элементов массива любой размерности»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[,,,] a =
- {
- {
- {
- {1,2,3 },
- {4,5,6 },
- {7,8,9 }
- },
- {
- {10,11,12},
- {13,14,15},
- {16,17,18}
- }
- },
- {
- {
- {19,20,21 },
- {22,23,24 },
- {25,26,27 }
- },
- {
- {28,29,30},
- {31,32,33},
- {34,35,36}
- }
- }
- };
- ForEach(a, Console.WriteLine);
- Console.ReadKey();
- }
- static void ForEach(Array a, Action<object> act, int index = 0)
- {
- if (a == null || index < 0 || index >= a.Length) return;
- int[] ind = new int[a.Rank];
- FillIndArray(a, index, 0, ind);
- act(a.GetValue(ind));
- if (index < a.Length - 1) ForEach(a, act, index + 1);
- }
- private static void FillIndArray(Array a, int index, int dimension, int[] result)
- {
- int d, r;
- d = Math.DivRem(index, a.GetLength(dimension), out r);
- result[dimension] = r;
- if (dimension < a.Rank - 1)
- {
- FillIndArray(a, d, dimension + 1, result);
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д