Esempio n. 1
0
        /// <summary>
        ///  A new instance of the WeightedSampler class.
        /// </summary>
        /// <param name="random">A random number generator. If nothing is passed, a
        /// new one is created.</param>
        public WeightedSampler(Random?random = null)
        {
            _entries     = new SortedDictionary <double, T>();
            _totalWeight = 0;

            _random = random ?? new Random();
        }
Esempio n. 2
0
        private static Random CreateInstance()
        {
            var buf = new byte[4];

            globalRandom.GetBytes(buf);
            return(threadRandom = new Random(BitConverter.ToInt32(buf, 0)));
        }
Esempio n. 3
0
        /// <summary>
        /// 配列の要素からランダムに値を選び出します。
        /// </summary>
        /// <typeparam name="T">配列の要素の型。</typeparam>
        /// <param name="source">対象となる配列。</param>
        /// <param name="random">乱数クラス。</param>
        /// <returns></returns>
        public static T GetRandomElement <T>(this T[] source, Random?random = null)
        {
            random = random ?? new Random();
            var index = random.Next() % source.Length;

            return(source[index]);
        }
Esempio n. 4
0
        public ThumbTwiddler(Context context, bool dullMode, bool showElapsedTime)
        {
            this.context = context ?? throw new ArgumentNullException(nameof(context));
            if (!context.InteractiveSession)
            {
                dullMode = true;
            }

            twiddler = context.Characters.Twiddler;
            if (twiddler == null || twiddler.Length == 0)
            {
                dullMode     = true;
                twiddleSteps = 0;
            }
            else
            {
                twiddleSteps = twiddler.Length;
            }

            if (!dullMode)
            {
                twiddleInterval = 1000 / twiddler !.Length;
            }
            else
            {
                random          = new Random();
                twiddleInterval = 10000;
            }

            this.dullMode        = dullMode;
            this.showElapsedTime = showElapsedTime;
            twiddleIndex         = 0;
        }
Esempio n. 5
0
        /// <summary>
        /// Iterative shuffle of an array. Modifies initial array. If you don't get what this is doing, do not use it!
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <param name="random">An optional random generator. If left null will use a default static one.</param>
        /// <returns></returns>
        public static T[] ShuffleInplace <T>(this T[] array, Random?random = null)
        {
            if (random == null)
            {
                random = defaultRand;
            }

            int n = array.Length;

            while (n > 0)
            {
                int r    = random.Next(0, n);
                T   temp = array[r];
                array[r]     = array[n - 1];
                array[n - 1] = temp;
                n--;
            }
            return(array);
            //if (n == 0)
            //    return array;
            //else
            //{
            //    array = Shuffle(n - 1, array);
            //    int r = rand.Next(0, n);
            //    T temp = array[r];
            //    array[r] = array[n - 1];
            //    array[n - 1] = temp;
            //    return array;
            //}
        }
Esempio n. 6
0
        public static void TransferBackupSet(bool encrypted, bool cache, Random?random = null, int regFileCount = 100)
        {
            (Core core, Dictionary <string, byte[]> verifyfilepaths,
             MetadataNode vfsroot, BPlusTree <byte[]> vfsdatastore)testdata;
            if (encrypted)
            {
                testdata = InitializeNewCoreWithStandardFiles(0, 1, random, cache, regFileCount);
            }
            else
            {
                testdata = InitializeNewCoreWithStandardFiles(1, 0, random, cache, regFileCount);
            }
            var(srcCore, _, _, _) = testdata;

            if (encrypted)
            {
                testdata = InitializeNewCoreWithStandardFiles(0, 1, random, cache, regFileCount);
            }
            else
            {
                testdata = InitializeNewCoreWithStandardFiles(1, 0, random, cache, regFileCount);
            }
            var(dstCore, _, _, _) = testdata;

            _ = srcCore.RunBackup("test", "run1");

            srcCore.TransferBackupSet(new BackupSetReference("test", false, false, false), dstCore, true);
        }
