jeudi 16 mars 2017

Non-repeating Integer within Range (exclude 0) produce repeated integer sequence

Referring to generating random numbers without consecutive repetition, I want to make a non-repeating random integer generator but between 2 to 9 inclusive.

I make good use of the wrapping code from the answer in the above url.

int oldrand = <prior random number>;
int adder = randomNumberGenerator() % 4;
int newrand = (oldrand + adder + 1) % 5;

My code, however,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Random Rand = new Random();
            int oldrand = Rand.Next(0,7);
            //Console.WriteLine(oldrand);
            for (int i=0; i<50;i++) {

            int adder = Rand.Next(0,7) % 7;
            int newrand = (oldrand + adder + 1) % 8+2;
            int newrand2 = (newrand + adder + 1) % 8+2;
            int newrand3 = (newrand2 + adder + 1) % 8+2;
            int newrand4 = (newrand3 + adder + 1) % 8+2;

            Console.WriteLine(newrand);
            Console.WriteLine(newrand2);
            Console.WriteLine(newrand3);
            Console.WriteLine(newrand4);
            oldrand = newrand4;
            Console.WriteLine();
            }
        }
    }

    public class Rand {
        private static readonly Random globalRandom = new Random(); 
        private static readonly object globalLock = new object();

        private static readonly ThreadLocal<Random> threadRandom = new ThreadLocal<Random>(NewRandom);

        public static Random NewRandom() 
        { 
            lock (globalLock) 
            { 
                return new Random(globalRandom.Next()); 
            } 
        }

        public static Random Instance { get { return threadRandom.Value; } }

        public static int Next(int minValue, int maxValue) 
        { 
            return Instance.Next(minValue, maxValue); 
        }

    }
}

generates a strange result:

2
7
4
9

2
3
4
5

2
7
4
9

5
9
5
9

8
7
6
5

3
9
7
5

2
7
4
9

5
9
5
9

5
9
5
9

9
9
9
9

5
9
5
9

7
5
3
9

8
7
6
5

3
9
7
5

9
5
9
5

4
3
2
9

6
3
8
5

2
7
4
9

6
3
8
5

9
5
9
5

As you can see, 5 and 9 repeat like a pattern while in another sequence you see all four 9's.




Aucun commentaire:

Enregistrer un commentaire