コード例 #1
0
        public static readonly IComparer <int[]> COMPARE_INT_ARRAYS = new Int32ArrayComparer(); // ICU4N TODO: API - rename to follow .NET Conventions

        /// <summary>
        /// Compact the set of strings.
        /// </summary>
        /// <param name="source">Set of strings.</param>
        /// <param name="adder">Adds each pair to the output. See the <see cref="IAdder"/> interface.</param>
        /// <param name="shorterPairs">Use abc-d instead of abc-abd.</param>
        /// <param name="moreCompact">Use a more compact form, at the expense of more processing. If false, source must be sorted.</param>
        public static void Compact(ISet <string> source, IAdder adder, bool shorterPairs, bool moreCompact)
        {
            if (!moreCompact)
            {
                string start     = null;
                string end       = null;
                int    lastCp    = 0;
                int    prefixLen = 0;
                foreach (string s in source)
                {
                    if (start != null)
                    { // We have something queued up
                        if (s.RegionMatches(0, start, 0, prefixLen))
                        {
                            int currentCp = s.CodePointAt(prefixLen);
                            if (currentCp == 1 + lastCp && s.Length == prefixLen + Character.CharCount(currentCp))
                            {
                                end    = s;
                                lastCp = currentCp;
                                continue;
                            }
                        }
                        // We failed to find continuation. Add what we have and restart
                        adder.Add(start, end == null ? null
                            : !shorterPairs ? end
                                : end.Substring(prefixLen, end.Length - prefixLen)); // ICU4N: Corrected 2nd parameter
                    }
                    // new possible range
                    start     = s;
                    end       = null;
                    lastCp    = s.CodePointBefore(s.Length);
                    prefixLen = s.Length - Character.CharCount(lastCp);
                }
                adder.Add(start, end == null ? null
                    : !shorterPairs ? end
                        : end.Substring(prefixLen, end.Length - prefixLen)); // ICU4N: Corrected 2nd parameter
            }
            else
            {
                // not a fast algorithm, but ok for now
                // TODO rewire to use the first (slower) algorithm to generate the ranges, then compact them from there.
                // first sort by lengths
                Relation <int, Ranges> lengthToArrays = Relation.Of(new SortedDictionary <int, ISet <Ranges> >(), typeof(SortedDictionary <int, ISet <Ranges> >));
                foreach (string s in source)
                {
                    Ranges item = new Ranges(s);
                    lengthToArrays.Put(item.Length, item);
                }
                // then compact items of each length and emit compacted sets
                foreach (var entry in lengthToArrays.KeyValues)
                {
                    LinkedList <Ranges> compacted = Compact(entry.Key, entry.Value);
                    foreach (Ranges ranges in compacted)
                    {
                        adder.Add(ranges.Start(), ranges.End(shorterPairs));
                    }
                }
            }
        }
コード例 #2
0
ファイル: Calculator.cs プロジェクト: foxy1982/calculator
        public decimal Calculate(string text)
        {
            var query = _queryParser.Parse(text);

            var result = 0m;

            switch (query.Operation)
            {
            case "x":
                result = _multiplier.Multiply(query.FirstNumber, query.SecondNumber);
                break;

            case "+":
                result = _adder.Add(query.FirstNumber, query.SecondNumber);
                break;

            case "-":
                result = _subtractor.Subtract(query.FirstNumber, query.SecondNumber);
                break;

            case "/":
                result = _divider.Divide(query.FirstNumber, query.SecondNumber);
                break;
            }

            return(result);
        }
コード例 #3
0
        public void DoMath()
        {
            switch (selectOperator)
            {
            case "+":
                Console.WriteLine(adder.Add());
                break;

            case "-":
                Console.WriteLine(subtractor.Subtract( ));
                break;

            case "*":
                Console.WriteLine(multiplier.Multiply());
                break;

            case "/":
                Console.WriteLine(divider.Divide());
                break;

            case "^":
                Console.WriteLine(exponenter.Exponent());
                break;

            default:
                break;
            }
        }
コード例 #4
0
        public void TestStaticInterfaceCast()
        {
            IAdder adder = DuckTyping.StaticCast <IAdder>(typeof(StaticAdder));

            Assert.AreEqual(4, adder.Add(2, 2));
            Assert.AreEqual(4, adder.LastTotal);

            adder.LastTotal = 15;
            Assert.AreEqual(15, adder.LastTotal);
        }
コード例 #5
0
        //sum value in enumeration using adder
        public T Sum <T>(IEnumerable <T> values, IAdder <T> adder)
        {
            T result = adder.Zero;

            foreach (var value in values)
            {
                result = adder.Add(result, value);
            }

            return(result);
        }
コード例 #6
0
        public void One_Plus_One_Should_Be_Ignored()
        {
            // Arrange
            int    a     = 1;
            int    b     = 1;
            IAdder adder = Container.GetInstance <IAdder>();
            // Act
            int result = adder.Add(a, b);

            // Assert
            Assert.ShouldEqual(3, result);
        }
コード例 #7
0
        public void One_Plus_One_Should_Equal_Two()
        {
            // Arrange
            int    a     = 1;
            int    b     = 1;
            IAdder adder = Container.GetInstance(typeof(IAdder)) as IAdder;
            // Act
            int result = adder.Add(a, b);

            // Assert
            Assert.ShouldEqual(2, result);
        }
コード例 #8
0
 public T Add(T valueX, T valueY)
 {
     return(_adder.Add(valueX, valueY));
 }
コード例 #9
0
ファイル: MyStartup.cs プロジェクト: Djeda8/.NET-Core
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAdder adder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            Console.WriteLine("3");


            // Hello world middleware
            app.Use(async(ctx, next) =>
            {
                if (ctx.Request.Path == "/hello-world")
                {
                    // Procesa la petición y no permite la ejecución de middlewares posteriores
                    await ctx.Response.WriteAsync("Hello, world!");
                }
                else
                {
                    // Pasa el control al siguiente middleware
                    await next();
                }
            });

            app.Use(async(ctx, next) =>
            {
                if (ctx.Request.Path.ToString().StartsWith("/hello"))
                {
                    // Procesa la petición y no permite la ejecución de otros middlewares
                    await ctx.Response.WriteAsync("Hello, user!");
                }
                else
                {
                    // Pasa la petición al siguiente middleware
                    await next();
                }
            });

            app.Run(async(context) =>
            {
                if (context.Request.Path == "/add")
                {
                    int a = 0, b = 0;
                    int.TryParse(context.Request.Query["a"], out a);
                    int.TryParse(context.Request.Query["b"], out b);

                    //var adder = app.ApplicationServices.GetService<IAdder>();
                    await context.Response.WriteAsync(adder.Add(a, b));
                }
                else
                {
                    await context.Response.WriteAsync($"Try again!");
                }
            });

            // Request Info middleware
            app.Run(async ctx =>
            {
                await ctx.Response.WriteAsync($"Path requested: {ctx.Request.Path}");
            });

            //app.Run(async (context) =>
            //{
            //    var msg = $"Current environment: {env.EnvironmentName}";
            //    await context.Response.WriteAsync(msg);
            //});

            //if (env.IsDevelopment())
            //{
            //    app.Run(async (context) =>
            //    {
            //        await context.Response.WriteAsync("Development environment");
            //    });
            //}
            //else
            //{
            //    app.Run(async (context) =>
            //    {
            //        await context.Response.WriteAsync("No development environment");
            //    });
            //}
        }
コード例 #10
0
 public static int Subtraction(this IAdder adder, int a, int b) //in this case, "this" indicates an extension method
 {
     return(adder.Add(a, -b));
 }
コード例 #11
0
 public double Add(double l, double r)
 {
     return(_adder.Add(l, r));
 }
コード例 #12
0
 public static int Subtraction(this IAdder adder, int a, int b)
 {
     return(adder.Add(a, -b));
 }
コード例 #13
0
        DijkstraShortestPaths <TVertex, TEdge>(
            this IWeightedDirectedGraph <TVertex, TEdge> graph,
            TVertex origin,
            IAdder <TEdge> adder,
            IComparer <TEdge> comparer
            )
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }
            if (origin == null)
            {
                throw new ArgumentNullException(nameof(origin));
            }
            if (adder == null)
            {
                throw new ArgumentNullException(nameof(adder));
            }
            if (comparer == null)
            {
                throw new ArgumentNullException(nameof(comparer));
            }

            if (!graph.Vertices.Contains(origin))
            {
                throw new ArgumentException();
            }

            // Constructs a dictionary which stores the graphs which contain the shortest path from the origin to
            // each of the vertices that is reachable from the origin by iteratively traversing successor endpoints.
            var graphs = new Dictionary <TVertex, IWeightedDirectedGraph <TVertex, TEdge> >();

            // Constructs a dictionary which stores the additions which represent the added edges which in turn
            // represent the shortest path from the origin to each of the vertices when added.
            var accumulations = new Dictionary <TVertex, TEdge>();

            var settledVertices   = new HashSet <TVertex>();
            var unsettledVertices = new HashSet <TVertex> {
                origin
            };

            while (unsettledVertices.Count > 0)
            {
                // Returns the unsettled vertex that is nearest to the origin by finding the shortest of all the
                // accumulated edges which form a path from the origin to each of the unsettled vertices. Calling
                // the `MinBy` method with only one unsettled vertex in the set of unsettled vertices will return
                // that unsettled vertex, hence it will always return the origin during the first iteration over
                // the unsettled vertices set, because the unsettled vertices set will only contain the origin.
                var nearestVertex = unsettledVertices.MinBy(vertex => accumulations[vertex], comparer);

                // Removes the nearest vertex from the set of unvisited vertices.
                unsettledVertices.Remove(nearestVertex);

                // Iterates over each of the successor endpoints of the nearest vertex.
                foreach (var endpoint in graph.SuccessorEndpoints(nearestVertex))
                {
                    // If the vertex of the endpoint is already settled, then continue to the next iteration.
                    if (settledVertices.Contains(endpoint.Vertex))
                    {
                        continue;
                    }

                    // If the dictionary of additions contains an addition for the nearest vertex, then add this
                    // addition and the endpoint edge together in order to calculate a single path from the origin
                    // to the endpoint vertex of the current iteration; otherwise, an addition for the nearest vertex
                    // does not exist so return the endpoint edge without adding.
                    var currentPath = accumulations.ContainsKey(nearestVertex)
                        ? adder.Add(accumulations[nearestVertex], endpoint.Edge)
                        : endpoint.Edge;

                    // Returns true if the dictionary of additions contains the endpoint vertex and the current path
                    // is less than the existing shortest path from the origin to the endpoint vertex; otherwise,
                    // false. The existing shortest path is taken from the addition of each of the endpoints from
                    // the origin to the endpoint vertex which represent the existing shortest path when added.
                    bool IsCurrentPathLessThanShortestPath()
                    {
                        return(accumulations.ContainsKey(endpoint.Vertex) &&
                               comparer.Compare(currentPath, accumulations[endpoint.Vertex]) < 0);
                    }

                    // If the dictionary of graphs does not contain a graph for the endpoint vertex or the current
                    // path is less than the existing shortest path, then update the graph of the endpoint vertex.
                    if (!graphs.ContainsKey(endpoint.Vertex) || IsCurrentPathLessThanShortestPath())
                    {
                        // If the dictionary of graphs contains a graph for the nearest vertex, then a shortest path
                        // from the origin to the nearest vertex already exists so return a copy of this graph;
                        // otherwise, such a shortest path does not exist so return a new empty graph.
                        var currentGraph = graphs.ContainsKey(nearestVertex)
                            ? graphs[nearestVertex].EndpointPairs.ToGraph()
                            : new WeightedDirectedGraph <TVertex, TEdge>();

                        // Adds an edge from the nearest vertex to the vertex of the endpoint. This means that the
                        // graph will now contain endpoint pairs from the origin to the endpoint vertex.
                        currentGraph.AddEdge(nearestVertex, endpoint.Vertex, endpoint.Edge);

                        // Updates the graph of the endpoint vertex with the current graph because the current graph
                        // contains a shorter path from the origin to the endpoint vertex than the existing graph.
                        graphs[endpoint.Vertex] = currentGraph;

                        // Updates the addition of the endpoint vertex with the current path for the same reason.
                        accumulations[endpoint.Vertex] = currentPath;
                    }

                    // Adds the endpoint vertex to the set of unsettled vertices.
                    unsettledVertices.Add(endpoint.Vertex);
                }

                // Adds the nearest vertex to the set of settled vertices.
                settledVertices.Add(nearestVertex);
            }

            return(graphs);
        }
コード例 #14
0
 public virtual int Add(int a, int b) => _adder.Add(a, b);
コード例 #15
0
        private void AssertCanMockInAndOutParamOnMethod(IAdder adder)
        {
            Expect.Once.On(adder).Message("Add").With(3, 5, Is.Out).Will(
                new SetNamedParameterAction("c", 8)
                );

            int outValue;
            adder.Add(3, 5, out outValue);
            Assert.AreEqual(8, outValue, "Outvalue was not set correctly.");
        }
コード例 #16
0
        private void AssertCanMockInAndOutParamWithReturnValueOnMethod(IAdder adder)
        {
            Expect.Once.On(adder).Message("Add").With(4, 7).Will(Return.Value(11));

            int c = adder.Add(4, 7);
            Assert.AreEqual(11, c, "Result was not set correctly.");
        }
コード例 #17
0
ファイル: Calculator.cs プロジェクト: JoshWidzer/SampleCode
 public int AddTwoNumbers(int first, int second)
 {
     return(adder.Add(first, second));
 }
コード例 #18
0
 public int Add(int a, int b)
 {
     return(_adder.Add(a, b));
 }
コード例 #19
0
 public void Handle(int firstNum, int secondNum)
 {
     adder.Add(firstNum, secondNum);
     subtractor.Subtract(firstNum, secondNum);
 }