Esempio n. 7
0
 /// <summary>
 /// Initialize an instance.
 /// </summary>
 /// <param name="random">The random to be used.</param>
 public Coin(Random?random = null)
 {
     lock (providerLocker)
     {
         this.random = random ?? new Random(randomProvider.Next());
     }
 }
        public static void LocalIsThreadStatic()
        {
            Random?t1R1 = null;
            Random?t1R2 = null;
            Random?t2R1 = null;
            Random?t2R2 = null;

            var t1 = new Thread(() =>
            {
                Interlocked.Exchange(ref t1R1, ThreadSafeRandom.Local);
                Interlocked.Exchange(ref t1R2, ThreadSafeRandom.Local);
            });

            var t2 = new Thread(() =>
            {
                Interlocked.Exchange(ref t2R1, ThreadSafeRandom.Local);
                Interlocked.Exchange(ref t2R2, ThreadSafeRandom.Local);
            });

            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();

            Assert.NotNull(t1R1);
            Assert.NotNull(t1R2);
            Assert.NotNull(t2R1);
            Assert.NotNull(t2R2);

            Assert.Same(t1R1, t1R2);
            Assert.Same(t2R1, t2R2);
            Assert.NotSame(t1R1, t2R1);
        }
Esempio n. 9
0
        public static void RemoveBackup(bool encrypted, bool cache, Random?random = null)
        {
            (Core core, Dictionary <string, byte[]> verifyfilepaths,
             MetadataNode vfsroot, BPlusTree <byte[]> vfsdatastore)testdata;
            if (encrypted)
            {
                testdata = InitializeNewCoreWithStandardFiles(0, 1, cache: cache, random: random);
            }
            else
            {
                testdata = InitializeNewCoreWithStandardFiles(1, 0, cache: cache, random: random);
            }
            var(core, _, vfsroot, _) = testdata;

            var bh1 = core.RunBackup("test", "run1");

            //System.Threading.Thread.Sleep(40); // Allow async writes to finish

            vfsroot.AddDirectory("src", VirtualFSInterop.MakeNewDirectoryMetadata("sub"));
            var bh2 = core.RunBackup("test", "run2");

            //System.Threading.Thread.Sleep(40); // Allow async writes to finish

            // Full hash test
            core.RemoveBackup("test", HashTools.ByteArrayToHexViaLookup32(bh1.GetOrThrow()));
            //System.Threading.Thread.Sleep(40); // Allow async writes to finish
            // Just prefix
            core.RemoveBackup("test", HashTools.ByteArrayToHexViaLookup32(bh2.GetOrThrow()).Substring(0, 10));
            // All backups deleted
            Assert.AreEqual(core.GetBackups("test").backups.Count(), 0);
        }
Esempio n. 10
0
        public Player(Game game, int millisecondInterval, Random?random = null)
        {
            this.game   = game ?? throw new ArgumentNullException(nameof(game));
            this.random = random ?? new Random();

            timer          = new Timer(millisecondInterval);
            timer.Elapsed += Timer_Elapsed;
        }
Esempio n. 11
0
 private static int NextRandom()
 {
     if (_rnd == null)
     {
         _rnd = new Random();
     }
     return(_rnd.Next());
 }
Esempio n. 12
0
 public override void Start()
 {
     base.Start();
     _random = new Random();
     _cactus = Image.FromFile(_random.Next(0, 100) > 50
         ? "CSA_GAME/Resources/Cactus/_cactus1.png" : "CSA_GAME/Resources/Cactus/_cactus2.png");
     Transform.Position.X = Engine.Game.Instance.Scene.Width + Offset;
 }
Esempio n. 13
0
        private object?EvaluateCallExpression(BoundCallExpression node)
        {
            if (node.Function is DeclaredFunctionSymbol declaredFunctionSymbol)
            {
                var locals = new Dictionary <VariableSymbol, object>();

                for (var i = 0; i < node.Arguments.Length; i++)
                {
                    var parameter = declaredFunctionSymbol.Parameters[i];
                    var value     = this.EvaluateExpression(node.Arguments[i]) !;

                    locals.Add(parameter, value);
                }

                this.Locals.Push(locals);

                var statement = this.Functions[declaredFunctionSymbol];
                var result    = this.EvaluateStatement(statement);

                _ = this.Locals.Pop();

                return(result);
            }
            else if (node.Function is BuiltinFunctionSymbol builtinFunctionSymbol)
            {
                if (builtinFunctionSymbol == BuiltinFunctions.Input)
                {
                    return(Console.ReadLine());
                }
                else if (builtinFunctionSymbol == BuiltinFunctions.Print)
                {
                    var value = this.EvaluateExpression(node.Arguments[0]) !;

                    Console.WriteLine(value);

                    return(null);
                }
                else if (builtinFunctionSymbol == BuiltinFunctions.Rnd)
                {
                    var max = (int)this.EvaluateExpression(node.Arguments[0]) !;

                    if (this.Random == null)
                    {
                        this.Random = new Random();
                    }

                    return(this.Random.Next(max));
                }
                else
                {
                    throw new Exception();
                }
            }
            else
            {
                throw new Exception();
            }
        }
