Example #1
0
        public static int SolveProblem()
        {
            HashSet<int> multiples = new HashSet<int>();
            //Find multples of 3 below 10
            foreach (int i in FindMultiplesBelow(3, 10))
            {
                multiples.Add(i);
            }

            foreach (int i in FindMultiplesBelow(5, 10))
            {
                multiples.Add(i);
            }

            if (multiples.Aggregate((total, i) => total + i) != 23)
            {
                Console.WriteLine("WOOPS -- " + string.Join(", ", multiples));
            }

            multiples.Clear();
            //Find multples of 3 below 10
            foreach (int i in FindMultiplesBelow(3, 1000))
            {
                multiples.Add(i);
            }

            foreach (int i in FindMultiplesBelow(5, 1000))
            {
                multiples.Add(i);
            }
            return multiples.Aggregate((total, i) => total + i);
        }
Example #2
0
        static void Main()
        {
            string s = Console.ReadLine();

            if (s == "INIT")
            {
                foreach (var ship in Battleships.Generate().OrderBy(i => i.Length))
                {
                    var points = new HashSet<string>
                    {
                        ship.Location.ToString(),
                        new Point
                        {
                            X = ship.Location.X + (ship.Orientation == Orientation.Vertical ? ship.Length - 1 : 0),
                            Y = ship.Location.Y + (ship.Orientation == Orientation.Vertical ? 0 : ship.Length - 1),
                        }.ToString()
                    };

                    Console.WriteLine(points.Aggregate((a, b) => a + ":" + b));
                }
            }
            else
            {
                int n = int.Parse(s);

                var board = Enumerable.Range(0, n).Select(i => Console.ReadLine()).ToList();
                var b = new Battleships(new Board(board), new Random());
                b.NextMove();
                Console.WriteLine(b.LastMove);
            }
        }
Example #3
0
        string GetAllTypesAsString(HashSet<string> types)
        {
            // This causes a conflict with the vim keyword 'contains'
            types.Remove("Contains");

            return types.Aggregate("", (current, type) => current + type + " ");
        }
Example #4
0
        public byte[] XmlFilter(byte[] data)
        {
            XDocument xdoc = XDocument.Load(XmlReader.Create(new MemoryStream(data), new XmlReaderSettings(){CloseInput = true}));
            var nodesToRemove = new List<XNode>();
            HashSet<string> removedModuleFeaturesIds = new HashSet<string>();
            HashSet<string> removedModulesIds = new HashSet<string>();

            foreach (var xelement in xdoc.DescendantNodes().OfType<XElement>())
            {
                if (xelement.Name.LocalName.Contains("KeyValueOfModuleID"))
                {
                    ModuleID featureId;
                    var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleID>(n.Value, out featureId)).ToList();
                    if (keys.Count != 0)
                    {
                        nodesToRemove.Add(xelement);
                        keys.ForEach(k => removedModulesIds.Add(k.Value));
                    }
                }
                else if (xelement.Name.LocalName.Contains("KeyValueOfModuleFeatureID"))
                {
                    ModuleFeatureID featureId;
                    var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleFeatureID>(n.Value, out featureId)).ToList();
                    if (keys.Count != 0)
                    {
                        nodesToRemove.Add(xelement);
                        keys.ForEach(k => removedModuleFeaturesIds.Add(k.Value));
                    }
                }
            }

            if (nodesToRemove.Count != 0)
            {
                if (removedModulesIds.Count != 0)
                {
                    var message = "ModuleIds filtered out from configuration:" + removedModulesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
                    SP.SysLog.AddWarn(this, message);
                }
                if (removedModuleFeaturesIds.Count != 0)
                {
                    var message = "ModuleFeatureIds filtered out from configuration:" + removedModuleFeaturesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
                    SP.SysLog.AddWarn(this, message);
                }

                nodesToRemove.ForEach(n => n.Remove());

                var ms = new MemoryStream(data.Length);
                var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings() { WriteEndDocumentOnClose = true, CloseOutput = true });
                xdoc.WriteTo(xmlWriter);
                xmlWriter.Close();
                return ms.ToArray();
            }
            else
            {
                return data;
            }
        }
