@mboze

Функция swap заменить максимальные и минимальные значения массивов?

Добрый день, поскажите пожалуйста, пытаюсь реализовать чтобы максимальные и минимальные значения менялись с друг другом , к примеру : Даны 2 массива ,в массиве А есть элемент 2, он минимальный, в массиве В есть элемент 3, он минимальный, надо так, чтобы они поменялись местами и аналогия с максимальными значениями, код, который сейчас есть:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp28
{
    class Program
    {
        public static void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;

        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Введите количесвто строк (m)");
            int m = int.Parse(Console.ReadLine());
            Console.WriteLine("Введите количесвто столбцов (n)");
            int n = int.Parse(Console.ReadLine());
            int[,] A = new int[m, n];
            Console.WriteLine("массив А");
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                    A[i, j] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Начальный массив");

            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                    Console.Write(A[i, j] + "\t");
                Console.WriteLine();
            }

            Console.WriteLine("Введите количесвто строк (k)");
            int k = int.Parse(Console.ReadLine());
            Console.WriteLine("Введите количесвто столбцов (l)");
            int l = int.Parse(Console.ReadLine());
            int[,] B = new int[k, l];
            Console.WriteLine("массив B");
            for (int e = 0; e < k; e++)
            {
                for (int g = 0; g < l; g++)
                    B[e, g] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Начальный массив");

            for (int e = 0; e < k; e++)
            {
                for (int g = 0; g < l; g++)
                    Console.Write(B[e, g] + "\t");
                Console.WriteLine();
            }
            int maxA = A[0, 0];
            int minA = A[0, 0];
            int maxB = B[0, 0];
            int minB = B[0, 0];
            Console.WriteLine("Готовый массив");
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (A[i, j] > maxA)
                        maxA = A[i, j];
                }
            }
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (A[i, j] < minA)
                        minA = A[i, j];
                }
            }

            for (int e = 0; e < k; e++)
            {
                for (int g = 0; g < l; g++)
                {
                    if (B[e, g] > maxB)
                        maxB = B[e, g];
                }
            }
            for (int e = 0; e < k; e++)
            {
                for (int g = 0; g < l; g++)
                {
                    if (B[e, g] < minB)
                        minB = B[e, g];
                }
            }
            //Console.WriteLine("do max A" + maxA);
            //Console.WriteLine("do max B" + maxB);
            Program.Swap(ref maxA, ref maxB);
            //Console.WriteLine("posl max A" + maxA);
            // Console.WriteLine("posl max B" + maxB);
            Program.Swap(ref minA, ref minB);
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                    Console.Write(A[i, j] + "\t");
                Console.WriteLine();
            }
            Console.WriteLine("Готовый массив");
            for (int e = 0; e < k; e++)
            {
                for (int g = 0; g < l; g++)
                    Console.Write(B[e, g] + "\t");
                Console.WriteLine();
            }

            Console.ReadLine();

        }
    }
}

Вывод, который сейчас есть:
628d224a3c5c7916512898.jpeg
  • Вопрос задан
  • 346 просмотров