Esempio n. 14
0
    /// <include file='ListExtensions.xml' path='members/member[@name="Random"]'/>
    public static void Random <T>(this IList <T?> values, IList <T?> buffer, Random?random = null)
    {
        random ??= RandomExtensions.RandomExtensions.Random;

        for (int i = 0; i < buffer.Count; i++)
        {
            buffer[i] = values[random.Next(0, values.Count)];
        }
    }
Esempio n. 15
0
 /// <summary>
 /// Shuffles the elements in the source span using the Fisher-Yates algorithm.
 /// </summary>
 /// <typeparam name="T">The element type of the span.</typeparam>
 /// <param name="span">The source span.</param>
 /// <param name="random">
 /// An optional <see cref="Random"/> object to generate random numbers.
 /// </param>
 public static void Shuffle <T>(this Span <T> span, Random?random = null)
 {
     random ??= new Random();
     for (int i = span.Length - 1; i >= 0; i--)
     {
         int j = random.Next(i + 1);
         (span[i], span[j]) = (span[j], span[i]);
     }
 }
Esempio n. 16
0
    public static T[] ShuffleF <T>(this IList <T> source, Random?rng)
    {
        if (source is T[] array)
        {
            return(array.ShuffleF(rng));
        }

        return(source.ShuffleIteratorF(rng ?? new Random()));
    }
Esempio n. 17
0
        static void Main(string[] args)
        {
            int totalHands          = args.Length >= 1 ? Int32.Parse(args[0]) : 973000;
            int degreeOfParallelism = args.Length >= 2 ? Int32.Parse(args[1]) : Environment.ProcessorCount;
            // Console.WriteLine($"Simluating {totalHands} hands with degree of parallelism {degreeOfParallelism}");
            var stopWatch = Stopwatch.StartNew();

            ParallelEnumerable.Range(0, totalHands)
            .WithDegreeOfParallelism(degreeOfParallelism)
            .ForAll((handNumber) =>
            {
                if (random == null)
                {
                    random = new Random();
                }

                var deal = DealTwoHands(random);
                // Console.WriteLine($"Deal: {string.Join(",", deal.Select(card => CardString(card)))}");
                var hands = new List <int>[] { deal.Take(4).ToList(), deal.Skip(4).ToList() };
                // Console.WriteLine($"Hands: {string.Join(",", hands[0].Select(card => CardString(card)))}; {string.Join(",", hands[1].Select(card => CardString(card)))}");
                var playerToPlay       = 0;
                var playCount          = 0;
                var consecutiveGoCount = 0;
                while (hands[0].Count() + hands[1].Count() > 0)
                {
                    var playableCards = hands[playerToPlay].Where(card => playCount + CountingValue(card) <= 31).ToList();
                    // Console.WriteLine($"Playable cards for player {playerToPlay}: {string.Join(",", playableCards.Select(card => CardString(card)))}");
                    if (playableCards.Count() > 0)
                    {
                        var playerToPlayPlay = playableCards[0];
                        hands[playerToPlay].Remove(playerToPlayPlay);
                        playCount += CountingValue(playerToPlayPlay);
                        // Console.WriteLine($"Player {playerToPlay + 1} plays {CardString(playerToPlayPlay)} for {playCount}");
                        consecutiveGoCount = 0;
                    }
                    else
                    {
                        // Console.WriteLine($"Player {playerToPlay} says \"Go!\"");
                        consecutiveGoCount++;
                        if (consecutiveGoCount == 2)
                        {
                            // Console.WriteLine($"Resetting play count to 0.");
                            consecutiveGoCount = 0;
                            playCount          = 0;
                        }
                    }

                    playerToPlay = (playerToPlay + 1) % 2;
                }
            }
                    );

            stopWatch.Stop();
            // Console.WriteLine($"Stopwatch frequency = {Stopwatch.Frequency} Hz");
            Console.WriteLine($"Simulated {totalHands} hands in {1000000000L * stopWatch.ElapsedTicks / Stopwatch.Frequency} ns for {1000000000L * stopWatch.ElapsedTicks / Stopwatch.Frequency / totalHands} ns per hand");
        }
Esempio n. 18
0
 private static void EnsureLocal()
 {
     if (_local is null)
     {
         lock (_global)
         {
             _local = new Random(_global.Next());
         }
     }
 }
Esempio n. 19
0
 public static (byte[] hash, byte[] file) MakeRandomFile(int size, Random?random = null)
 {
     byte[] data = new byte[size];
     if (random == null)
     {
         random = new Random();
     }
     random.NextBytes(data);
     return(Hasher.ComputeHash(data), data);
 }
 public void IterationSetup()
 {
     random      = new Random(7);
     array       = new int[N];
     totalWeight = 0;
     for (int i = 0; i < N; i++)
     {
         array[i]     = i;
         totalWeight += i;
     }
 }
Esempio n. 21
0
        static Random GetRandom()
        {
            var inst = _local;

            if (inst == null)
            {
                byte[] buffer = new byte[4];
                _global.GetBytes(buffer);
                _local = inst = new Random(BitConverter.ToInt32(buffer, 0));
            }
            return(inst);
        }
    internal AnimatedTexture Clone(Random?rand = null)
    {
        var result = new AnimatedTexture(
            Texture,
            Size,
            SpriteOffsets,
            TicksPerFrame,
            (rand is not null) ? (uint)rand.Next(SpriteOffsets.Length * TicksPerFrame) : CurrentTick
            );

        return(result);
    }
Esempio n. 23
0
        public async Task SerializeAsync(Stream stream, DataSegment segment, Random?random = null, CancellationToken token = default)
        {
            // length
            int numsize = s_encoding.GetBytes(segment.Length.ToString(), _buffer);
            await stream.WriteAsync(_buffer.AsMemory().Slice(0, numsize), token);

            stream.WriteByte((byte)',');
            // checksum
            numsize = s_encoding.GetBytes(segment.Checksum.ToString(), _buffer);
            await stream.WriteAsync(_buffer.AsMemory().Slice(0, numsize), token);

            stream.WriteByte((byte)',');
            // payload
            Memory <byte> source = segment.AsMemory();

            // write the entire segment outright if not given random instance
            if (random == null)
            {
                await stream.WriteAsync(source, token);

                return;
            }
            // randomize chunking otherwise
            while (source.Length > 0)
            {
                if (random.NextBoolean(probability: 0.05))
                {
                    stream.WriteByte(source.Span[0]);
                    source = source.Slice(1);
                }
                else
                {
                    // TODO consider non-uniform distribution for chunk sizes
                    int           chunkSize = random.Next(source.Length);
                    Memory <byte> chunk     = source.Slice(0, chunkSize);
                    source = source.Slice(chunkSize);

                    if (random.NextBoolean(probability: 0.9))
                    {
                        await stream.WriteAsync(chunk, token);
                    }
                    else
                    {
                        stream.Write(chunk.Span);
                    }
                }

                if (random.NextBoolean(probability: 0.3))
                {
                    await stream.FlushAsync(token);
                }
            }
        }
    private static async ValueTask <int> RollAsync()
    {
        if (rnd == null)
        {
            rnd = new Random();
        }

        await Task.Delay(500);

        int diceRoll = rnd.Next(1, 7);

        return(diceRoll);
    }
Esempio n. 25
0
        /// <summary>
        /// Shuffles the elements of a list using the specified <see cref="Random"/> instance.
        /// </summary>
        /// <typeparam name="T">The type of the elements in <c>list</c>.</typeparam>
        /// <param name="list">The list to shuffle.</param>
        /// <param name="random">A random number generator to use to shuffle the list. If null, a new random number generator will be used.</param>
        public static void Shuffle <T>(
            [NotNull] this IList <T> list,
            Random?random = null)
        {
            list.CheckArgumentNull(nameof(list));
            random = random ?? new Random();

            for (int i = list.Count - 1; i > 0; i--)
            {
                int swapIndex = random.Next(i + 1);
                list.Swap(i, swapIndex);
            }
        }
