@evgemiil

Как посчитать количество одинаковых элементов в строчке и вывести первый?

Программа должна найти и вывести все последовательности из 2 и более одинаковых символов подряд в любой вертикали, горизонтали и диагонали.
Порядок вывода последовательностей не важен.
Нумерация столбцов и строк ведётся с единицы, слева направо и сверху вниз, соответственно.
Пример ввода:
M=4
N=5
b = = = b
1 b 2 b a
c 4 b a +
5 c a b +
Пример вывода:
- [1 2] = 3
| [3 5] + 2
\ [1 1] b 4
\ [3 1] c 2
/ [2 5] a 3
/ [1 5] b 3

Я вот не пойму есть специальные методы способы ероме циклов или в цикле все дело, пытался в циклах не так как нужно, подскажите направьте в правильном направлении?
using System;
using System.Linq;

namespace Matrix
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Введите количество строк");
            int M;
            string inputM = Console.ReadLine();
            var a = int.TryParse(inputM, out M);
                
            Console.WriteLine("Введите количество столбцов");
            int N;
            string inputN = Console.ReadLine();
            var b = int.TryParse(inputN, out N);
            
            if (a == false || b == false || M < 1 || N < 1)
            {
                Console.WriteLine("Неккоректный ввод!");
            }
            Console.WriteLine("Заполните матрицу");
            string[,] matrix = new string[M, N];
            try
            {
                
                string[] str;
                for (int i = 0; i < M; i++)
                {
                    str = (Console.ReadLine()).Split(' ');
                    for (int j = 0; j < M; j++)
                        matrix[i, j] = Convert.ToString(str[j]);
                }
                    
                Console.WriteLine("Матрица");

                for (int i = 0; i < M; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        Console.Write(matrix[i, j] + "\t");
                    }
                    Console.WriteLine("\n");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ошибка: " + ex.Message);
            }

            string z;
            
            for (int i = 0; i < M; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    if (j < N - 1)
                    {
                        if (matrix[i, j] == matrix[i, j + 1])
                        {
                            for (int k = N; k >= 0; --k)
                            {
                                if (k == 0) { Console.WriteLine("[" + (i + 1) + " " + (j + 1) + "]"); }
                            }

                        }
                    }
                }

            }

            Console.Write("Для выхода нажмите <Enter>");
            Console.ReadLine();

        }

        
    }
}
  • Вопрос задан
  • 3861 просмотр
Пригласить эксперта
Ответы на вопрос 2
AnnTHony
@AnnTHony
Интроверт
using System;
using System.Collections.Generic;

