Exemplo n.º 1
0
        private static void Main(string[] args)
        {
            string filePath = GetInputFilePath();

            var       input     = File.ReadLines(filePath).Select(i => long.Parse(i)).ToList();
            int       inputSize = input.Count;
            const int preamble  = 25;

            long[] buffer = new long[preamble];

            var bufferPosition = 0;

            // Load preamble
            for (int i = 0; i < preamble; i++)
            {
                buffer[i] = input[i];
            }

            var searchFor = 0L;

            foreach (var number in input.Skip(preamble))
            {
                Console.WriteLine($"Working on {number}");
                var found = buffer.Any(p1 => buffer.Any(p2 => p1 + p2 == number));
                if (!found)
                {
                    searchFor = number;
                }

                buffer[bufferPosition] = number;
                bufferPosition         = (bufferPosition + 1) % preamble;
            }

            Console.WriteLine($"not found: {searchFor}");

            for (var pos = 0; pos < inputSize; pos++)
            {
                long sum  = 0;
                int  pos2 = pos;

                while (sum < searchFor && input[pos2] < searchFor)
                {
                    sum += input[pos2++];
                }

                if (sum == searchFor)
                {
                    var endpos = pos2 - 1;

                    var range = input.GetRange(pos, endpos - pos);

                    Console.WriteLine($"Found it: {pos} {endpos}, {range.Min()}+{range.Max()}={range.Min() + range.Max()}");
                }
            }
        }
