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();
}
asked Mar 7, 2013 at 6:15
1
  • 1
    In .Net 4.5 this would generate the hello world string : Console.WriteLine(RandomString(1095915106) + " " + RandomString(-852581083)); Commented Sep 1, 2014 at 13:20

2 Answers 2

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.)

answered Mar 7, 2013 at 6:19

1 Comment

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: stackoverflow.com/questions/9758472/…
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.

answered Mar 7, 2013 at 6:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.