All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.robovm.objc.LongMap Maven / Gradle / Ivy

There is a newer version: 2.3.21
Show newest version
/*******************************************************************************
 * Copyright 2011 See AUTHORS file.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package org.robovm.objc;

import java.util.Iterator;
import java.util.NoSuchElementException;

/*
 * RoboVM note: The LongMap and RandomXS128 classes in this file have been copied
 * from the libGDX project and modified slightly (removed a few things we don't
 * need).
 */

/** An unordered map that uses long keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small
 * stash for problematic keys. Null values are allowed. No allocation is done except when growing the table size. 
*
* This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. * @author Nathan Sweet */ public class LongMap implements Iterable> { @SuppressWarnings("unused") private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; private static final int PRIME3 = 0xced1c241; private static final int EMPTY = 0; public int size; long[] keyTable; V[] valueTable; int capacity, stashSize; V zeroValue; boolean hasZeroValue; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private Entries entries1, entries2; //private Values values1, values2; //private Keys keys1, keys2; /** Returns the next power of two. Returns the specified value if the value is already a power of two. */ // RoboVM note: Inlined from com.badlogic.gdx.math.MathUtils static public int nextPowerOfTwo (int value) { if (value == 0) return 1; value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the * backing table. */ public LongMap () { this(32, 0.8f); } /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing * table. */ public LongMap (int initialCapacity) { this(initialCapacity, 0.8f); } /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items * before growing the backing table. */ @SuppressWarnings("unchecked") public LongMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = /*MathUtils.*/nextPowerOfTwo(initialCapacity); if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); mask = capacity - 1; hashShift = 63 - Long.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2); pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8); keyTable = new long[capacity + stashCapacity]; valueTable = (V[])new Object[keyTable.length]; } /** Creates a new map identical to the specified map. */ public LongMap (LongMap map) { this(map.capacity, map.loadFactor); stashSize = map.stashSize; System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; zeroValue = map.zeroValue; hasZeroValue = map.hasZeroValue; } public V put (long key, V value) { if (key == 0) { V oldValue = zeroValue; zeroValue = value; if (!hasZeroValue) { hasZeroValue = true; size++; } return oldValue; } long[] keyTable = this.keyTable; // Check for existing keys. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == key) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == key) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == key) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } // Update key in the stash. for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } } // Check for empty buckets. if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3); return null; } public void putAll (LongMap map) { for (Entry entry : map.entries()) put(entry.key, entry.value); } /** Skips checks for existing keys. */ private void putResize (long key, V value) { if (key == 0) { zeroValue = value; hasZeroValue = true; return; } // Check for empty buckets. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } push(key, value, index1, key1, index2, key2, index3, key3); } static public RandomXS128 random = new RandomXS128(); private void push (long insertKey, V insertValue, int index1, long key1, int index2, long key2, int index3, long key3) { long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; // Push keys until an empty bucket is found. long evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; do { // Replace the key and value for one of the hashes. switch (/*MathUtils.random(2)*/random.nextInt(3)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; default: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and stop. index1 = (int)(evictedKey & mask); key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(evictedKey); key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(evictedKey); key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash (long key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the table size. resize(capacity << 1); put(key, value); return; } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; size++; } public V get (long key) { if (key == 0) { if (!hasZeroValue) return null; return zeroValue; } int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, null); } } return valueTable[index]; } public V get (long key, V defaultValue) { if (key == 0) { if (!hasZeroValue) return defaultValue; return zeroValue; } int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, defaultValue); } } return valueTable[index]; } private V getStash (long key, V defaultValue) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return valueTable[i]; return defaultValue; } public V remove (long key) { if (key == 0) { if (!hasZeroValue) return null; V oldValue = zeroValue; zeroValue = null; hasZeroValue = false; size--; return oldValue; } int index = (int)(key & mask); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } return removeStash(key); } V removeStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex (int index) { // If the removed location was not last, move the last tuple to the removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } /** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is * done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */ public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = /*MathUtils.*/nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); } /** Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger. */ public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } zeroValue = null; hasZeroValue = false; size = 0; resize(maximumCapacity); } public void clear () { if (size == 0) return; long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = EMPTY; valueTable[i] = null; } size = 0; stashSize = 0; zeroValue = null; hasZeroValue = false; } /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return true; long[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return true; } else if (identity) { if (value == zeroValue) return true; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { if (hasZeroValue && value.equals(zeroValue)) return true; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey (long key) { if (key == 0) return hasZeroValue; int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return containsKeyStash(key); } } return true; } private boolean containsKeyStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return true; return false; } /** Returns the key for the specified value, or notFound if it is not in the map. Note this traverses the entire map * and compares every value, which may be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public long findKey (Object value, boolean identity, long notFound) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return 0; long[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return keyTable[i]; } else if (identity) { if (value == zeroValue) return 0; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { if (hasZeroValue && value.equals(zeroValue)) return 0; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return notFound; } /** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(/*MathUtils.*/nextPowerOfTwo((int)(sizeNeeded / loadFactor))); } @SuppressWarnings("unchecked") private void resize (int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int)(newSize * loadFactor); mask = newSize - 1; hashShift = 63 - Long.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize)) * 2); pushIterations = Math.max(Math.min(newSize, 8), (int)Math.sqrt(newSize) / 8); long[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = new long[newSize + stashCapacity]; valueTable = (V[])new Object[newSize + stashCapacity]; int oldSize = size; size = hasZeroValue ? 1 : 0; stashSize = 0; if (oldSize > 0) { for (int i = 0; i < oldEndIndex; i++) { long key = oldKeyTable[i]; if (key != EMPTY) putResize(key, oldValueTable[i]); } } } private int hash2 (long h) { h *= PRIME2; return (int)((h ^ h >>> hashShift) & mask); } private int hash3 (long h) { h *= PRIME3; return (int)((h ^ h >>> hashShift) & mask); } public String toString () { if (size == 0) return "[]"; StringBuilder buffer = new StringBuilder(32); buffer.append('['); long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append(']'); return buffer.toString(); } public Iterator> iterator () { return entries(); } /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries entries () { if (entries1 == null) { entries1 = new Entries(this); entries2 = new Entries(this); } if (!entries1.valid) { entries1.reset(); entries1.valid = true; entries2.valid = false; return entries1; } entries2.reset(); entries2.valid = true; entries1.valid = false; return entries2; } // RoboVM note: Not needed /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ /* public Values values () { if (values1 == null) { values1 = new Values(this); values2 = new Values(this); } if (!values1.valid) { values1.reset(); values1.valid = true; values2.valid = false; return values1; } values2.reset(); values2.valid = true; values1.valid = false; return values2; }*/ /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ /* public Keys keys () { if (keys1 == null) { keys1 = new Keys(this); keys2 = new Keys(this); } if (!keys1.valid) { keys1.reset(); keys1.valid = true; keys2.valid = false; return keys1; } keys2.reset(); keys2.valid = true; keys1.valid = false; return keys2; }*/ static public class Entry { public long key; public V value; public String toString () { return key + "=" + value; } } static private class MapIterator { static final int INDEX_ILLEGAL = -2; static final int INDEX_ZERO = -1; public boolean hasNext; final LongMap map; int nextIndex, currentIndex; boolean valid = true; public MapIterator (LongMap map) { this.map = map; reset(); } public void reset () { currentIndex = INDEX_ILLEGAL; nextIndex = INDEX_ZERO; if (map.hasZeroValue) hasNext = true; else findNextIndex(); } void findNextIndex () { hasNext = false; long[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != EMPTY) { hasNext = true; break; } } } public void remove () { if (currentIndex == INDEX_ZERO && map.hasZeroValue) { map.zeroValue = null; map.hasZeroValue = false; } else if (currentIndex < 0) { throw new IllegalStateException("next must be called before remove."); } else if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); nextIndex = currentIndex - 1; findNextIndex(); } else { map.keyTable[currentIndex] = EMPTY; map.valueTable[currentIndex] = null; } currentIndex = INDEX_ILLEGAL; map.size--; } } static public class Entries extends MapIterator implements Iterable>, Iterator> { private Entry entry = new Entry(); public Entries (LongMap map) { super(map); } /** Note the same entry instance is returned each time this method is called. */ public Entry next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new IllegalStateException("#iterator() cannot be used nested."); long[] keyTable = map.keyTable; if (nextIndex == INDEX_ZERO) { entry.key = 0; entry.value = map.zeroValue; } else { entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; } currentIndex = nextIndex; findNextIndex(); return entry; } public boolean hasNext () { if (!valid) throw new IllegalStateException("#iterator() cannot be used nested."); return hasNext; } public Iterator> iterator () { return this; } public void remove () { super.remove(); } } // RoboVM note: Not needed /* static public class Values extends MapIterator implements Iterable, Iterator { public Values (LongMap map) { super(map); } public boolean hasNext () { if (!valid) throw new GdxRuntimeExceptionIllegalStateException("#iterator() cannot be used nested."); return hasNext; } public V next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeExceptionIllegalStateException("#iterator() cannot be used nested."); V value; if (nextIndex == INDEX_ZERO) value = map.zeroValue; else value = map.valueTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return value; } public Iterator iterator () { return this; } *//** Returns a new array containing the remaining values. *//* public Array toArray () { Array array = new Array(true, map.size); while (hasNext) array.add(next()); return array; } public void remove () { super.remove(); } }*/ /* static public class Keys extends MapIterator { public Keys (LongMap map) { super(map); } public long next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeExceptionIllegalStateException("#iterator() cannot be used nested."); long key = nextIndex == INDEX_ZERO ? 0 : map.keyTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return key; } *//** Returns a new array containing the remaining values. *//* public LongArray toArray () { LongArray array = new LongArray(true, map.size); while (hasNext) array.add(next()); return array; } }*/ } /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ //import java.util.Random; /** This class implements the xorshift128+ algorithm that is a very fast, top-quality 64-bit pseudo-random number generator. The * quality of this PRNG is much higher than {@link Random}'s, and its cycle length is 2128 − 1, which * is more than enough for any single-thread application. More details and algorithms can be found here. *

* Instances of RandomXS128 are not thread-safe. * * @author Inferno * @author davebaol */ @SuppressWarnings("serial") class RandomXS128 extends java.util.Random { /** Normalization constant for double. */ private static final double NORM_DOUBLE = 1.0 / (1L << 53); /** Normalization constant for float. */ private static final double NORM_FLOAT = 1.0 / (1L << 24); /** The first half of the internal state of this pseudo-random number generator. */ private long seed0; /** The second half of the internal state of this pseudo-random number generator. */ private long seed1; /** Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely * to be distinct from any other invocation of this constructor. *

* This implementation creates a {@link Random} instance to generate the initial seed. */ public RandomXS128 () { setSeed(new java.util.Random().nextLong()); } /** Creates a new random number generator using a single {@code long} seed. * @param seed the initial seed */ public RandomXS128 (long seed) { setSeed(seed); } /** Creates a new random number generator using two {@code long} seeds. * @param seed0 the first part of the initial seed * @param seed1 the second part of the initial seed */ public RandomXS128 (long seed0, long seed1) { setState(seed0, seed1); } /** Returns the next pseudo-random, uniformly distributed {@code long} value from this random number generator's sequence. *

* Subclasses should override this, as this is used by all other methods. */ @Override public long nextLong () { long s1 = this.seed0; final long s0 = this.seed1; this.seed0 = s0; s1 ^= s1 << 23; return (this.seed1 = (s1 ^ s0 ^ (s1 >>> 17) ^ (s0 >>> 26))) + s0; } /** This protected method is final because, contrary to the superclass, it's not used anymore by the other methods. */ @Override protected final int next (int bits) { return (int)(nextLong() & ((1L << bits) - 1)); } /** Returns the next pseudo-random, uniformly distributed {@code int} value from this random number generator's sequence. *

* This implementation uses {@link #nextLong()} internally. */ @Override public int nextInt () { return (int)nextLong(); } /** Returns a pseudo-random, uniformly distributed {@code int} value between 0 (inclusive) and the specified value (exclusive), * drawn from this random number generator's sequence. *

* This implementation uses {@link #nextLong()} internally. * @param n the positive bound on the random number to be returned. * @return the next pseudo-random {@code int} value between {@code 0} (inclusive) and {@code n} (exclusive). */ @Override public int nextInt (final int n) { return (int)nextLong(n); } /** Returns a pseudo-random, uniformly distributed {@code long} value between 0 (inclusive) and the specified value (exclusive), * drawn from this random number generator's sequence. The algorithm used to generate the value guarantees that the result is * uniform, provided that the sequence of 64-bit values produced by this generator is. *

* This implementation uses {@link #nextLong()} internally. * @param n the positive bound on the random number to be returned. * @return the next pseudo-random {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). */ public long nextLong (final long n) { if (n <= 0) throw new IllegalArgumentException("n must be positive"); for (;;) { final long bits = nextLong() >>> 1; final long value = bits % n; if (bits - value + (n - 1) >= 0) return value; } } /** Returns a pseudo-random, uniformly distributed {@code double} value between 0.0 and 1.0from this random number generator's * sequence. *

* This implementation uses {@link #nextLong()} internally. */ @Override public double nextDouble () { return (nextLong() >>> 11) * NORM_DOUBLE; } /** Returns a pseudo-random, uniformly distributed {@code float} value between 0.0 and 1.0 from this random number generator's * sequence. *

* This implementation uses {@link #nextLong()} internally. */ @Override public float nextFloat () { return (float)((nextLong() >>> 40) * NORM_FLOAT); } /** Returns a pseudo-random, uniformly distributed {@code boolean } value from this random number generator's sequence. *

* This implementation uses {@link #nextLong()} internally. */ @Override public boolean nextBoolean () { return (nextLong() & 1) != 0; } /** Generates random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the * length of the byte array. *

* This implementation uses {@link #nextLong()} internally. */ @Override public void nextBytes (final byte[] bytes) { int n = 0; int i = bytes.length; while (i != 0) { n = i < 8 ? i : 8; // min(i, 8); for (long bits = nextLong(); n-- != 0; bits >>= 8) bytes[--i] = (byte)bits; } } /** Sets the internal seed of this generator based on the given {@code long} value. *

* The given seed is passed twice through an hash function. This way, if the user passes a small value we avoid the short * irregular transient associated with states having a very small number of bits set. * @param seed a nonzero seed for this generator (if zero, the generator will be seeded with {@link Long#MIN_VALUE}). */ @Override public void setSeed (final long seed) { long seed0 = murmurHash3(seed == 0 ? Long.MIN_VALUE : seed); setState(seed0, murmurHash3(seed0)); } /** Sets the internal state of this generator. * @param seed0 the first part of the internal state * @param seed1 the second part of the internal state */ public void setState (final long seed0, final long seed1) { this.seed0 = seed0; this.seed1 = seed1; } private final static long murmurHash3 (long x) { x ^= x >>> 33; x *= 0xff51afd7ed558ccdL; x ^= x >>> 33; x *= 0xc4ceb9fe1a85ec53L; x ^= x >>> 33; return x; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy