01: /*
02: * Copyright 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package com.google.gwt.user.client;
17:
18: /**
19: * This class can be used as a substitute for {@link java.util.Random}. The
20: * semantics differ in that the underlying browser's implementation is used. The
21: * random generator cannot be seeded or otherwise used to reproduce a particular
22: * sequence of results.
23: */
24: public final class Random {
25:
26: /**
27: * Returns true or false with roughly equal probability. The underlying
28: * browser's random implementation is used.
29: */
30: public static native boolean nextBoolean() /*-{
31: return Math.random() < 0.5;
32: }-*/;
33:
34: /**
35: * Returns a random <code>double</code> between 0 (inclusive) and 1
36: * (exclusive). The underlying browser's random implementation is used.
37: */
38: public static native double nextDouble() /*-{
39: return Math.random();
40: }-*/;
41:
42: /**
43: * Returns a random <code>int</code> between -2147483648 and 2147483647
44: * (inclusive) with roughly equal probability of returning any particular
45: * <code>int</code> in this range. The underlying browser's random
46: * implementation is used.
47: */
48: public static native int nextInt() /*-{
49: // "~~" forces the value to a 32 bit integer.
50: return ~~(Math.floor(Math.random() * 4294967296) - 2147483648);
51: }-*/;
52:
53: /**
54: * Returns a random <code>int</code> between 0 (inclusive) and
55: * <code>upperBound</code> (exclusive) with roughly equal probability of
56: * returning any particular <code>int</code> in this range. The underlying
57: * browser's random implementation is used.
58: */
59: public static native int nextInt(int upperBound) /*-{
60: // "~~" forces the value to a 32 bit integer.
61: return ~~(Math.floor(Math.random() * upperBound));
62: }-*/;
63:
64: /**
65: * Not instantiable. Having different instances of this class would not be
66: * meaningful because no state is stored and the common browser implementation
67: * is shared.
68: */
69: private Random() {
70: }
71: }
|