/// <summary> /// Returns an array containing the cumulative sum of frequencies at specified <see cref="Position"/> in specified /// <see cref="FrequencyMap{T}"/> value collection. /// </summary> /// <param name="map"><see cref="FrequencyMap{T}"/> whose cumulative sum of frequencies to get for /// <paramref name="position"/>.</param> /// <param name="position"><see cref="Position"/> in <paramref name="map"/>'s value collection to /// consider.</param> /// <returns>An array containing the cumulative sum of frequencies at <paramref name="position"/> in /// <paramref name="map"/>.</returns> public int[] GetBuckets(FrequencyMap <T> map, Position position) { int[] buckets = new int[map.Count]; int sum = 0; int index = 0; StateFrequency frequency; int value; foreach (var pair in map) { frequency = pair.Value; value = Math.Max(_minFrequency, frequency.GetValue(position)); sum += value; buckets[index++] = sum; } return(buckets); }
/// <summary> /// Gets a random <typeparamref name="T"/> key from specified <see cref="FrequencyMap{T}"/> based on all values at /// specified <see cref="Position"/> in map's frequencies. /// </summary> /// <param name="map"><see cref="FrequencyMap{T}"/> used for issuing values.</param> /// <param name="position"><see cref="Position"/> in <paramref name="map"/>'s frequencies to consider issuing /// values for.</param> /// <returns>A random <see cref="T"/> value from <paramref name="map"/>'s keys based on frequencies at /// <paramref name="position"/> in the map.</returns> /// <exception cref="NullReferenceException"><paramref name="map"/> is null.</exception> public T GetValue(FrequencyMap <T> map, Position position) { int[] buckets = GetBuckets(map, position); int length = buckets.Length; int total = buckets[length - 1]; int value = _random.Next(0, total); int index = 0; for (; index < length; index++) { if (value < buckets[index]) { break; } } return(map.Keys.ToList()[index]); }