예제 #1
0
        public static ISnailfishNumber Add(params ISnailfishNumber[] numbers)
        {
            if (numbers.Length == 0)
            {
                return(new SnailfishValue(0));
            }

            var sum = numbers[0];

            for (int i = 1; i < numbers.Length; i++)
            {
                sum = new SnailfishPair(sum, numbers[i]);
                Reduce(sum);
            }

            return(sum);
        }
예제 #2
0
        public static bool Split(ISnailfishNumber num)
        {
            if (num is SnailfishValue)
            {
                return(false);
            }

            Stack <(ISnailfishNumber number, SnailfishPair?parent)> stack = new();

            stack.Push((num, null));

            while (stack.Count > 0)
            {
                (var curr, var parent) = stack.Pop();

                if (curr is SnailfishValue value)
                {
                    if (value.Value >= 10)
                    {
                        int x = value.Value / 2;
                        int y = value.Value / 2 + value.Value % 2;

                        var newValue = new SnailfishPair(x, y);

                        if (parent?.X == curr)
                        {
                            parent.X = newValue;
                        }
                        else if (parent?.Y == curr)
                        {
                            parent.Y = newValue;
                        }
                        return(true);
                    }
                }
                else if (curr is SnailfishPair pair)
                {
                    stack.Push((pair.Y, pair));
                    stack.Push((pair.X, pair));
                }
            }

            return(false);
        }