Example #5
0
        public string Handle(string input, Match match, IListener listener)
        {
            var process = match.Groups[1].Value.ToLower();
            var list = Process.GetProcesses().Where(o => o.ProcessName.ToLower().Contains(process)).ToList();
            var closed = new HashSet<string>();
            foreach (var p in list)
            {
                try
                {
                    p.Kill();
                    closed.Add(p.ProcessName);
                }
                catch(Exception)
                {
                }
            }

            return closed.Aggregate("", (current, close) => current + "I've closed " + close + Environment.NewLine);
        }
Example #6
0
 private void AddNonUniformCandidateInvariant(List<Cmd> cs, Block header)
 {
     var loopNodes = new HashSet<Block>();
     foreach (var b in blockGraph.BackEdgeNodes(header))
       loopNodes.UnionWith(blockGraph.NaturalLoops(header, b));
     var exits = new HashSet<Expr>();
     foreach (var ln in loopNodes) {
       if (ln.TransferCmd is GotoCmd) {
     var gCmd = (GotoCmd) ln.TransferCmd;
     foreach (var exit in gCmd.labelTargets.Cast<Block>()
                          .Where(b => !loopNodes.Contains(b)))
       exits.Add(blockIds[exit]);
       }
       if (ln.TransferCmd is ReturnCmd)
     exits.Add(returnBlockId);
     }
     var curIsHeaderOrExit = exits.Aggregate((Expr)Expr.Eq(cur, blockIds[header]),
                                     (e, exit) => Expr.Or(e, Expr.Eq(cur, exit)));
     cs.Add(prog.CreateCandidateInvariant(
      CreateIfFPThenElse(curIsHeaderOrExit, Expr.Eq(cur, returnBlockId)),
      "non-uniform loop"));
 }
    public bool Write(InstallScript script,
      Func<string, DatabasePackageAction> errorHandler = null,
      Action<int, string> reportProgress = null)
    {
      var cont = true;
      var typeGroups = from l in script.Lines
                       where l.Type == InstallType.Create
                       group l by l.Reference.Type into typeGroup
                       select typeGroup;
      var cnt = typeGroups.Count();
      var idx = 0;
      var packageGroups = new HashSet<string>();
      string currPackageId = null;

      while (cont)
      {
        IEnumerable<IReadOnlyItem> elements;
        foreach (var typeGroup in typeGroups)
        {
          if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Checking for existing package elements ({0} of {1}) ", idx + 1, cnt));

          if (typeGroup.First().Reference.Unique.IsGuid())
          {
            elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
              + typeGroup.Key
              + "</element_type><element_id condition=\"in\">'"
              + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
              + "'</element_id></Item>").Items();
          }
          else
          {
            elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
              + typeGroup.Key
              + "</element_type><element_id condition=\"in\">(select id from innovator.["
              + typeGroup.Key.Replace(' ', '_')
              + "] where "
              + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
              + ")</element_id></Item>").Items();
          }

          packageGroups.UnionWith(elements.Select(e => e.SourceId().Value));
          idx++;
        }

        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><id condition=\"in\">(select SOURCE_ID FROM innovator.PACKAGEGROUP where id in ('"
          + packageGroups.Aggregate((p, c) => p + "','" + c)
          + "'))</id></Item>").Items();
        currPackageId = packages.Where(p => p.Property("name").Value == script.Title).SingleOrDefault().Id();

        cont = false;
        if (packages.Any(p => p.Property("name").Value != script.Title))
        {
          if (errorHandler != null)
          {
            var packageList = (from p in packages
                               where p.Property("name").Value != script.Title
                               select p.Property("name").Value)
                              .Aggregate((p, c) => p + ", " + c);
            switch (errorHandler("The package cannot be created because one or more elements exist in the packages: " + packageList))
            {
              case DatabasePackageAction.TryAgain:
                cont = true;
                break;
              case DatabasePackageAction.RemoveElementsFromPackages:
                foreach (var typeGroup in typeGroups)
                {
                  if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Removing package elements ({0} of {1}) ", idx + 1, cnt));

                  if (typeGroup.First().Reference.Unique.IsGuid())
                  {
                    elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
                      + typeGroup.Key
                      + "' and [PackageElement].[element_id] in ('"
                      + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
                      + "')\" />").Items();
                  }
                  else
                  {
                    elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
                      + typeGroup.Key
                      + "' and [PackageElement].[element_id] in (select id from innovator.["
                      + typeGroup.Key.Replace(' ', '_')
                      + "] where "
                      + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
                      + ")\" />").Items();
                  }

                  idx++;
                }


                break;
              default:
                return false;
            }
          }
          else
          {
            return false;
          }
        }
      }

      // Try one more time to get the package
      if (string.IsNullOrEmpty(currPackageId))
      {
        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><name>" + script.Title + "</name></Item>");
        currPackageId = packages.AssertItem().Id();
      }

      // Add the package
      if (string.IsNullOrEmpty(currPackageId))
      {
        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"add\" ><name>" + script.Title + "</name></Item>", true);
        currPackageId = packages.AssertItem().Id();
      }

      string groupId;
      foreach (var typeGroup in typeGroups)
      {
        if (reportProgress != null) reportProgress((int)(50 + idx * 50.0 / cnt), string.Format("Adding package elements of type ({0} of {1}) ", idx + 1, cnt));

        groupId = _conn.Apply("<Item type=\"PackageGroup\" action=\"merge\" where=\"[PackageGroup].[source_id] = '"
          +  currPackageId
          + "' and [PackageGroup].[name] = '"
          + typeGroup.Key
          + "'\"><name>"
          + typeGroup.Key
          + "</name></Item>", true).AssertItem().Id();

        foreach (var elem in typeGroup)
        {
          _conn.Apply("<Item type=\"PackageElement\" action=\"merge\" where=\"[PackageElement].[source_id] = '"
            + groupId
            + "' and [PackageElement].[element_id] = '"
            + (elem.InstalledId ?? elem.Reference.Unique)
            + "'\">"
            + "<element_type>" + typeGroup.Key + "</element_type>"
            + "<element_id>" + (elem.InstalledId ?? elem.Reference.Unique) + "</element_id>"
            + "<source_id>" + groupId + "</source_id>"
            + "<name>" + elem.Reference.KeyedName + "</name></Item>").AssertNoError();
        }

        idx++;
      }

      return true;
    }
 /// <summary>
 /// Appends strings from a HashSet<string>, separating them with Delimiter
 /// </summary>
 /// <param name="strToAppend">String to append to the file</param>
 /// <param name="Delimiter">Delimiter to append at the end of strToAppend.</param>
 public void AppendHashToDelimitedFile(HashSet<string> hashToAppend, char Delimiter)
 {
     AppendString(hashToAppend.Aggregate((temp, next) => temp + next + Delimiter));
 }
        /// <summary>
        /// This finds the "Aliquot Root": the terminating element of the onward
        /// Aliquot Chain from the number supplied. It works with the Aliquot DB links.
        /// It will deal correctly with arbitrary sized loops, returning the lowest
        /// element in the loop as the "root".
        /// </summary>
        /// <param name="n">Starting point</param>
        /// <returns>Aliquot root, or 0 if no root can be found</returns>
        private BigInteger GetRootOfChain(BigInteger n)
        {
            var aliquotChain = new HashSet<BigInteger>();
              while (true)
              {
            // No onward link - root is undefined
            if(! Links.ContainsKey(n))
            {
              return BigInteger.Zero;
            }

            // We are looping - get minimal element of loop
            if (aliquotChain.Contains(n))
            {
              // Gather the loop
              var aliquotLoop = new HashSet<BigInteger>();
              while(! aliquotLoop.Contains(n))
              {
            aliquotLoop.Add(n);
            n = Links[n].Successor;
              }
              // Calculate and return the smallest element
              var minimumInLoop = aliquotLoop.Aggregate(n, (x, e) => BigInteger.Min(x, e));
              return minimumInLoop;
            } // if: a loop

            BigInteger s = Links[n].Successor;

            // If successor is 1 then it's a prime - this is the root
            if (s == 1)
            {
              return n;
            }

            // add to the chain
            aliquotChain.Add(n);

            // Go to the next element
            n = s;

              } // while: true
        }
