1

If I run this code in c#, The output generated is Two random strings which changes for every execution. But the Java code always print 'Hello World'.

 static void Main(string[] args)
        {
           Console.WriteLine(randomString(-229985452) + " " + randomString(-147909649));
           Console.ReadLine();
        }
        public static String randomString(int i)
        {
            Random ran = new Random(i);
            StringBuilder sb = new StringBuilder();
            for (int n = 0; ; n++)
            {
                int k = ran.Next(27);
                if (k == 0)
                    break;

                sb.Append((char)('`' + k));

            }

            return sb.ToString();
        }

But the same code in Java prints 'Hello World'. Why these languages act differently?

The Java code

System.out.println(randomString(-229985452) + " " + randomString(-147909649));

Its Method

public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}
Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
  • 1
    In .Net 4.5 this would generate the *hello world* string : `Console.WriteLine(RandomString(1095915106) + " " + RandomString(-852581083));` – Floris Sep 01 '14 at 13:20

2 Answers2

14

Nope, the .NET version always gives the same output - "terkcq onbmmjujsrb".

It's not "Hello World" because the random number generator in .NET doesn't use the same algorithm as the one in Java, but in both cases you're starting with the same seeds each time, so you're getting the same sequence of random numbers. The seeds happen to be chosen such that in Java you end up with "Hello World". There may be seeds which give the same results in .NET (while probably messing up the Java output of course).

From the docs for the .NET Random constructor taking a seed:

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers.

If your application requires different random number sequences, invoke this constructor repeatedly with different seed values.

(It's not documented whether the algorithm has been kept stable for all versions of .NET, admittedly.)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    The docs do state that you should not rely on the algorithm being stable. It has definitely changed in past, as evidenced by this question: http://stackoverflow.com/questions/9758472/implementation-change-to-nets-random – Mike Zboray Mar 07 '13 at 07:55
0

It relies on java.util.Random using a specific algorithm and using the seed in a specific way, which clearly C# does not share.

user207421
  • 305,947
  • 44
  • 307
  • 483