namespace matrix
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            if (args.Length > 0)
                return;

            string[] matrix =
            {
                "1b2ba", 
                "b====", 
                "ccb++",
                "ccab+"
            };
            HorizontalLeftToRight(matrix);
            VerticalTopToBottom(matrix);
            DiagonalUp(matrix);
            DiagonalDown(matrix);
            Console.ReadLine();
        }

        private static void HorizontalLeftToRight(IReadOnlyList<string> matrix)
        {
            for (var row = 0; row < matrix.Count; row++)
            {
                var count = 0;
                for (var col = 0; col < matrix[0].Length; col++)
                {
                    count++;
                    try
                    {
                        if (matrix[row][col].Equals(matrix[row][col + 1])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(26), row, col - count + 1, matrix[row][col], count);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(26), row, col - count + 1, matrix[row][col], count);
                    }
                    count = 0;
                }
            }
        }

        private static void VerticalTopToBottom(IReadOnlyList<string> matrix)
        {
            for (var col = 0; col < matrix[0].Length; col++)
            {
                var count = 0;
                for (var row = 0; row < matrix.Count; row++)
                {
                    count++;
                    try
                    {
                        if (matrix[row][col].Equals(matrix[row + 1][col])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(25), row - count + 1, col, matrix[row][col], count);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(25), row - count + 1, col, matrix[row][col], count);
                    }
                    count = 0;
                }
            }
        }

        private static void DiagonalUp(IReadOnlyList<string> matrix)
        {
            for (var row = 1; row < matrix.Count; row++)
            {
                var r = row;
                var count = 0;
                for (var col = 0; col < matrix[0].Length; col++)
                {
                    count++;
                    try
                    {
                        if (matrix[r][col].Equals(matrix[r - 1][col + 1])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), r + count - 1, col - count + 1, matrix[r][col], count);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), r + count - 1, col - count + 1, matrix[r][col], count);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), r + count - 1, col - count + 1, matrix[r][col], count);
                    }
                    finally
                    {
                        r--;
                    }
                    count = 0;
                }
            }

            for (var col = 1; col < matrix[0].Length; col++)
            {
                var c = col;
                var count = 0;
                for (var row = matrix.Count - 1; row > -1; row--)
                {
                    count++;
                    try
                    {
                        if (matrix[row][c].Equals(matrix[row - 1][c + 1])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), row + count - 1, c - count + 1, matrix[row][c], count);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), row + count - 1, c - count + 1, matrix[row][c], count);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(47), row + count - 1, c - count + 1, matrix[row][c], count);
                    }
                    finally
                    {
                        c++;
                    }
                    count = 0;
                }
            }
        }

        private static void DiagonalDown(IReadOnlyList<string> matrix)
        {
            for (var col = matrix[0].Length - 2; col > -1; col--)
            {
                var c = col;
                var count = 0;
                for (var row = 0; row < matrix.Count; row++)
                {
                    count++;
                    try
                    {
                        if (matrix[row][c].Equals(matrix[row + 1][c + 1])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), row - count + 1, c - count + 1, matrix[row][c], count);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), row - count + 1, c - count + 1, matrix[row][c], count);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), row - count + 1, c - count + 1, matrix[row][c], count);
                    }
                    finally
                    {
                        c++;
                    }
                    count = 0;
                }
            }

            for (var row = 1; row < matrix.Count; row++)
            {
                var r = row;
                var count = 0;
                for (var col = 0; col < matrix[0].Length; col++)
                {
                    count++;
                    try
                    {
                        if (matrix[r][col].Equals(matrix[r + 1][col + 1])) continue;
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), r - count + 1, col - count + 1, matrix[r][col], count);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), r - count + 1, col - count + 1, matrix[r][col], count);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (count > 1)
                            Console.WriteLine("{0}  [{1}, {2}]  \'{3}\'  {4}", Convert.ToChar(92), r - count + 1, col - count + 1, matrix[r][col], count);
                    }
                    finally
                    {
                        r++;
                    }
                    count = 0;
                }
            }
        }
    }
}
Ответ написан
Вариант на Linq, Extension methods и generic (можно использовать с любым типом массивов).

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace easyMatrix
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = GetTestArray();

            // Вывод массива
            for (int i = 0; i < arr.GetLength(0); i++)
            {
                Console.WriteLine(string.Join(" ", arr.GetRow(i).Select(item => item.Value)));
            }
            Console.WriteLine();
            
            
            foreach(var row in arr.GetAllRows())
            { 
                foreach (var range in row.Split((cur, next) => cur.Value != next.Value))
                {
                    Console.WriteLine("- [{0} {1}] {2} {3}", range.Item1.Row + 1, range.Item1.Col + 1, range.Item1.Value, range.Item2);
                }
            }

            foreach (var col in arr.GetAllCols())
            {
                foreach (var range in col.Split((cur, next) => cur.Value != next.Value))
                {
                    Console.WriteLine("| [{0} {1}] {2} {3}", range.Item1.Row + 1, range.Item1.Col + 1, range.Item1.Value, range.Item2);
                }
            }

            foreach (var d in arr.GetAllRightDioganals())
            {
                foreach (var range in d.Split((cur, next) => cur.Value != next.Value))
                {
                    Console.WriteLine("\\ [{0} {1}] {2} {3}", range.Item1.Row + 1, range.Item1.Col + 1, range.Item1.Value, range.Item2);
                }
            }

            foreach (var d in arr.GetAllLeftDioganals())
            {
                foreach (var range in d.Split((cur, next) => cur.Value != next.Value))
                {
                    Console.WriteLine("/ [{0} {1}] {2} {3}", range.Item1.Row + 1, range.Item1.Col + 1, range.Item1.Value, range.Item2);
                }
            }

            Console.WriteLine();
            var lookup = arr.GetRow(0).ToLookup(c => c.Value);

            Console.WriteLine("Lookup второй строки:");
            foreach (var g in lookup)
            {
                Console.WriteLine("'{0}' {1}", g.Key, g.Count());
            }
            Console.WriteLine();

            var group = lookup.OrderByDescending(g => g.Count()).First();
            Console.WriteLine("Максимальное количество вхождений {0} обнаружено для символа '{1}'", group.Count(), group.Key);

            Console.WriteLine("Обчщее количество повторяющихся символов {0}", lookup.Where(g => g.Count() > 1).Sum(s => s.Count()));


            Console.ReadKey();
        }

        public static Char[,] GetTestArray()
        {
            var lst = new string[]{
                "b=b==",
                "1b2ba",
                "c4b++",
                "5cab+"
            };

            Char[,] arr = new Char[lst.Count(), lst.First().Length];

            for (int rowIndex = 0; rowIndex < lst.Count(); ++rowIndex)
            {
                var row = lst[rowIndex];

                for (int colIndex = 0; colIndex < lst.First().Length; ++colIndex)
                {
                    arr[rowIndex, colIndex] = row.ElementAt(colIndex);
                }
            }

            return arr;
        }
    }

    public static class IEnumerableExtension
    {
        public static IEnumerable<Tuple<T, int>> Split<T>(this IEnumerable<T> items, Func<T, T, bool> separator)
        {
            T p = items.First();
            int cnt = 0;
            foreach (var item in items)
            {
                if (separator(p, item))
                {
                    if (cnt > 1)
                    {
                        yield return Tuple.Create(p, cnt);
                    }

                    p = item;
                    cnt = 1;
                }
                else
                {
                    ++cnt;
                }
            }

            if (cnt > 1)
            {
                yield return Tuple.Create(p, cnt);
            }
        }
    }

    public static class ArrayExtension
    {
        public class Item<T>
        {
            private int _row;
            public int Row { get { return _row; } }

            private int _col;
            public int Col { get { return _col; } }

            private T _value;
            public T Value { get { return _value; } }

            public Item(T[,] arr, int row, int col)
            {
                Debug.Assert(row >= 0 && col >= 0 && row < arr.GetRowCount() && col < arr.GetColCount());

                _value = arr[row, col];
                _row = row;
                _col = col;
            }
        }

        public static int GetRowCount<T>(this T[,] arr)
        {
            return arr.GetLength(0);
        }

        public static int GetColCount<T>(this T[,] arr)
        {
            return arr.GetLength(1);
        }

        public static IEnumerable<Item<T>> GetCol<T>(this T[,] arr, int col)
        {
            for (int i = 0; i < arr.GetRowCount(); i++)
            {
                yield return new Item<T>(arr, i, col);
            }
        }

        public static IEnumerable<IEnumerable<Item<T>>> GetAllCols<T>(this T[,] arr)
        {
            for (int i = 0; i < arr.GetColCount(); i++)
            {
                yield return arr.GetCol(i);
            }
        }

        public static IEnumerable<Item<T>> GetRow<T>(this T[,] arr, int row)
        {
            for (int i = 0; i < arr.GetColCount(); i++)
            {
                yield return new Item<T>(arr, row, i);
            }
        }

        public static IEnumerable<IEnumerable<Item<T>>> GetAllRows<T>(this T[,] arr)
        {
            for (int i = 0; i < arr.GetRowCount(); i++)
            {
                yield return arr.GetRow(i);
            }
        }

        public static IEnumerable<Item<T>> GetRightDioganal<T>(this T[,] arr, int row, int col)
        {
            while (row < arr.GetRowCount() && col < arr.GetColCount())
            {
                yield return new Item<T>(arr, row, col);
                ++row;
                ++col;
            }
        }

        public static IEnumerable<IEnumerable<Item<T>>> GetAllRightDioganals<T>(this T[,] arr)
        {
            foreach (var item in arr.GetCol(0).Reverse().Skip(1)          // first col items skip last
                        .Concat(arr.GetRow(0).Skip(1).Reverse().Skip(1))  // first row items skip first and last
                    )
            {
                yield return arr.GetRightDioganal(item.Row, item.Col);
            }
        }

        public static IEnumerable<Item<T>> GetLeftDioganal<T>(this T[,] arr, int row, int col)
        {
            while (row < arr.GetRowCount() && col >= 0)
            {
                yield return new Item<T>(arr, row, col);
                ++row;
                --col;
            }
        }

        public static IEnumerable<IEnumerable<Item<T>>> GetAllLeftDioganals<T>(this T[,] arr)
        {
            foreach (var item in arr.GetRow(0).Skip(1)                                                   // first row items skip first
                                    .Concat(arr.GetCol(arr.GetColCount() - 1).Skip(1).Reverse().Skip(1)) // last col skip first and last
                    )
            {
                yield return arr.GetLeftDioganal(item.Row, item.Col);
            }
        }
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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