Example #10
0
 private Color GetNearestColor(HashSet<Color> palette, Color color)
 {
     return palette
         .Aggregate((a, b) => Color.DistanceSquared(a, color) < Color.DistanceSquared(b, color) ? a : b);
 }
Example #11
0
        public void FillTriangleSelection()
        {
            if (CurrentTriangleSelection.Count == 0)
                return;

            HashSet<Triangle> FillSelect = new HashSet<Triangle>(CurrentTriangleSelection);
            HashSet<Triangle> Frontier = new HashSet<Triangle>(CurrentTriangleSelection);

            while (true)
            {
                HashSet<Triangle> Select = new HashSet<Triangle>();
                float AngleLimit = (float) Math.Cos(SelectionAngle / 180f * Math.PI);
                Vector3 SelectionNormal = new Vector3(0);
                SelectionNormal = FillSelect.Aggregate(SelectionNormal, (current, t) => current + t.VolumeNormal);
                SelectionNormal.Normalize();

                foreach (Triangle t in Frontier)
                    foreach (Triangle n in t.Neighbors)
                        if (n.IsVisible && n.Patch == null && !FillSelect.Contains(n) && Vector3.Dot(SelectionNormal, n.VolumeNormal) >= AngleLimit)
                            Select.Add(n);

                if (Select.Count == 0)
                    break;

                Frontier = Select;
                foreach (var t in Select)
                    FillSelect.Add(t);
            }

            SelectTriangles(FillSelect);
        }
        private static void AddAjaxDataUrlsToElementSet(this HtmlHelper html, IObjectFacade nakedObject, IActionFacade action, TagBuilder fieldSet) {
            var parameters = new HashSet<string>(action.Parameters.SelectMany(p => p.GetChoicesParameters()).Select(t => t.Item1));
            // check the names match 

            IEnumerable<string> matches = from p in parameters
                                          from pp in action.Parameters
                                          where p.ToLower() == pp.Id.ToLower()
                                          select p;

            if (matches.Count() != parameters.Count) {
                string error = String.Format("On choices method Choices{0} one or more parameters in: '{1}' does not match a parameter on : {0}", action.Id, parameters.Aggregate("", (s, t) => s + " " + t));
                throw new ArgumentException(error);
            }

            string parameterNames = parameters.Aggregate("", (s, t) => (s == "" ? "" : s + ",") + html.IdHelper().GetParameterInputId(action, action.Parameters.Single(p => p.Id.ToLower() == t.ToLower())));

            var url = html.GenerateUrl("GetActionChoices", "Ajax", new RouteValueDictionary(new { id = Encode(html.Facade().OidTranslator.GetOidTranslation(nakedObject)), actionName = action.Id }));
            fieldSet.MergeAttribute("data-choices", url);
            fieldSet.MergeAttribute("data-choices-parameters", parameterNames);
        }
        private static void AddAjaxDataUrlsToElementSet(this HtmlHelper html, IObjectFacade nakedObject, TagBuilder fieldSet, PropertyContext parent = null) {
            var parameters = new HashSet<string>(nakedObject.Specification.Properties.SelectMany(p => p.GetChoicesParameters()).Select(t => t.Item1));

            // check the names match 

            var properties = nakedObject.Specification.Properties;
            IEnumerable<string> matches = from p in parameters
                                          from pp in properties
                                          where p.ToLower() == pp.Id.ToLower()
                                          select p;

            if (matches.Count() != parameters.Count) {
                string error = String.Format("On choices method in: {0} one or more properties in: '{1}' does not match a property on that class", nakedObject.Specification.FullName, parameters.Aggregate("", (s, t) => s + " " + t));
                throw new ArgumentException(error);
            }

            string parameterNames = parameters.Aggregate("", (s, t) => (s == "" ? "" : s + ",") + new PropertyContext(html.IdHelper(), nakedObject, nakedObject.Specification.Properties.Single(p => p.Id.ToLower() == t.ToLower()), false, parent).GetFieldInputId());

            string url = html.GenerateUrl("GetPropertyChoices", "Ajax", new RouteValueDictionary(new { id = Encode(html.Facade().OidTranslator.GetOidTranslation(nakedObject)) }));
            fieldSet.MergeAttribute("data-choices", url);
            fieldSet.MergeAttribute("data-choices-parameters", parameterNames);
        }