Esempio n. 26
0
    /// <include file='ListExtensions.xml' path='members/member[@name="Shuffle"]'/>
    public static void Shuffle <T>(this IList <T?> values, Random?random = null)
    {
        random ??= RandomExtensions.RandomExtensions.Random;

        int count = values.Count;

        while (count > 0)
        {
            int index = random.Next(count--);

            values.Swap(count, index);
        }
    }
        public static void Shuffle <T>(this IList <T> list, Random?random = null)
        {
            var rng = random ?? new Random();

            int n = list.Count;

            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                (list[k], list[n]) = (list[n], list[k]);
            }
        }
Esempio n. 28
0
        internal GrpcChannel(Uri address, GrpcChannelOptions channelOptions) : base(address.Authority)
        {
            _lock            = new object();
            _methodInfoCache = new ConcurrentDictionary <IMethod, GrpcMethodInfo>();

            // Dispose the HTTP client/handler if...
            //   1. No client/handler was specified and so the channel created the client itself
            //   2. User has specified a client/handler and set DisposeHttpClient to true
            _shouldDisposeHttpClient = (channelOptions.HttpClient == null && channelOptions.HttpHandler == null) ||
                                       channelOptions.DisposeHttpClient;

            Address     = address;
            HttpInvoker = channelOptions.HttpClient ?? CreateInternalHttpInvoker(channelOptions.HttpHandler);
            IsWinHttp   = channelOptions.HttpHandler != null?HttpHandlerFactory.HasHttpHandlerType(channelOptions.HttpHandler, "System.Net.Http.WinHttpHandler") : false;

            SendMaxMessageSize        = channelOptions.MaxSendMessageSize;
            ReceiveMaxMessageSize     = channelOptions.MaxReceiveMessageSize;
            MaxRetryAttempts          = channelOptions.MaxRetryAttempts;
            MaxRetryBufferSize        = channelOptions.MaxRetryBufferSize;
            MaxRetryBufferPerCallSize = channelOptions.MaxRetryBufferPerCallSize;
            CompressionProviders      = ResolveCompressionProviders(channelOptions.CompressionProviders);
            MessageAcceptEncoding     = GrpcProtocolHelpers.GetMessageAcceptEncoding(CompressionProviders);
            LoggerFactory             = channelOptions.LoggerFactory ?? NullLoggerFactory.Instance;
            Logger = LoggerFactory.CreateLogger <GrpcChannel>();
            ThrowOperationCanceledOnCancellation = channelOptions.ThrowOperationCanceledOnCancellation;
            _createMethodInfoFunc = CreateMethodInfo;
            ActiveCalls           = new HashSet <IDisposable>();
            if (channelOptions.ServiceConfig is { } serviceConfig)
            {
                RetryThrottling = serviceConfig.RetryThrottling != null?CreateChannelRetryThrottling(serviceConfig.RetryThrottling) : null;

                _serviceConfigMethods = CreateServiceConfigMethods(serviceConfig);
                _random = new Random();
            }

            if (channelOptions.Credentials != null)
            {
                var configurator = new DefaultChannelCredentialsConfigurator();
                channelOptions.Credentials.InternalPopulateConfiguration(configurator, null);

                IsSecure        = configurator.IsSecure;
                CallCredentials = configurator.CallCredentials;

                ValidateChannelCredentials();
            }

            if (!string.IsNullOrEmpty(Address.PathAndQuery) && Address.PathAndQuery != "/")
            {
                Log.AddressPathUnused(Logger, Address.OriginalString);
            }
        }
Esempio n. 29
0
        /// <summary>
        ///     Shuffles the items of a list.
        /// </summary>
        public static void Shuffle <T>(this IList <T> list, Random?random = null)
        {
            random ??= new Random();
            var n = list.Count;

            while (n > 1)
            {
                n--;
                var k     = random.Next(n + 1);
                var value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
Esempio n. 30
0
        private static uint Next()
        {
            var inst = s_local;

            if (inst == null)
            {
                int seed;
                lock (s_global)
                {
                    seed = s_global.Next();
                }
                s_local = inst = new Random(seed);
            }
            return((uint)inst.Next());
        }