How to traverse multidimensional arrays with an undefined dimension limit

Source: Internet
Author: User

This question is not convenient to use recursion!

Intuition tells me that we can use two layers to traverse. The outer layer is a dimension, and the inside layer is a dimension. But in fact, it is very difficult to do it!

Finally, the number of elements used in the outermost loop is determined. The number of elements used in the loop is used in conjunction with the cycle of dimensions, and the problem is finally solved!

 

 Static void Arrenum ( Array Arr, Action < Int32 []> Func ){ Int32 [] IX = New  Int32 [Arr. Rank]; Int32 Rank = 0; For ( Int I = 0; I <arr. length; I ++ ){ // The current layer is cleared below For ( Int J = rank + 1; j <arr. rank; j ++) {IX [J] = 0 ;} // Set it to the bottom layer Rank = arr. Rank-1; // Do something // arr. setvalue (I, IX ); Func (IX ); // Increment of the current Layer IX [Rank] ++; // If the upper limit is exceeded, the hierarchy is reduced.  While (IX [Rank]> = arr. getlength (rank) {rank --; If (Rank <0) Break ; IX [Rank] ++ ;}}}Static void Test2 (){ Int32 [,] Arr = New  Int32 [24, 24, 24, 24]; Int32 N = 1; arrenum (ARR, IX => arr. setvalue (N ++, IX); arrenum (ARR, Delegate ( Int32 [] IX ){ Console . Write ( "[" ); For ( Int I = 0; I <IX. length; I ++ ){ If (I> 0) Console . Write ( "," ); Console . Write (IX [I]);} Console . Write ( "] \ T" ); Console . Writeline (ARR. getvalue (IX ));});}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.