当前位置: 首页>>代码示例>>C#>>正文


C# IRandom类代码示例

本文整理汇总了C#中IRandom的典型用法代码示例。如果您正苦于以下问题:C# IRandom类的具体用法?C# IRandom怎么用?C# IRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IRandom类属于命名空间,在下文中一共展示了IRandom类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Apply

    public static void Apply(IRandom random, LinearLinkage lle, int n) {
      var grouping = lle.GetGroups().ToList();
      var groupsLargerOne = grouping.Select((v, i) => Tuple.Create(i, v))
                                    .Where(x => x.Item2.Count > 1)
                                    .ToDictionary(x => x.Item1, x => x.Item2);
      if (groupsLargerOne.Count == 0) return;
      var toRemove = new List<int>();

      for (var i = 0; i < n; i++) {
        var g = groupsLargerOne.Keys.SampleRandom(random);
        var idx = random.Next(1, groupsLargerOne[g].Count);
        // shuffle here to avoid a potential bias of grouping smaller and larger numbers together
        var tmp = groupsLargerOne[g].Shuffle(random);
        var before = new List<int>();
        var after = new List<int>();
        foreach (var t in tmp) {
          if (idx > 0) before.Add(t);
          else after.Add(t);
          idx--;
        }
        if (before.Count > 1) groupsLargerOne[grouping.Count] = before;
        grouping.Add(before);
        if (after.Count > 1) groupsLargerOne[grouping.Count] = after;
        grouping.Add(after);
        toRemove.Add(g);
        groupsLargerOne.Remove(g);
        if (groupsLargerOne.Count == 0) break;
      }
      foreach (var r in toRemove.OrderByDescending(x => x))
        grouping.RemoveAt(r);

      lle.SetGroups(grouping);
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:33,代码来源:SplitGroupManipulator.cs

示例2: Apply

    /// <summary>
    /// Performs the rounded blend alpha crossover (BLX-a) of two integer vectors.<br/>
    /// It creates new offspring by sampling a new value in the range [min_i - d * alpha, max_i + d * alpha) at each position i
    /// and rounding the result to the next integer.
    /// Here min_i and max_i are the smaller and larger value of the two parents at position i and d is max_i - min_i.
    /// </summary>
    /// <exception cref="ArgumentException">
    /// Thrown when <paramref name="parent1"/> and <paramref name="parent2"/> are of different length or<br/>
    /// when <paramref name="alpha"/> is less than 0.
    /// </exception>
    /// <param name="random">The random number generator.</param>
    /// <param name="parent1">The first parent for the crossover operation.</param>
    /// <param name="parent2">The second parent for the crossover operation.</param>
    /// <param name="bounds">The bounds and step size for each dimension (will be cycled in case there are less rows than elements in the parent vectors).</param>
    /// <param name="alpha">The alpha value for the crossover.</param>
    /// <returns>The newly created integer vector resulting from the crossover operation.</returns>
    public static IntegerVector Apply(IRandom random, IntegerVector parent1, IntegerVector parent2, IntMatrix bounds, DoubleValue alpha) {
      if (parent1.Length != parent2.Length) throw new ArgumentException("RoundedBlendAlphaCrossover: The parents' vectors are of different length.", "parent1");
      if (alpha.Value < 0) throw new ArgumentException("RoundedBlendAlphaCrossover: Paramter alpha must be greater or equal than 0.", "alpha");
      if (bounds == null || bounds.Rows < 1 || bounds.Columns < 2) throw new ArgumentException("RoundedBlendAlphaCrossover: Invalid bounds specified.", "bounds");

      int length = parent1.Length;
      var result = new IntegerVector(length);
      double max = 0, min = 0, d = 0, resMin = 0, resMax = 0;
      int minBound, maxBound, step = 1;

      for (int i = 0; i < length; i++) {
        minBound = bounds[i % bounds.Rows, 0];
        maxBound = bounds[i % bounds.Rows, 1];
        if (bounds.Columns > 2) step = bounds[i % bounds.Rows, 2];
        maxBound = FloorFeasible(minBound, maxBound, step, maxBound - 1);

        max = Math.Max(parent1[i], parent2[i]);
        min = Math.Min(parent1[i], parent2[i]);
        d = Math.Abs(max - min);
        resMin = FloorFeasible(minBound, maxBound, step, min - d * alpha.Value);
        resMax = CeilingFeasible(minBound, maxBound, step, max + d * alpha.Value);

        result[i] = RoundFeasible(minBound, maxBound, step, resMin + random.NextDouble() * Math.Abs(resMax - resMin));
      }
      return result;
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:42,代码来源:RoundedBlendAlphaCrossover.cs

示例3: Apply

    public static PotvinPDShiftMove Apply(PotvinEncoding individual, IVRPProblemInstance problemInstance, IRandom rand) {
      List<int> cities = new List<int>();

      IPickupAndDeliveryProblemInstance pdp = problemInstance as IPickupAndDeliveryProblemInstance;
      for (int i = 1; i <= individual.Cities; i++) {
        if (pdp == null || pdp.GetDemand(i) >= 0)
          cities.Add(i);
      }

      if (cities.Count >= 1) {
        int city = cities[rand.Next(cities.Count)];
        Tour oldTour = individual.Tours.Find(t => t.Stops.Contains(city));
        int oldTourIndex = individual.Tours.IndexOf(oldTour);

        int max = individual.Tours.Count;
        if (individual.Tours.Count >= problemInstance.Vehicles.Value)
          max = max - 1;

        int newTourIndex = rand.Next(max);
        if (newTourIndex >= oldTourIndex)
          newTourIndex++;

        return new PotvinPDShiftMove(city, oldTourIndex, newTourIndex, individual);
      } else {
        return null;
      }
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:27,代码来源:PotvinPDShiftSingleMoveGenerator.cs

示例4: RemoveRandomBranch

    public static void RemoveRandomBranch(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, int maxTreeLength, int maxTreeDepth) {
      var allowedSymbols = new List<ISymbol>();
      ISymbolicExpressionTreeNode parent;
      int childIndex;
      int maxLength;
      int maxDepth;
      // repeat until a fitting parent and child are found (MAX_TRIES times)
      int tries = 0;

      var nodes = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).ToList();
      do {
        parent = nodes.SampleRandom(random);

        childIndex = random.Next(parent.SubtreeCount);
        var child = parent.GetSubtree(childIndex);
        maxLength = maxTreeLength - symbolicExpressionTree.Length + child.GetLength();
        maxDepth = maxTreeDepth - symbolicExpressionTree.Root.GetBranchLevel(child);

        allowedSymbols.Clear();
        foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) {
          // check basic properties that the new symbol must have
          if ((symbol.Name != child.Symbol.Name || symbol.MinimumArity > 0) &&
            symbol.InitialFrequency > 0 &&
            parent.Grammar.GetMinimumExpressionDepth(symbol) <= maxDepth &&
            parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength) {
            allowedSymbols.Add(symbol);
          }
        }
        tries++;
      } while (tries < MAX_TRIES && allowedSymbols.Count == 0);

      if (tries >= MAX_TRIES) return;
      ReplaceWithMinimalTree(random, symbolicExpressionTree.Root, parent, childIndex);
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:34,代码来源:RemoveBranchManipulation.cs

示例5: Apply

 /// <summary>
 /// Performs an adaptive normally distributed all position manipulation on the given 
 /// <paramref name="vector"/>.
 /// </summary>
 /// <exception cref="InvalidOperationException">Thrown when the strategy vector is not
 /// as long as the vector to get manipulated.</exception>
 /// <param name="sigma">The strategy vector determining the strength of the mutation.</param>
 /// <param name="random">A random number generator.</param>
 /// <param name="vector">The real vector to manipulate.</param>
 /// <returns>The manipulated real vector.</returns>
 public static void Apply(IRandom random, RealVector vector, RealVector sigma) {
   if (sigma == null || sigma.Length == 0) throw new ArgumentException("ERROR: Vector containing the standard deviations is not defined.", "sigma");
   NormalDistributedRandom N = new NormalDistributedRandom(random, 0.0, 1.0);
   for (int i = 0; i < vector.Length; i++) {
     vector[i] = vector[i] + (N.NextDouble() * sigma[i % sigma.Length]);
   }
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:17,代码来源:FixedNormalAllPositionsManipulator.cs

示例6: PlanetGenerator

 public PlanetGenerator(IMap map, IRandom random)
 {
     _map = map;
     _random = random;
     MaximumMapSize = new Size(10000,10000);
     MaximumPlanetSize = 250;
 }
开发者ID:LucBos,项目名称:DrunkCodingProject,代码行数:7,代码来源:PlanetGenerator.cs

示例7: Manipulate

    protected override void Manipulate(IRandom random, PrinsEncoding individual) {
      List<Tour> tours = individual.GetTours();
      bool improvement = false;
      int iterations = 0;

      do {
        improvement = false;
        double originalQuality = GetQuality(individual);
        PrinsEncoding child = null;

        int samples = 0;
        while (!improvement &&
          samples < SampleSize.Value.Value) {
          int u = random.Next(ProblemInstance.Cities.Value);
          int v = random.Next(ProblemInstance.Cities.Value);

          child = Manipulate(individual,
                originalQuality, u, v);

          improvement = child != null;

          samples++;
        }

        if (improvement) {
          for (int i = 0; i < child.Length; i++) {
            individual[i] = child[i];
          }
        }

        iterations++;
      } while (improvement &&
        iterations < Iterations.Value.Value);
    }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:34,代码来源:PrinsStochasticLSManipulator.cs

示例8: CreateDecorationAt

    private void CreateDecorationAt(Chunk chunk, int blockX, int blockY, int blockZ, IRandom random)
    {
        int offsetX = blockX;
        int offsetY = blockY;
        int numberOfVerticalSegments = BlockSize.Z / 5;
        int diskZ = blockZ;
        int radius = 5;
        BlockType blockType = BlockType.Stone;
        for (int seg = 0; seg < numberOfVerticalSegments; seg++)
        {
            for (int disc = 0; disc < 5; disc++)
            {
                CreateDiskAt(offsetX, offsetY, diskZ, radius, blockType);
                diskZ++;
            }
            if (radius > 1)
            {
                radius--;
                if (radius == 1)
                {
                    blockType = BlockType.Dirt;
                }
            }
        }

        AddGameObjectDecorationToWorld("gray diamond", chunk, new Vector3(blockX + 0.5f, blockY + 0.5f, diskZ + 0.1f),
                                       new Vector3(0, -90, 0));
    }
开发者ID:skistua,项目名称:MinePackage,代码行数:28,代码来源:WeavingRockPillarDecoration.cs

示例9: Apply

    /// <summary>
    /// Performs a breeder genetic algorithm manipulation on the given <paramref name="vector"/>.
    /// </summary>
    /// <param name="random">A random number generator.</param>
    /// <param name="vector">The real vector to manipulate.</param>
    /// <param name="bounds">The lower and upper bound (1st and 2nd column) of the positions in the vector. If there are less rows than dimensions, the rows are cycled.</param>
    /// <param name="searchIntervalFactor">The factor determining the size of the search interval.</param>
    public static void Apply(IRandom random, RealVector vector, DoubleMatrix bounds, DoubleValue searchIntervalFactor) {
      int length = vector.Length;
      double prob, value;
      do {
        value = Sigma(random);
      } while (value == 0);

      prob = 1.0 / (double)length;
      bool wasMutated = false;

      for (int i = 0; i < length; i++) {
        if (random.NextDouble() < prob) {
          double range = bounds[i % bounds.Rows, 1] - bounds[i % bounds.Rows, 0];
          if (random.NextDouble() < 0.5) {
            vector[i] = vector[i] + value * searchIntervalFactor.Value * range;
          } else {
            vector[i] = vector[i] - value * searchIntervalFactor.Value * range;
          }
          wasMutated = true;
        }
      }

      // make sure at least one gene was mutated
      if (!wasMutated) {
        int pos = random.Next(length);
        double range = bounds[pos % bounds.Rows, 1] - bounds[pos % bounds.Rows, 0];
        if (random.NextDouble() < 0.5) {
          vector[pos] = vector[pos] + value * searchIntervalFactor.Value * range;
        } else {
          vector[pos] = vector[pos] - value * searchIntervalFactor.Value * range;
        }
      }
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:40,代码来源:BreederGeneticAlgorithmManipulator.cs

示例10: Apply

    public static AlbaLambdaInterchangeMove Apply(AlbaEncoding individual, int cities, int lambda, IRandom rand) {
      List<Tour> tours = individual.GetTours();

      if (tours.Count > 1) {
        int route1Index = rand.Next(tours.Count);
        Tour route1 = tours[route1Index];

        int route2Index = rand.Next(tours.Count - 1);
        if (route2Index >= route1Index)
          route2Index += 1;

        Tour route2 = tours[route2Index];

        int length1 = rand.Next(Math.Min(lambda + 1, route1.Stops.Count + 1));
        int index1 = rand.Next(route1.Stops.Count - length1 + 1);

        int l2Min = 0;
        if (length1 == 0)
          l2Min = 1;
        int length2 = rand.Next(l2Min, Math.Min(lambda + 1, route2.Stops.Count + 1));
        int index2 = rand.Next(route2.Stops.Count - length2 + 1);

        return new AlbaLambdaInterchangeMove(route1Index, index1, length1, route2Index, index2, length2, individual);
      } else {
        return new AlbaLambdaInterchangeMove(0, 0, 0, 0, 0, 0, individual);
      }
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:27,代码来源:AlbaStochasticLambdaInterchangeSingleMoveGenerator.cs

示例11: Apply

    /// <summary>
    /// Mixes the elements of the given <paramref name="permutation"/> randomly 
    /// in a randomly chosen interval.
    /// </summary>
    /// <param name="random">The random number generator.</param>
    /// <param name="permutation">The permutation to manipulate.</param>
    public static void Apply(IRandom random, Permutation permutation) {
      int breakPoint1, breakPoint2;
      int[] scrambledIndices, remainingIndices, temp;
      int selectedIndex, index;

      breakPoint1 = random.Next(permutation.Length - 1);
      breakPoint2 = random.Next(breakPoint1 + 1, permutation.Length);

      scrambledIndices = new int[breakPoint2 - breakPoint1 + 1];
      remainingIndices = new int[breakPoint2 - breakPoint1 + 1];
      for (int i = 0; i < remainingIndices.Length; i++) {  // initialise indices
        remainingIndices[i] = i;
      }
      for (int i = 0; i < scrambledIndices.Length; i++) {  // generate permutation of indices
        selectedIndex = random.Next(remainingIndices.Length);
        scrambledIndices[i] = remainingIndices[selectedIndex];

        temp = remainingIndices;
        remainingIndices = new int[temp.Length - 1];
        index = 0;
        for (int j = 0; j < remainingIndices.Length; j++) {
          if (index == selectedIndex) {
            index++;
          }
          remainingIndices[j] = temp[index];
          index++;
        }
      }

      Apply(permutation, breakPoint1, scrambledIndices);
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:37,代码来源:ScrambleManipulator.cs

示例12: Manipulate

    protected override void Manipulate(IRandom random, GVREncoding individual) {
      Tour tour = individual.Tours[random.Next(individual.Tours.Count)];
      int breakPoint1 = random.Next(tour.Stops.Count);
      int length = random.Next(1, tour.Stops.Count - breakPoint1 + 1);

      List<int> displaced = tour.Stops.GetRange(breakPoint1, length);
      tour.Stops.RemoveRange(breakPoint1, length);
      //with a probability of 1/(2*V) create a new tour, else insert at another position
      if (individual.GetTours().Count > 0 &&
        individual.GetTours().Count < ProblemInstance.Vehicles.Value &&
        random.Next(individual.GetTours().Count * 2) == 0) {
        Tour newTour = new Tour();
        newTour.Stops.InsertRange(0, displaced);

        individual.Tours.Add(newTour);
      } else {
        Tour newTour = individual.Tours[random.Next(individual.Tours.Count)];
        int newPosition = newTour.Stops.Count;

        newTour.Stops.InsertRange(newPosition, displaced);
      }

      if (tour.Stops.Count == 0)
        individual.Tours.Remove(tour);
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:25,代码来源:GVRDisplacementManipulator.cs

示例13: DeleteSubroutine

    public static bool DeleteSubroutine(
      IRandom random,
      ISymbolicExpressionTree symbolicExpressionTree,
      int maxFunctionDefinitions, int maxFunctionArguments) {
      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>().ToList();

      if (!functionDefiningBranches.Any())
        // no ADF to delete => abort
        return false;

      var selectedDefunBranch = functionDefiningBranches.SampleRandom(random);
      // remove the selected defun
      int defunSubtreeIndex = symbolicExpressionTree.Root.IndexOfSubtree(selectedDefunBranch);
      symbolicExpressionTree.Root.RemoveSubtree(defunSubtreeIndex);

      // remove references to deleted function
      foreach (var subtree in symbolicExpressionTree.Root.Subtrees.OfType<SymbolicExpressionTreeTopLevelNode>()) {
        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
                                    where symb.FunctionName == selectedDefunBranch.FunctionName
                                    select symb).SingleOrDefault();
        if (matchingInvokeSymbol != null) {
          subtree.Grammar.RemoveSymbol(matchingInvokeSymbol);
        }
      }

      DeletionByRandomRegeneration(random, symbolicExpressionTree, selectedDefunBranch);
      return true;
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:28,代码来源:SubroutineDeleter.cs

示例14: Randomize

 public virtual void Randomize(IRandom random, int startIndex, int length) {
   if (length > 0) {
     for (int i = 0; i < length; i++)
       array[startIndex + i] = random.Next(2) == 0;
     OnReset();
   }
 }
开发者ID:t-h-e,项目名称:HeuristicLab,代码行数:7,代码来源:BinaryVector.cs

示例15: Apply

    public static LinearLinkage Apply(IRandom random, ItemArray<LinearLinkage> parents) {
      var len = parents[0].Length;

      var child = new LinearLinkage(len);
      var childGroup = new List<HashSet<int>>();
      var currentParent = random.Next(parents.Length);
      var groups = parents.Select(x => x.GetGroups().Select(y => new HashSet<int>(y)).ToList()).ToList();
      bool remaining;
      do {
        var maxGroup = groups[currentParent].Select((v, i) => Tuple.Create(i, v))
          .MaxItems(x => x.Item2.Count)
          .SampleRandom(random).Item1;
        var group = groups[currentParent][maxGroup];
        groups[currentParent].RemoveAt(maxGroup);
        childGroup.Add(group);

        remaining = false;
        for (var p = 0; p < groups.Count; p++) {
          for (var j = 0; j < groups[p].Count; j++) {
            foreach (var elem in group) groups[p][j].Remove(elem);
            if (!remaining && groups[p][j].Count > 0) remaining = true;
          }
        }

        currentParent = (currentParent + 1) % parents.Length;
      } while (remaining);

      child.SetGroups(childGroup);
      return child;
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:30,代码来源:GreedyPartitionCrossover.cs


注:本文中的IRandom类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。