Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.CodeDom;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CodeRetreate
- {
- public static class CodeRetreat
- {
- public static int Sum(int a, int b)
- {
- return SumRec(a, b, 0, false);
- }
- public static int Substract(int a, int b)
- {
- return Sum(a, Sum(~b, 1));
- }
- private static int SumRec(int a, int b, int index, bool overflow)
- {
- return IF(index == sizeof(int)*8, () => a, () =>
- {
- var bita = ((a >> index) & 1) == 1;
- var bitb = ((b >> index) & 1) == 1;
- a = IF(bita ^ bitb ^ overflow,
- () => a | (1 << index),
- () => a & ~(1 << index));
- overflow = bita & overflow | bitb & overflow | bita & bitb;
- return SumRec(a, b, index + 1, overflow);
- });
- }
- public static int SumByPairs(int[] array, int l, int r)
- {
- return IF(Substract(r, l) <= 1, () => array[l], () =>
- {
- var centerIndex = (int) Math.Pow(2, Math.Truncate(Math.Log(Substract(r, l), 2)));
- IF(Sum(l, centerIndex) == r, () => centerIndex /= 2, () => { });
- centerIndex = Sum(centerIndex, l);
- var leftValue = SumByPairs(array, l, centerIndex);
- var rightValue = SumByPairs(array, centerIndex, r);
- return IF(leftValue > rightValue,
- () => Substract(leftValue, rightValue),
- () => Sum(leftValue, rightValue));
- });
- }
- public static void IF(bool condition, Action actionIfTrue, Action actionIfFalse)
- {
- var actions = new[] {actionIfFalse, actionIfTrue};
- actions[Convert.ToInt32(condition)]();
- }
- public static T IF<T>(bool condition, Func<T> actionIfTrue, Func<T> actionIfFalse)
- {
- var actions = new[] {actionIfFalse, actionIfTrue};
- return actions[Convert.ToInt32(condition)]();
- }
- }
- class Program
- {
- static void Main()
- {
- var data = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
- var sum = 0;
- for (var i = 0; i < data.Length; i = CodeRetreat.Sum(i, 1))
- sum = CodeRetreat.Sum(sum, data[i]);
- Console.WriteLine(sum);
- var sumAndSubstract = data[0];
- for (var i = 1; i < data.Length; i = CodeRetreat.Sum(i, 1))
- sumAndSubstract = CodeRetreat.IF(data[i] > data[i - 1],
- () => CodeRetreat.Sum(sumAndSubstract, data[i]),
- () => CodeRetreat.Substract(sumAndSubstract, data[i]));
- Console.WriteLine(sumAndSubstract);
- var sumByPairs = CodeRetreat.SumByPairs(data, 0, data.Length);
- Console.WriteLine(sumByPairs);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement