From 54a42c00245540455a3b930a7a2d8ce5e3096bf8 Mon Sep 17 00:00:00 2001 From: Phil Steitz Date: Sun, 23 Nov 2008 15:35:11 +0000 Subject: [PATCH] Added test case to ensure permuting arrays changes hash. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/branches/MATH_2_0@719995 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/math/util/MathUtilsTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/test/org/apache/commons/math/util/MathUtilsTest.java b/src/test/org/apache/commons/math/util/MathUtilsTest.java index c916d3ff3..0aad8f54f 100644 --- a/src/test/org/apache/commons/math/util/MathUtilsTest.java +++ b/src/test/org/apache/commons/math/util/MathUtilsTest.java @@ -19,6 +19,7 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.apache.commons.math.random.RandomDataImpl; import org.apache.commons.math.TestUtils; /** @@ -331,6 +332,35 @@ public final class MathUtilsTest extends TestCase { assertFalse(MathUtils.hash(new double[] { 1d }) == MathUtils.hash(new double[] { 1d, 1d })); } + + /** + * Make sure that permuted arrays do not hash to the same value. + */ + public void testPermutedArrayHash() { + double[] original = new double[10]; + double[] permuted = new double[10]; + RandomDataImpl random = new RandomDataImpl(); + + // Generate 10 distinct random values + for (int i = 0; i < 10; i++) { + original[i] = random.nextUniform((double)i + 0.5, (double)i + 0.75); + } + + // Generate a random permutation, making sure it is not the identity + boolean isIdentity = true; + do { + int[] permutation = random.nextPermutation(10, 10); + for (int i = 0; i < 10; i++) { + if (i != permutation[i]) { + isIdentity = false; + } + permuted[i] = original[permutation[i]]; + } + } while (isIdentity); + + // Verify that permuted array has different hash + assertFalse(MathUtils.hash(original) == MathUtils.hash(permuted)); + } public void testIndicatorByte() { assertEquals((byte)1, MathUtils.indicator((byte)2));