Решения вопроса 1
Casper-SC
@Casper-SC
Программист (.NET)
Обмен местами первых найденных минимальных значений в двух двумерных массивах.
using System;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[,] arrayA = new int[3, 4]
            {
                {5, 5, 50, 5},
                {5, 5, 5, 5},
                {5, 5, 5, 2},
            };
            int[,] arrayB = new int[4, 2]
            {
                {5, 5},
                {5, 1},
                {15, 5},
                {5, 1},
            };

            Console.WriteLine("Array A:");
            Print(arrayA);

            Console.WriteLine();
            Console.WriteLine("Array B:");
            Print(arrayB);

            Console.WriteLine();
            Console.WriteLine("Array A, first min value position:");
            var (yMinA, xMinA) = FindFirstMinValuePosition(arrayA);
            Print(xMinA, yMinA);

            Console.WriteLine();
            Console.WriteLine("Array B, first min value position:");
            var (yMinB, xMinB) = FindFirstMinValuePosition(arrayB);
            Print(xMinB, yMinB);

            Console.WriteLine();
            Console.WriteLine("Array A, first max value position:");
            var (yMaxA, xMaxA) = FindFirstMaxValuePosition(arrayA);
            Print(xMaxA, yMaxA);

            Console.WriteLine();
            Console.WriteLine("Array B, first max value position:");
            var (yMaxB, xMaxB) = FindFirstMaxValuePosition(arrayB);
            Print(xMaxB, yMaxB);

            Swap(arrayA, arrayB, yMinA, xMinA, yMinB, xMinB);
            Swap(arrayA, arrayB, yMaxA, xMaxA, yMaxB, xMaxB);

            Console.WriteLine("----");
            Console.WriteLine();
            Console.WriteLine("Array A after two swaps:");
            Print(arrayA);

            Console.WriteLine();
            Console.WriteLine("Array B after two swaps:");
            Print(arrayB);

            Console.WriteLine();
        }

        private static void Swap(int[,] arrayA, int[,] arrayB, int yA, int xA, int yB, int xB)
        {
            int tempB = arrayB[yB, xB];
            arrayB[yB, xB] = arrayA[yA, xA];
            arrayA[yA, xA] = tempB;
        }

        private static (int y, int x) FindFirstMinValuePosition(int[,] array)
        {
            if (array is null) throw new ArgumentNullException(nameof(array));

            int y = array.GetLength(0);
            int x = array.GetLength(1);

            if (y == 0) throw new InvalidOperationException(
                "The dimension of the array along the Y axis is zero.");
            if (x == 0) throw new InvalidOperationException(
                "The dimension of the array along the X axis is zero.");

            int yResult = 0;
            int xResult = 0;

            int minValue = array[0, 0];
            for (int yIndex = 0; yIndex < y; yIndex++)
            {
                for (int xIndex = 0; xIndex < x; xIndex++)
                {
                    if (minValue > array[yIndex, xIndex])
                    {
                        yResult = yIndex;
                        xResult = xIndex;
                        minValue = array[yIndex, xIndex];
                    }
                }
            }

            return (yResult, xResult);
        }

        private static (int y, int x) FindFirstMaxValuePosition(int[,] array)
        {
            if (array is null) throw new ArgumentNullException(nameof(array));

            int y = array.GetLength(0);
            int x = array.GetLength(1);

            if (y == 0) throw new InvalidOperationException(
                "The dimension of the array along the Y axis is zero.");
            if (x == 0) throw new InvalidOperationException(
                "The dimension of the array along the X axis is zero.");

            int yResult = 0;
            int xResult = 0;

            int maxValue = array[0, 0];
            for (int yIndex = 0; yIndex < y; yIndex++)
            {
                for (int xIndex = 0; xIndex < x; xIndex++)
                {
                    if (maxValue < array[yIndex, xIndex])
                    {
                        yResult = yIndex;
                        xResult = xIndex;
                        maxValue = array[yIndex, xIndex];
                    }
                }
            }

            return (yResult, xResult);
        }

        private static void Print(int x, int y)
        {
            Console.WriteLine($"x: {x}, y: {y}");
        }

        private static void Print(int[,] array)
        {
            int x = array.GetLength(0);
            int y = array.GetLength(1);

            for (int xIndex = 0; xIndex < x; xIndex++)
            {
                for (int yIndex = 0; yIndex < y; yIndex++)
                {
                    Console.Write($"{array[xIndex, yIndex]}, ");
                }
                Console.WriteLine();
            }
        }
    }
}


Вывод программы:
Array A:
5, 5, 50, 5,
5, 5, 5, 5,
5, 5, 5, 2,

Array B:
5, 5,
5, 1,
15, 5,
5, 1,

Array A, first min value position:
x: 3, y: 2

Array B, first min value position:
x: 1, y: 1

Array A, first max value position:
x: 2, y: 0

Array B, first max value position:
x: 0, y: 2
----

Array A after two swaps:
5, 5, 15, 5,
5, 5, 5, 5,
5, 5, 5, 1,

Array B after two swaps:
5, 5,
5, 2,
50, 5,
5, 1,
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
freeExec
@freeExec
Участник OpenStreetMap
Так ты меняешь местами найденные макс/мин значения, а не где ты их нашёл в массивах. И вообще использовать ref дурной тон. Найди индексы этих значений в массиве и поменяй значения по-человечески.
Ответ написан
EveningEugene
@EveningEugene
Unity-разраб
Вызывая Swap() вы меняете местами значения в переменных maxA и maxB, но этим вы никак не модифицируете массивы, так как int - значимый тип, а не ссылочный.

Предлагаю, вместо сохранения значений минимума и максимума, сохранять индексы ячеек с такими значениями, а функцию Swap() переделать так, чтоб он принимал массивы и индексы заменяемых ячеек и уже редактировать этот массив, меняя в нем местами значения по указанным индексам.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы