Esempio n. 1
0
        public Program(string inputFile, string outputFile)
        {
            io = new IOHelper(inputFile, outputFile, Encoding.Default);

            sizeOfEach = new List <int>();
            sizeOfEach.Add(0);
            n   = io.NextInt(); m = io.NextInt(); k = io.NextInt();
            map = new string[n];
            foreach (int i in E.Range(0, n))
            {
                map[i] = io.NextToken();
            }
            vis = new int[n, m];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (map[i][j] != '*' && vis[i, j] == 0)
                    {
                        sizeOfEach.Add(bfs(new Point(i, j)));
                    }
                }
            }
            for (; k-- > 0;)
            {
                int xi = io.NextInt();
                int yi = io.NextInt();
                --xi; --yi;
                io.WriteLine(sizeOfEach[vis[xi, yi]]);
            }

            io.Dispose();
        }
Esempio n. 2
0
        public static CylinderComponent[] CreateNonLinear(int count, double r1, double r2, double r3)
        {
            Contract.Requires(count >= 2);
            Contract.Requires(r1 > 0);
            Contract.Requires(r2 > 0);
            Contract.Requires(r3 > 0);
            Contract.Ensures(Contract.Result <CylinderComponent[]>() != null);
            Contract.Ensures(Contract.Result <CylinderComponent[]>().Length == count);
            Contract.Ensures(Contract.Result <CylinderComponent[]>()[0].Radius == r1);
            Contract.Ensures(NumericUtils.AreRelativeClose(Contract.Result <CylinderComponent[]>().Last().Radius, r3, maxFraction: 1E-5));

            // coefficients of a quadratic function r(t) = a + bt + ct² such that
            // r(0) = r1, r(0.5) = r2, r(1) = r3.
            var a = r1;
            var b = -r3 + 4 * r2 - 3 * r1;
            var c = 2 * r3 - 4 * r2 + 2 * r1;

            // create a set of radii according to the above function.
            var resultQuery =
                from i in Enumerable.Range(0, count)
                let t                 = i / (double)(count - 1)
                                let r = a + b * t + c * t * t
                                        select new CylinderComponent(r, t);

            return(resultQuery.ToArray());
        }
        public void SimpleChunkingShouldReturnPredefined()
        {
            var x          = Enumerable.Range(1, 7);
            var chunkCount = x.TakeChunks(3).Count();

            chunkCount.Should().Be(3);
        }
Esempio n. 4
0
    static void Main(string[] args)
    {
        string[] temp = System.Console.ReadLine().Split(' ');
        int      N    = int.Parse(temp[0]);
        int      M    = int.Parse(temp[1]);

        string[] temp1  = System.Console.ReadLine().Split(' ');
        int[]    target = new int[M];
        for (int i = 0; i < M; i++)
        {
            target[i] = int.Parse(temp1[i]);
        }
        Array.Sort(target);
        int[] distance = new int[target.Length];
        for (int i = 1; i < target.Length; i++)
        {
            distance[i] = target[i] - target[i - 1];
        }
        var dsDesc = E.Range(0, distance.Length).ToArray();

        Array.Sort(distance.ToArray(), dsDesc);
        Array.Reverse(dsDesc);

        var k = target.Last() - target.First() - dsDesc.Take(N - 1).Sum(x => distance[x]);

        Console.WriteLine(k);
    }
Esempio n. 5
0
        private static void EnsureFiniteRadii(double[] result)
        {
            var containsFiniteRadius = result.Any(r => !double.IsInfinity(r));

            if (containsFiniteRadius)
            {
                var n = result.Length;
                var firstFiniteIdx = Enumerable.Range(0, n).First(i => !double.IsInfinity(result[i]));
                var lastFiniteIdx  = Enumerable.Range(0, n).Last(i => !double.IsInfinity(result[i]));

                for (int i = 0; i < firstFiniteIdx; ++i)
                {
                    result[i] = result[firstFiniteIdx];
                }
                for (int i = lastFiniteIdx + 1; i < n; ++i)
                {
                    result[i] = result[lastFiniteIdx];
                }
            }
            else
            {
                // we make all radii be a small value (0.01) if no finite radius has been found
                for (int i = 0; i < result.Length; i++)
                {
                    result[i] = 0.01;
                }
            }
        }
Esempio n. 6
0
    public void Solve()
    {
        int N = Reader.Int(), K = Reader.Int(), L = Reader.Int();

        int[][] E1 = Reader.IntTable(K), E2 = Reader.IntTable(L);

        var uf1 = new UnionFind(N);

        foreach (var e in E1)
        {
            uf1.Unite(e[0] - 1, e[1] - 1);
        }

        var uf2 = new UnionFind(N);

        foreach (var e in E2)
        {
            uf2.Unite(e[0] - 1, e[1] - 1);
        }

        var dic = new Dictionary <long, int>();
        Func <int, long> Key = i => (long)N * uf1.Root(i) + uf2.Root(i);

        for (int i = 0; i < N; i++)
        {
            AddDic(dic, Key(i), 1);
        }

        Console.WriteLine(string.Join(" ", Enu.Range(0, N).Select(i => dic[Key(i)])));
    }
Esempio n. 7
0
        public IEnumerable <Annotation> InferAnnotations(NewPrimitive toBeSnapped, SnappedPrimitive toBeAnnotated)
        {
            var toBeAnnotatedCurves = toBeAnnotated.FeatureCurves;
            var candidateTriples    =
                from i in Enumerable.Range(0, toBeAnnotatedCurves.Length)
                from j in Enumerable.Range(i + 1, toBeAnnotatedCurves.Length - i - 1)
                // at this point (i, j) are all the possible pairs of curves without repetitions
                let allExistingCurves = sessionData.FeatureCurves.Except(toBeAnnotatedCurves)
                                        from existingCurve in allExistingCurves
                                        where AreGoodCandidates(toBeAnnotatedCurves[i], toBeAnnotatedCurves[j], existingCurve)
                                        select new
            {
                FistNewCurve   = toBeAnnotatedCurves[i],
                SecondNewCurve = toBeAnnotatedCurves[j],
                ExistingCurve  = existingCurve
            };

            if (candidateTriples.Any())
            {
                var bestCandidate = candidateTriples.Minimizer(triple => ProximityMeasure(triple.FistNewCurve, triple.SecondNewCurve, triple.ExistingCurve));
                var annotation    = new ColinearCenters
                {
                    Elements = UtilsEnumerable.ArrayOf(bestCandidate.FistNewCurve, bestCandidate.SecondNewCurve, bestCandidate.ExistingCurve)
                };
                return(UtilsEnumerable.Singleton(annotation));
            }
            else
            {
                return(Enumerable.Empty <Annotation>());
            }
        }
Esempio n. 8
0
    public void Solve()
    {
        int N = Reader.Int(), L = Reader.Int();
        var A = Reader.IntArray(N);
        int x = Enu.Range(1, N - 1).FirstOrDefault(i => A[i - 1] + A[i] >= L) - 1;

        if (x == -1)
        {
            Console.WriteLine(NG); return;
        }
        Console.WriteLine(OK);
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput())
        {
            AutoFlush = false
        });
        for (int i = 0; i < x; i++)
        {
            Console.WriteLine(i + 1);
        }
        for (int i = N - 2; i > x; i--)
        {
            Console.WriteLine(i + 1);
        }
        Console.WriteLine(x + 1);
        Console.Out.Flush();
    }
Esempio n. 9
0
    public void Solve()
    {
        int N = Reader.Int(), K = Reader.Int();

        E = Enu.Range(0, N).Select(i => new List <int>()).ToArray();

        for (int i = 0; i < N - 1; i++)
        {
            int a = Reader.Int() - 1, b = Reader.Int() - 1;
            E[a].Add(b);
            E[b].Add(a);
        }
        int ans = N;

        for (int start = 0; start < N; start++)
        {
            int bad = 0, best = 0;
            foreach (int next in E[start])
            {
                var count = new int[N];
                DFS(next, start, 1, count);
                for (int c = K / 2 + 1; c < N; c++)
                {
                    bad += count[c];
                }
                if (K % 2 == 1)
                {
                    best = Math.Max(best, count[(K + 1) / 2]);
                }
            }
            ans = Math.Min(ans, bad - best);
        }

        Console.WriteLine(ans);
    }
Esempio n. 10
0
    private long Calc(double lastMin, int[] A, long Mult, out int[] count, out int[] index)
    {
        int  N   = A.Length;
        long sum = 0;

        count = new int[N];
        index = Enu.Range(0, N).ToArray();
        var last = new double[N];

        for (int i = 0; i < N; i++)
        {
            int    L = -1, R = (int)1e9;
            double logA = Math.Log(A[i]);
            while (R - L > 1)
            {
                int    mid = L + R >> 1;
                double val = logA + mid * Math.Log(Mult);
                if (val >= lastMin - 1e-9)
                {
                    R = mid;
                }
                else
                {
                    L = mid;
                }
            }
            sum     += R;
            count[i] = R;
            last[i]  = logA + R * Math.Log(Mult);
        }
        Array.Sort(last, index);

        return(sum);
    }
Esempio n. 11
0
        public IntermFResult FindSequence(string [] query, bool last_query_is_exact = false)
        {
            if (query.Length == 0)
            {
                throw new InterfaceE();                               // <- form of an empty query is [""]  , anythning special to do with ["" , "" , ... ] ???
            }
            if (query.Length == 1)
            {
                return(FindSingle(query[0], exact_query: last_query_is_exact));                          // this stuff is kind of confusing. see : T4_exact_queries()
            }
            // ---
            var sub_res_here = FindSingle(query[0], exact_query: true);

            if (sub_res_here.type == FRType.ambigous_fit || sub_res_here.type == FRType.empty)
            {
                return(sub_res_here);
            }
            // --
            // at this point sub_res_here is unique -> exactly one suggestion with steplength >= 1
            if (!(sub_res_here.suggs.Length == 1 && sub_res_here.suggs[0].steps.Length >= 1))
            {
                throw new Bug(2);
            }

            var sub_res_down = sub_res_here.suggs[0].val.FindSequence(query.Skip(1).ToArray(), last_query_is_exact);
            var own_res      = sub_res_down;                     // assuming shallow copy for structs

            foreach (var i  in E.Range(0, own_res.suggs.Length)) // prepend own step to results at recur up
            {
                own_res.suggs[i].steps = new [] { sub_res_here.suggs[0].steps[0] }.Concat(sub_res_down.suggs[i].steps).ToArray();
            }
            return(own_res);
        }
        /// <summary>
        /// Converts a set of points to a polyline
        /// </summary>
        /// <param name="points">The set of points</param>
        /// <param name="proximityThreshold">The threshold to consider to points "neighbors" on the polyline</param>
        /// <returns>A set of points that approximate the polyline given by <paramref name="points"/></returns>
        public static Point[] Convert(Point[] points, double proximityThreshold)
        {
            Contract.Requires(points != null);
            Contract.Requires(points.Length >= 1);

            Contract.Ensures(Contract.Result <Point[]>() != null);
            Contract.Ensures(Contract.Result <Point[]>().Length >= 1);

            Func <int, int, double> weight = (x, y) => (points[x] - points[y]).Length;
            var graph = GetPointsGraph(points, proximityThreshold);

            // first we find the farthest vertex from any vertex. This will be one endpoint of the path.
            var anyVertex     = 0;
            var distances     = Dijkstra.ComputeDistnces(graph, weight, anyVertex);
            var firstEndpoint = Enumerable.Range(0, distances.Length).Minimizer(i => - distances[i]);

            // now we compute the farthest point from the first endpoint. This will be the second endpoint of the path
            distances = Dijkstra.ComputeDistnces(graph, weight, firstEndpoint);
            var secondEndpoint = Enumerable.Range(0, distances.Length).Minimizer(i => - distances[i]);

            // now we compute the path between two endpoints
            var path = Dijkstra.ComputePath(graph, weight, firstEndpoint, secondEndpoint);

            // convert graph vertices of the path (indices of points) to points
            var result = from i in path
                         select points[i];

            return(result.ToArray());
        }
Esempio n. 13
0
        public static Image ScaledGray(double[,] data)
        {
            var height = data.GetLength(1);
            var width  = data.GetLength(0);
            var flat   = data.Flatten();

            var min = flat.Min();
            var max = flat.Max();

            var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Gray8, null);

            if (max > min)
            {
                for (int row = 0; row < height; ++row)
                {
                    var rowBytesQuery = from col in Enumerable.Range(0, width)
                                        let value = (data[row, col] - min) / (max - min)
                                                    select(byte) Math.Round(255 * value);
                    var rowBytes = rowBytesQuery.ToArray();
                    bitmap.WritePixels(new Int32Rect(0, row, width, 1), rowBytes, width, 0);
                }
            }
            else // the whole image is black
            {
                bitmap.WritePixels(new Int32Rect(0, 0, width, height), new byte[width * height], width, 0);
            }

            return(GetImage(width, height, bitmap));
        }
        public void ExceptExtensionShouldWork()
        {
            var x            = Enumerable.Range(1, 7);
            var x2           = Enumerable.Range(1, 6);
            var filteredList = x.Except(x2);

            filteredList.Count().Should().Be(1);
        }
Esempio n. 15
0
        private IEnumerable <IEnumerable <IEnumerable <(string name, object value)> > > Execute(IDbCommand command)
        {
            using var reader = command.ExecuteReader();

            do
            {
                var values = new object[reader.FieldCount];
                var names  = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();

                // holds the result of a single statement within the query
                var table = new List <(string, object)[]>();
        private static Tuple <int, int>[] GetPointsGraph(Point[] points, double proximityThreshold)
        {
            var searchStructure = new NaivePointsSearchStructure(points);
            var result          =
                from i in Enumerable.Range(0, points.Length)
                let pnt = points[i]
                          from j in FindNearPoints(pnt, searchStructure.GetPointsInRect, proximityThreshold)
                          where i != j
                          select Tuple.Create(i, j);

            return(result.ToArray());
        }
Esempio n. 17
0
    public void Solve()
    {
        int N = Reader.Int();
        var A = Reader.IntArray(N);

        Array.Sort(A, (a, b) => b - a);
        int  L   = Enu.Range(0, N).First(i => i + 1 == N || A[i + 1] <= i + 1);
        int  R   = Enu.Range(L, N).First(i => i + 1 == N || A[i + 1] <= L);
        bool win = (A[L] - L) % 2 == 0 || (R - L) % 2 == 1;

        Console.WriteLine(win ? "First" : "Second");
    }
Esempio n. 18
0
        public void CanReturnAStaticFile()
        {
            using (var server = new HttpServer("http://*:1234/"))
            {
                server.GET("/")
                .Subscribe(ctx => ctx.StaticFileResponse(@"samples\example_1.txt").Send());

                Browser.ExecuteGet("http://localhost:1234")
                .ReadAllContent()
                .Should().Contain(string.Join(Environment.NewLine, Enumerable.Range(1, 9)));
            }
        }
Esempio n. 19
0
    public void Solve()
    {
        Init();
        Queue <List <int> > cand = new Queue <List <int> >(), nextCand;
        Queue <int>         range = new Queue <int>(), nextRange;

        cand.Enqueue(Enu.Range(0, NQ).ToList());
        range.Enqueue(0); range.Enqueue(M);
        var ans = new int[NQ];

        for (; cand.Count > 0; cand = nextCand, range = nextRange)
        {
            nextCand  = new Queue <List <int> >();
            nextRange = new Queue <int>();
            var uf = new UnionFind(N);
            while (cand.Count > 0)
            {
                var who = cand.Dequeue();
                int L = range.Dequeue(), R = range.Dequeue(), mid = L + R >> 1;
                for (int i = L; i < mid; i++)
                {
                    uf.Unite(E[i][0], E[i][1]);
                }
                var next = new[] { new List <int>(), new List <int>() };
                foreach (int i in who)
                {
                    int num = uf.Count(Q[i][0]) + (uf.Same(Q[i][0], Q[i][1]) ? 0 : uf.Count(Q[i][1]));
                    if (num >= Q[i][2])
                    {
                        ans[i] = mid; next[0].Add(i);
                    }
                    else
                    {
                        next[1].Add(i);
                    }
                }
                for (int i = mid; i < R; i++)
                {
                    uf.Unite(E[i][0], E[i][1]);
                }
                if (L == R - 1)
                {
                    who.ForEach(i => ans[i] = R); continue;
                }
                nextCand.Enqueue(next[0]); nextCand.Enqueue(next[1]);
                nextRange.Enqueue(L); nextRange.Enqueue(mid);
                nextRange.Enqueue(mid); nextRange.Enqueue(R);
            }
        }

        Console.WriteLine(string.Join("\n", ans));
    }
Esempio n. 20
0
    public void Solve()
    {
        int N = Reader.Int(), M = Reader.Int(), S = Reader.Int() - 1;
        var E = Enu.Range(0, N).Select(i => new List <int>()).ToArray();

        for (int i = 0; i < M; i++)
        {
            int a = Reader.Int() - 1, b = Reader.Int() - 1;
            E[a].Add(b);
            E[b].Add(a);
        }
        var maxMinV = Enu.Repeat(-1, N).ToArray();

        maxMinV[S] = S;
        var heap = new Heap <long>(true);

        heap.Push(((long)S << 32) + S);

        while (heap.Count > 0)
        {
            long mask = heap.Pop();
            int  val  = (int)(mask >> 32);
            int  at   = (int)mask;
            if (val < maxMinV[at])
            {
                continue;
            }

            foreach (int next in E[at])
            {
                int nextVal = Math.Min(next, val);
                if (nextVal > maxMinV[next])
                {
                    maxMinV[next] = nextVal;
                    heap.Push(((long)nextVal << 32) + next);
                }
            }
        }

        Console.SetOut(new StreamWriter(Console.OpenStandardOutput())
        {
            AutoFlush = false
        });
        for (int i = 0; i < N; i++)
        {
            if (maxMinV[i] >= i)
            {
                Console.WriteLine(i + 1);
            }
        }
        Console.Out.Flush();
    }
Esempio n. 21
0
        public MockBookingService()
        {
            var rng = new Random();

            _IsLogged = (0 == rng.Next(2));

            _Reservations = E.Range(0, rng.Next(1, 2))
                            .Select(idx => new Reservation("RSV" + idx.ToString("D4", CultureInfo.InvariantCulture),
                                                           E.Range(0, rng.Next(1, 4))
                                                           .Select(idx2 => new Segment(
                                                                       new Flight(rng.Next(0, 10000).ToString()), Airports[rng.Next(0, Airports.Length)], Airports[rng.Next(0, Airports.Length)], TariffsBaggage[rng.Next(0, TariffsBaggage.Length)])).ToArray()))
                            .ToArray();
        }
Esempio n. 22
0
        /// <summary>
        /// Zips each element with its index in the source enumeration.
        /// </summary>
        /// <typeparam name="T">Type of elements in the source enumeration</typeparam>
        /// <param name="source">The source enumeration</param>
        /// <param name="offset">An offset value to add to all the indices</param>
        /// <returns>An enumeration of structueres containing items from source with their index + <paramref name="offset"/></returns>
        public static IEnumerable <IndexedItem <T> > ZipIndex <T>(this IEnumerable <T> source, int offset)
        {
            Contract.Requires(source != null);
            Contract.Ensures(Contract.Result <IEnumerable <IndexedItem <T> > >().Count() == source.Count());

            var count = source.Count();

            return
                (from pair in source.Zip(SysEnumerable.Range(offset, count))
                 let index = pair.Item2
                             let value = pair.Item1
                                         select IndexedItem.Create(index, value));
        }
Esempio n. 23
0
    public void Solve()
    {
        int N = Reader.Int(), M = Reader.Int();
        var T    = Reader.IntTable(M);
        var list = Enu.Range(0, N + 1).Select(i => new List <int[]>()).ToArray();

        Array.ForEach(T, t => list[t[1]].Add(t));
        var Q  = list.Select(a => a.ToArray()).ToArray();
        var dp = new int[N + 1, N + 1, N + 1];

        dp[0, 0, 0] = 1;
        int ans = 0;

        Func <int, int, int, bool> OK = (a, b, c) =>
        {
            foreach (var t in Q[c])
            {
                if ((a >= t[0] ? 1 : 0) + (b >= t[0] ? 1 : 0) + 1 != t[2])
                {
                    return(false);
                }
            }
            return(true);
        };

        for (int a = 0, val; a <= N; a++)
        {
            for (int b = a; b <= N; b++)
            {
                for (int c = b; c <= N; c++)
                {
                    if ((val = dp[a, b, c]) > 0)
                    {
                        if (!OK(a, b, c))
                        {
                            continue;
                        }
                        if (c == N)
                        {
                            Add(ref ans, val); continue;
                        }
                        Add(ref dp[a, b, c + 1], val);
                        Add(ref dp[a, c, c + 1], val);
                        Add(ref dp[b, c, c + 1], val);
                    }
                }
            }
        }

        Console.WriteLine(ans);
    }
Esempio n. 24
0
    public void Solve()
    {
        int N = Reader.Int(), K = Reader.Int();
        var S = new long[1].Concat(Reader.IntArray(N).Select(a => (long)a - K)).ToArray();

        for (int i = 1; i <= N; i++)
        {
            S[i] += S[i - 1];
        }
        var  tree = new WaveletTree(S);
        long ans  = Enu.Range(0, N).Sum(i => (long)(N - i) - tree.Rank(i + 1, N + 1, S[i] - 1));

        Console.WriteLine(ans);
    }
Esempio n. 25
0
    public void Solve()
    {
        int N = Reader.Int(), M = Reader.Int(), S = Reader.Int() - 1;
        var E = Enu.Range(0, N).Select(i => new List <int>()).ToArray();

        for (int i = 0; i < M; i++)
        {
            int a = Reader.Int() - 1, b = Reader.Int() - 1;
            E[a].Add(b);
            E[b].Add(a);
        }
        var maxMinV = Enu.Repeat(-1, N).ToArray();

        maxMinV[S] = S;
        var que   = new Queue <int>();
        var inQue = new bool[N];

        que.Enqueue(S);

        while (que.Count > 0)
        {
            int at = que.Dequeue();
            inQue[at] = false;
            foreach (int next in E[at])
            {
                int nextVal = Math.Min(next, maxMinV[at]);
                if (nextVal > maxMinV[next])
                {
                    maxMinV[next] = nextVal;
                    if (!inQue[next])
                    {
                        inQue[next] = true; que.Enqueue(next);
                    }
                }
            }
        }

        Console.SetOut(new StreamWriter(Console.OpenStandardOutput())
        {
            AutoFlush = false
        });
        for (int i = 0; i < N; i++)
        {
            if (maxMinV[i] >= i)
            {
                Console.WriteLine(i + 1);
            }
        }
        Console.Out.Flush();
    }
Esempio n. 26
0
        private static Tuple <Term, Term[]> CreateSGCTerms(SnappedStraightGenCylinder snappedPrimitive, double[] radii, Point spineStart, Point spineEnd)
        {
            var constraints = new Term[] { snappedPrimitive.Axis.NormSquared - 1 };

            if (radii.Length > 0)
            {
                var featureCurveTerms =
                    from item in snappedPrimitive.FeatureCurves.Cast <CircleFeatureCurve>()
                    where item != null
                    where item.SnappedTo != null
                    from term in ProjectionFit.Compute(item)
                    select term;

                var featureCurvesTerm = 0.1 * TermUtils.SafeAvg(featureCurveTerms);

                // the difference between the primitive's radii and the computed radii is minimized
                var radiiApproxTerm = TermUtils.SafeAvg(
                    from i in Enumerable.Range(0, snappedPrimitive.Components.Length)
                    let component = snappedPrimitive.Components[i]
                                    let radius = radii[i]
                                                 select TermBuilder.Power(component.Radius - radius, 2));

                // the smoothness of the primitive's radii (laplacian norm) is minimized
                var radiiSmoothTerm = TermUtils.SafeAvg(
                    from pair in snappedPrimitive.Components.SeqTripples()
                    let r1                                              = pair.Item1.Radius
                                               let r2                   = pair.Item2.Radius
                                                                 let r3 = pair.Item3.Radius
                                                                          select TermBuilder.Power(r2 - 0.5 * (r1 + r3), 2)); // how far is r2 from the avg of r1 and r3

                // we specifically wish to give higher weight to first and last radii, so we have
                // an additional first/last radii term.
                var endpointsRadiiTerm =
                    TermBuilder.Power(radii[0] - snappedPrimitive.Components.First().Radius, 2) +
                    TermBuilder.Power(radii.Last() - snappedPrimitive.Components.Last().Radius, 2);

                // objective - weighed average of all terms
                var objective =
                    radiiApproxTerm +
                    radiiSmoothTerm +
                    featureCurvesTerm +
                    endpointsRadiiTerm;

                return(Tuple.Create(objective, constraints));
            }
            else
            {
                return(Tuple.Create((Term)0, constraints)); // if we can't extract radii approximation, we don't do any snapping
            }
        }
Esempio n. 27
0
    int[] BinarySearch(int N, int Range, Action Init, Action <int> Act, Predicate <int> OK)
    {
        var res = new int[N];
        Queue <List <int> > cand = new Queue <List <int> >(), nextCand;
        Queue <int>         range = new Queue <int>(), nextRange;

        cand.Enqueue(Enu.Range(0, N).ToList());
        range.Enqueue(0); range.Enqueue(Range);

        for (; cand.Count > 0; cand = nextCand, range = nextRange)
        {
            nextCand  = new Queue <List <int> >();
            nextRange = new Queue <int>();
            Init();
            while (cand.Count > 0)
            {
                var who = cand.Dequeue();
                int L = range.Dequeue(), R = range.Dequeue(), mid = L + R >> 1;
                for (int i = L; i < mid; i++)
                {
                    Act(i);
                }
                var next = new[] { new List <int>(), new List <int>() };
                foreach (int i in who)
                {
                    if (OK(i))
                    {
                        next[0].Add(i);
                    }
                    else
                    {
                        next[1].Add(i);
                    }
                }
                for (int i = mid; i < R; i++)
                {
                    Act(i);
                }
                if (R - L == 1)
                {
                    who.ForEach(i => res[i] = R); continue;
                }
                nextCand.Enqueue(next[0]); nextCand.Enqueue(next[1]);
                nextRange.Enqueue(L); nextRange.Enqueue(mid);
                nextRange.Enqueue(mid); nextRange.Enqueue(R);
            }
        }

        return(res);
    }
        /// <summary>
        ///     Returns a random integer
        /// </summary>
        /// <param name="min">Minimum range</param>
        /// <param name="max">Maximum range</param>
        /// <returns>Random Integer</returns>
        public static int Next(int min, int max)
        {
            var list = new List <int>();

            list.AddRange(Enumerable.Range(min, max));

            var mean   = list.Average();
            var stdDev = list.StandardDeviation();

            var v1 = Random.NextDouble();
            var v2 = Random.NextDouble();

            var randStdNormal = System.Math.Sqrt(-2.0 * System.Math.Log(v1)) *
                                System.Math.Sin(2.0 * System.Math.PI * v2);

            return((int)(mean + stdDev * randStdNormal));
        }
Esempio n. 29
0
        public static Image Binary(bool[,] data)
        {
            var height = data.GetLength(0);
            var width  = data.GetLength(1);
            var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Gray8, null);

            for (int row = 0; row < height; ++row)
            {
                var rowBytesQuery = from col in Enumerable.Range(0, width)
                                    select data[row, col] ? (byte)255 : (byte)0;
                var rowBytes = rowBytesQuery.ToArray();
                bitmap.WritePixels(new Int32Rect(0, row, width, 1), rowBytes, width, 0);
            }

            var image = GetImage(width, height, bitmap);

            return(image);
        }
Esempio n. 30
0
        public static CylinderComponent[] Create(int count, double r1, double r2)
        {
            Contract.Requires(count >= 2);
            Contract.Requires(r1 > 0);
            Contract.Requires(r2 > 0);
            Contract.Ensures(Contract.Result <CylinderComponent[]>() != null);
            Contract.Ensures(Contract.Result <CylinderComponent[]>().Length == count);
            Contract.Ensures(Contract.Result <CylinderComponent[]>()[0].Radius == r1);
            Contract.Ensures(Contract.Result <CylinderComponent[]>().Last().Radius == r2);

            var resultQuery =
                from i in Enumerable.Range(0, count)
                let t                 = i / (double)(count - 1)
                                let r = (1 - t) * r1 + t * r2
                                        select new CylinderComponent(r, t);

            return(resultQuery.ToArray());
        }