Exemplo n.º 2
0
        private static long FindRepeatSteps(IEnumerable <Body> bodies, long maxSteps = 1000000000)
        {
            var simulator = new MotionSimulator();
            var steps     = new long[] { -1, -1, -1 };

            for (int i = 0; i < 3; i++)
            {
                simulator.Bodies = bodies.Select(b => b.Clone()).ToList();
                var    axis  = (Axis)i;
                string state = simulator.GetAxisState(axis);

                for (long j = 0; j < maxSteps; j++)
                {
                    simulator.Run();
                    if (simulator.GetAxisState(axis) == state)
                    {
                        steps[i] = j + 1;
                        break;
                    }
                }
            }

            if (steps.Any(s => s == -1))
            {
                return(-1);
            }
            return(MathUtils.Lcm(MathUtils.Lcm(steps[0], steps[1]), steps[2]));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Projects Enumeration of Observations from the raw set of Observation entities.
        /// During build:
        /// override the observations start date using the start date of the corresponding visit.
        /// </summary>
        /// <param name="observations">raw set of observations entities</param>
        /// <param name="visitOccurrences">the visit occurrences entities for current person</param>
        /// <param name="observationPeriods">the observation periods entities for current person</param>
        /// <returns>Enumeration of Observation from the raw set of Observation entities</returns>
        public override IEnumerable <Observation> BuildObservations(Observation[] observations,
                                                                    Dictionary <long, VisitOccurrence> visitOccurrences, ObservationPeriod[] observationPeriods)
        {
            var uniqueEntities  = new HashSet <Observation>();
            var patbillEntities = new HashSet <Observation>(new PatbillObservationComparer());

            foreach (var observation in observations)
            {
                var valueAsStringConceptIds = new long[] { 4053609, 40757183, 40757177, 40769091 };
                if (valueAsStringConceptIds.Any(c => c == observation.ConceptId) && string.IsNullOrEmpty(observation.ValueAsString))
                {
                    continue;
                }

                if (!observation.VisitOccurrenceId.HasValue)
                {
                    continue;
                }
                if (!visitOccurrences.ContainsKey(observation.VisitOccurrenceId.Value))
                {
                    continue;
                }

                var visitOccurrence = visitOccurrences[observation.VisitOccurrenceId.Value];


                if (observation.AdditionalFields != null &&
                    observation.AdditionalFields.ContainsKey("serv_day")) // coming from PATBILL
                {
                    SetDate(observation, visitOccurrence, observation.AdditionalFields["serv_day"]);

                    patbillEntities.Add(observation);
                }
                else //patcpt or paticd
                {
                    observation.StartDate = visitOccurrence.StartDate;

                    uniqueEntities.Add(observation);
                }
            }

            foreach (var patbillEntity in patbillEntities)
            {
                yield return(patbillEntity);
            }

            foreach (var uniqueEntity in uniqueEntities)
            {
                yield return(uniqueEntity);
            }
        }
Exemplo n.º 4
0
        private void SeekSecondaryStreams(long offset, SeekOrigin origin)
        {
            var results = new long[SubStreams.Length - 1];

            Parallel.For(1, SubStreams.Length, (i) =>
            {
                results[i - 1] = SubStreams[i].Seek(offset, origin);
            });

            if (results.Any(t => t != offset))
            {
                throw new IOException("Soft-RAID streams out of sync: Different positions after seeking");
            }
        }
Exemplo n.º 5
0
        private void AssertPositions()
        {
            var results = new long[SubStreams.Length];

            Parallel.For(0, SubStreams.Length, (i) =>
            {
                results[i] = SubStreams[i].Position;
            });

            if (results.Any(t => t != results[0]))
            {
                throw new IOException("Soft-RAID streams out of sync: Different positions");
            }
        }
Exemplo n.º 6
0
        public static long findGeometricProgression(long[] numbers, long number, int cratio, Dictionary <long, int> numberFreq)
        {
            long[] progression = new long[3];
            progression[0] = number / cratio;
            progression[1] = number;
            progression[2] = number * cratio;

            if (progression.Any(x => !numbers.Contains(x)))
            {
                return(0);
            }
            else
            {
                return(numberFreq[progression[0]] * numberFreq[progression[2]]);
            }
        }
Exemplo n.º 7
0
    public void calc()
    {
        cin = new Scanner();
        int N = cin.nextInt();
        int K = cin.nextInt();

        long[] s = new long[N];

        for (int i = 0; i < N; i++)
        {
            s[i] = cin.nextLong();
        }

        if (s.Any(x => x == 0))
        {
            Console.WriteLine(N);
            Console.Read();
            return;
        }

        if (K == 0)
        {
            Console.WriteLine(0);
            Console.Read();
            return;
        }

        int  l    = 0;
        int  r    = 0;
        int  res  = 0;
        long prod = 1;

        while (r < N)
        {
            prod *= s[r++];
            while (l < r && prod > K)
            {
                prod /= s[l++];
            }
            res = Math.Max(res, r - l);
        }

        Console.WriteLine(res);
        Console.Read();
    }
Exemplo n.º 8
0
        public CampaignAcivityDetailViewModel GetCampaignActivity(long campaignId)
        {
            var campaignActivities = _campaignActivityRepository.GetByCampaignId(campaignId);

            IEnumerable <CampaignActivityAssignment> campaignActivityAssignments = null;
            var campaignCreatedByIds = new long[0];

            if (campaignActivities != null && campaignActivities.Any())
            {
                var campaignActivityIds = campaignActivities.Select(x => x.Id).ToArray();

                if (campaignActivityIds != null && campaignActivityIds.Any())
                {
                    campaignActivityAssignments = _campaignActivityAssignmentRepository.GetByCampaignActivityIds(campaignActivityIds).ToArray();

                    if (campaignActivityAssignments != null && campaignActivityAssignments.Any())
                    {
                        var activityAssignmentOrgRoleIds = campaignActivityAssignments.Select(x => x.AssignedToOrgRoleUserId).Distinct().ToArray();

                        campaignCreatedByIds = campaignCreatedByIds.Concat(activityAssignmentOrgRoleIds).ToArray();
                    }
                }
            }

            IEnumerable <OrderedPair <long, string> > campaignCreatedByAgentNameIdPair = null;

            if (campaignCreatedByIds != null && campaignCreatedByIds.Any())
            {
                campaignCreatedByAgentNameIdPair = _organizationRoleUserRepository.GetNameIdPairofUsers(campaignCreatedByIds).ToArray();
            }

            var campaign = _campaignRepository.GetById(campaignId);

            var directMailTypes = _directMailTypeRepository.GetAll();

            var activityViewModels = _campaignListModelFactory.GetCampaignActivityViewModel(campaignId, campaignActivities, campaignActivityAssignments, campaignCreatedByAgentNameIdPair, directMailTypes, campaign.IsPublished);

            var model = new CampaignAcivityDetailViewModel()
            {
                Campaign         = campaign,
                CampaignActivity = activityViewModels
            };

            return(model);
        }
Exemplo n.º 9
0
        public static void Solve()
        {
            var(N, W) = Scanner.Scan <int, int>();
            var lim  = (int)2e5 + 2;
            var imos = new long[lim];

            for (var i = 0; i < N; i++)
            {
                var(S, T, P) = Scanner.Scan <int, int, int>();
                imos[S]     -= P;
                imos[T]     += P;
            }

            imos = imos.Cumulate((x, y) => x + y).ToArray();
            var answer = !imos.Any(x => W + x < 0);

            Console.WriteLine(answer ? "Yes" : "No");
        }
Exemplo n.º 10
0
    public void Solve()
    {
        long k;
        long w   = (N + 1) * N / 2;
        long sum = A.Sum();

        if (sum % w != 0)
        {
            Console.WriteLine("NO");
            return;
        }
        k = sum / w;
        long[] d = new long[N];
        for (int i = 0; i < N; i++)
        {
            d[i] = A[i] - A[(i + 1) % N];
        }

        d = d.Select(i => i + k).ToArray();
        if (d.Any(i => i < 0))
        {
            Console.WriteLine("NO");
            return;
        }
        long cnt = 0;

        for (int i = 0; i < N; i++)
        {
            if (d[i] % N != 0)
            {
                Console.WriteLine("NO");
                return;
            }
            cnt += d[i] / N;
        }
        if (cnt != k)
        {
            Console.WriteLine("NO");
        }
        else
        {
            Console.WriteLine("YES");
        }
    }
Exemplo n.º 11
0
        public override long Seek(long offset, SeekOrigin origin)
        {
            lock (mLock)
            {
                var results = new long[SubStreams.Length];

                Parallel.For(0, SubStreams.Length, (i) =>
                {
                    results[i] = SubStreams[i].Seek(offset, origin);
                });

                if (results.Any(t => t != results[0]))
                {
                    throw new IOException("Soft-RAID streams out of sync: Different positions after seeking");
                }

                return(results[0]);
            }
        }
Exemplo n.º 12
0
        public static void Solve()
        {
            var N   = Scanner.Scan <int>();
            var A   = Scanner.ScanEnumerable <long>().ToArray();
            var all = (long)N * (N + 1) / 2;
            var sum = A.Sum();

            if (sum % all != 0)
            {
                Console.WriteLine("NO"); return;
            }

            var k = sum / all;
            var d = new long[N];

            for (var i = 0; i < N; i++)
            {
                d[i] = A[i] - A[(i + 1) % N] + k;
            }

            if (d.Any(x => x < 0))
            {
                Console.WriteLine("NO"); return;
            }

            var count = 0L;

            for (var i = 0; i < N; i++)
            {
                if (d[i] % N != 0)
                {
                    Console.WriteLine("NO");
                    return;
                }

                count += d[i] / N;
            }

            var answer = count == k;

            Console.WriteLine(answer ? "YES" : "NO");
        }
Exemplo n.º 13
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(_, length) = inputStream.ReadValue <int, int>();
            var a         = inputStream.ReadLongArray();
            var adjacents = new long[a.Length - 1];

            for (int i = 0; i < adjacents.Length; i++)
            {
                adjacents[i] = a[i] + a[i + 1];
            }

            if (adjacents.Any(adj => adj >= length))
            {
                yield return("Possible");

                var last = -1;
                for (int i = 0; i < adjacents.Length; i++)
                {
                    if (adjacents[i] >= length)
                    {
                        last = i;
                        break;
                    }
                }

                last += 1; // 1-index
                for (int i = 1; i <= last - 1; i++)
                {
                    yield return(i);
                }
                for (int i = a.Length - 1; i >= last + 1; i--)
                {
                    yield return(i);
                }
                yield return(last);
            }
            else
            {
                yield return("Impossible");
            }
        }
