所谓的潇洒

导航

二维数组和交错数组

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)
        {
            //交错数组
            Console.WriteLine("交错数组");
            int[][] arr = new int[3][] { new int[] { 1, 2, 3 }, new int[] { 4 }, new int[] { 5, 6 } };
            PrintJaggedArry(arr);

            //二维数组
            Console.WriteLine("\r\n二维数组");
            int[,] arr2 = new int[3, 2] { { 1, 3 }, { 2, 4 }, { 2, 6 } };
            Console.WriteLine($"元素总数:{arr2.Length}");
            int len = arr2.GetLength(0);
            Console.WriteLine($"第1维长度:{len}");
            int len2 = arr2.GetLength(1);
            Console.WriteLine($"第2维长度:{len2}");
            for (int i = 0; i < len; i++)
            {
                for (int j = 0; j < len2; j++)
                {
                    Console.Write($"{arr2[i, j]} ");
                }
                Console.WriteLine();
            }

            //二维数组转交错数组
            Console.WriteLine("\r\n二维数组转交错数组");
            var arr3 = TwoDimenArryToJaggedArry(arr2);
            PrintJaggedArry(arr3);

            Console.ReadKey();
        }

        private static void PrintJaggedArry(int[][] arr)
        {
            Console.WriteLine($"外层数组长度:{arr.Length}");
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write($"子数组{i + 1}(长度:{arr[i].Length}): ");

                for (int j = 0; j < arr[i].Length; j++)
                {
                    Console.Write(arr[i][j] + " ");
                }

                Console.WriteLine();
            }
        }

        /// <summary>
        /// 二维数组转交错数组
        /// </summary>
        /// <param name="twoDimenArry"></param>
        /// <returns></returns>
        public static int[][] TwoDimenArryToJaggedArry(int[,] twoDimenArry)
        {
            int len = twoDimenArry.GetLength(0);
            int len2 = twoDimenArry.GetLength(1);
            int[][] jaggedArry = new int[len][];
            for (int i = 0; i < len; i++)
            {
                jaggedArry[i] = new int[len2];
                for (int j = 0; j < len2; j++)
                {
                    jaggedArry[i][j] = twoDimenArry[i, j];
                }
            }
            return jaggedArry;
        }
    }
}

 

posted on 2023-08-25 11:44  所谓的潇洒  阅读(15)  评论(0编辑  收藏  举报