{C#}算法.解耦

2021-06-23  本文已影响0人  码农猫爸

背景

对策(亲测有效)

namespace AlgorithmDecoupling
{
    class Program
    {
        static void Main(string[] args)
        {
            var demo = new Demo();
            demo.Show();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;

namespace AlgorithmDecoupling
{
    public abstract class Bracket
    {
        protected readonly string Fx;

        protected List<int>
            Lefts = new List<int>(), // 左括号位置清单
            Rights = new List<int>(); // 右括号位置清单

        public Bracket(string fx)
        {
            Fx = fx;
        }

        public void Show()
        {
            Split();

            string method = GetType().Name.ToLower()
                .Replace("bracket", "");
            WriteLine($"*** by {method} ***");
            WriteLine("- at= 0123456789X");
            WriteLine($"- fx= {Fx}");

            WriteLine($"index of left bracket are: ");
            WriteLine("- " + string.Join(",", Lefts));

            WriteLine($"index of right bracket are: ");
            WriteLine("- " + string.Join(",", Rights));

            WriteLine();
            ReadKey();
        }

        protected abstract void Split();
    }

    // 同时提取左右括号
    public class CouplingBracket : Bracket
    {
        public CouplingBracket(string fx) : base(fx) { }

        protected override void Split()
        {
            int at = -1;
            var symbols = new char[] { '(', ')' };

            while (at < Fx.Length)
            {
                at = Fx.IndexOfAny(symbols, ++at);
                if (at == -1) break;

                var indexes = Fx[at] == '('
                    ? Lefts
                    : Rights;
                indexes.Add(at);
            }
        }
    }

    // 分步提取左右括号
    public class DecouplingBracket : Bracket
    {
        public DecouplingBracket(string fx) : base(fx) { }

        protected override void Split()
        {
            Lefts = _Locate('(');
            Rights = _Locate(')');

            // 实现了代码重用
            List<int> _Locate(char search)
                => Fx.Select((x, index) => x == search ? index : -1)
                    .Where(at => at >= 0)
                    .ToList();
        }
    }

    public class Demo
    {
        public void Show()
        {
            string fx = "(a+b)*(c-d)";

            var coupling = new CouplingBracket(fx);
            coupling.Show();

            var decoupling = new DecouplingBracket(fx);
            decoupling.Show();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读