Exemplo n.º 14
0
        public static IEnumerable <IEnumerable <long> > ByteRanges(IDictionary <string, dynamic> env, long size)
        {
            string httpRange = env.ContainsKey("HTTP_RANGE") ? env["HTTP_RANGE"] : null;

            if (httpRange == null)
            {
                return(null);
            }

            var ranges = new long[] { };

            var rangeSpecs = Regex.Split(httpRange, @",\s*");

            foreach (var rangeSpec in rangeSpecs)
            {
                var regex   = new Regex(@"bytes=(\d*)-(\d*)");
                var matches = regex.Matches(rangeSpec);

                if (matches.Count == 0 || matches[0].Groups.Count == 0)
                {
                    return(null);
                }

                var groups = matches[0].Groups;

                if (groups.Count <= 1)
                {
                    return(null);
                }

                var  r0 = groups[1].Value;
                var  r1 = groups[2].Value;
                long r0Value;
                long r1Value;

                if (r0 == string.Empty)
                {
                    if (r1 == string.Empty)
                    {
                        return(null);
                    }

                    // suffix-byte-range-spec, represents trailing suffix of file
                    r0Value = new long[] { size - long.Parse(r1), 0 }.Max <long>();
                    r1Value = size - 1;
                }
                else
                {
                    r0Value = long.Parse(r0);

                    if (r1 == string.Empty)
                    {
                        r1Value = size - 1;
                    }
                    else
                    {
                        r1Value = long.Parse(r1);

                        if (r1Value < r0Value)
                        {
                            // backwards range is syntactically invalid
                            return(null);
                        }

                        if (r1Value >= size)
                        {
                            r1Value = size - 1;
                        }
                    }
                }

                if (r0Value <= r1Value)
                {
                    ranges = CreateRangeArray(r0Value, r1Value);
                }
            }

            return(ranges.Any()
                ? new[] { ranges }
                : new long[][] { });
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            try
            {
                _logger = LogManager.GetCurrentClassLogger();
                var loadDate = DateTime.Now;
                Console.WriteLine("Обновление данных: Start {0}", loadDate.ToString());


                FileUpdater.Instance.UpdateFileInFolder();
                string pathToUpdatedFile = FileUpdater.Instance.GetPathToUpdatedFile();


                string pathToUnarchiveFile = Environment.CurrentDirectory + Settings.Instance.EndingUnarchiveFilePath;
                FileHelper.DeleteFileIfExist(pathToUnarchiveFile);
                FileHelper.BZipUnarchiveFromNewFile(pathToUpdatedFile, pathToUnarchiveFile);


                int countPassportsDataInFile = FileHelper.GetCountLinesFromCVSFile(pathToUnarchiveFile);

                long[] idsActualItems = new long[countPassportsDataInFile - 1];//первый элемент просто текст- пропускаем
                int    lastAddIndex   = 0;



                int currentPage = 0;
                int countPage   = (int)Math.Ceiling((double)countPassportsDataInFile / (double)Settings.Instance.CountLoadetPerPageItems);
                int skip        = 0;

                Task[] tasks = new Task[Settings.Instance.CountThreads];
                for (int i = 0; i < Settings.Instance.CountThreads; i++)
                {
                    tasks[i] = Task.Factory.StartNew(new Action(() =>
                    {
                        while (true)
                        {
                            lock (PageLoker)
                            {
                                if (currentPage >= countPage)
                                {
                                    break;
                                }

                                skip = currentPage * Settings.Instance.CountLoadetPerPageItems + 1;//первый элемент просто текст- пропускаем
                                currentPage++;
                            }
                            string[] unzippedLines = FileReader.ReadCVSFileInParts(pathToUnarchiveFile, skip, Settings.Instance.CountLoadetPerPageItems);

                            var actualItems = Parser.ToExpiredPassports(unzippedLines);

                            foreach (var item in actualItems)
                            {
                                long?id = DBHelper.Instance.IsExist(item);
                                if (id == null)
                                {
                                    id = DBHelper.Instance.AddItem(item);
                                }

                                lock (AddArrayLoker)
                                {
                                    if (lastAddIndex % 100000 == 0)
                                    {
                                        Console.WriteLine($"Обработанно: {lastAddIndex}");
                                    }


                                    idsActualItems[lastAddIndex] = (long)id;
                                    lastAddIndex++;
                                }
                            }
                        }
                    }));
                }
                Task.WaitAll(tasks);



                long[] idsIrrelevantItems = DBHelper.Instance.GetIdActualItems().ToArray().Where(i => !idsActualItems.Any(id => id == i)).ToArray();



                int count = (int)Math.Ceiling((double)idsIrrelevantItems.Length / (double)Settings.Instance.CountUpdateItemsPerRequest);
                for (int i = 0; i < count; i++)
                {
                    DBHelper.Instance.UpdateIrrelevantItems(idsIrrelevantItems.Skip(i * Settings.Instance.CountUpdateItemsPerRequest).Take(Settings.Instance.CountUpdateItemsPerRequest), loadDate);
                }


                FileHelper.DeleteFileIfExist(pathToUnarchiveFile);

                Statistics.Instance.SendStatistics();
                Statistics.Instance.SendMessage("Данные обновлены.");

                Console.WriteLine("Обновление данных завершено: End {0}", DateTime.Now.ToString());
                Console.WriteLine("Затраченно времени: {0}", DateTime.Now - loadDate);
            }
            catch (SettingsException ex)
            {
                _logger.Fatal(ex.ToString() + Environment.NewLine);
                Console.WriteLine("Error! При инициализации ностроек. Проверить App.config!");
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex.ToString() + Environment.NewLine);
                Statistics.Instance.SendMessage("Error! При обновлении данных произошла ошибка.");

                Console.WriteLine("Error! При обновлении данных произошла ошибка.");
            }

            Console.ReadLine();
        }