简体   繁体   English

如何在分布式系统中以相同的方式随机化两个字符串 collections?

[英]How to randomize two String collections in the same fashion in distributed system?

I have several collections of strings (~100k elements).我有几个 collections 字符串(约 100k 个元素)。 They are initialized from the same network source:它们从相同的网络源初始化:

List<String> source = Arrays.asList("cat Tom", "dog Woof", "bird Carry", "fish Silent", "mice Dr Black");
List<String> list1 = new ArrayList<>(source);
List<String> list2 = new ArrayList<>(source); 
List<String> list3 = new ArrayList<>(source);

During their life they could be modified independently:在他们的一生中,他们可以独立修改:

list1.add("raccoon George");
list2.set(2, "bird Frank"); // Different bird
list3.remove(2); // No birds!

These collections live in different JVMs, but have the same (shared) seed:这些 collections 存在于不同的 JVM 中,但具有相同(共享)的种子:

String seed = UUID.randomUUID().toString();

I need some sort/shuffle method (or Comparator ) to randomize these collections:我需要一些排序/洗牌方法(或Comparator )来随机化这些 collections:

magicSort(list1, seed); // JVM #1
magicSort(list2, seed); // JVM #2
magicSort(list3, seed); // JVM #3

To receive consistent/repeatable output like this:要像这样接收一致/可重复的 output:

[mice Dr Black, bird Carry, raccoon George, cat Tom, dog Woof, fish Silent]
[mice Dr Black, bird Frank, cat Tom, dog Woof, fish Silent]
[mice Dr Black, cat Tom, dog Woof, fish Silent]

This doesn't work:这不起作用:

  • Collections.shuffle() from this answer - because it does not provide affinity for items with the same prefix;此答案中的Collections.shuffle() - 因为它不为具有相同前缀的项目提供亲和力;
  • keep randomized order in Map<String, UUID> - because of (a) collection's dynamic nature and (b) distributed setup.Map<String, UUID>中保持随机顺序 - 因为 (a) 集合的动态性质和 (b) 分布式设置。

Any help will be appreciated任何帮助将不胜感激

Edit #1编辑#1

This doesn't work:这不起作用:

  • sha1 , md5 and similar hash algorithms - because they do not provide affinity for items with the same prefix - bird Carry and bird Frank could be placed far from each other. sha1md5和类似的 hash 算法 - 因为它们不为具有相同前缀的项目提供亲和力 - bird Carrybird Frank可以放置在远离彼此的位置。

Edit #2编辑#2

Additional condition: items with the same prefix should be grouped together (affinity), eg all birds are placed between mices and raccoons.附加条件:具有相同前缀的项目应该组合在一起(亲和),例如所有的鸟都放在老鼠和浣熊之间。

Many thanks for hashing hint in comments!非常感谢评论中的散列提示!

I've ended up with re-mapping characters order through pseudo-random hashing (similar to Fisher–Yates shuffle).我最终通过伪随机散列(类似于 Fisher-Yates shuffle)重新映射字符顺序。 The rest code was copy-pasted from String.compareTo : rest 代码是从String.compareTo复制粘贴的:

private void magicSort(List<String> list, String seed) {
    list.sort(new ShuffleComparator(seed));
}

public class ShuffleComparator implements Comparator<String> {
    private static final long MAGIC = 0x5DEECE66DL;
    private final String seed;

    public ShuffleComparator(String seed) {
        this.seed = seed;
    }

    @Override
    public int compare(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int lim = Math.min(len1, len2);

        int seedLen = seed.length();
        long random = seed.hashCode();

        for (int k = 0; k < lim; k++) {
            random = random * MAGIC + seed.charAt(k % seedLen);
            char c1 = s1.charAt(k);
            char c2 = s2.charAt(k);
            if (c1 != c2) {
                return ((random % (c1 + 0xFFFF)) & 0xFFFF) -
                    ((random % (c2 + 0xFFFF)) & 0xFFFF) > 0 ? 1 : -1;
            }
        }
        return (random > 0 ? 1 : -1) * (len1 - len2);
    }
}

Result:结果:

  • You can keep collections shuffle-sorted at all times您可以始终保持 collections 随机排序
  • Items with identical prefix are grouped together (affinity)具有相同前缀的项目组合在一起(亲和力)
  • The only resource (string seed) is shared between JVMs JVM 之间共享唯一的资源(字符串种子)
  • Negligible impact on performance对性能的影响可以忽略不计
  • Zero GC零垃圾回收

Examples:例子:

seed: b85a9119-3a98-4491-b503-fc2cfdc344f3
[raccoon George, bird Carry, mice Dr Black, fish Silent, cat Tom, dog Woof]
[bird Frank, mice Dr Black, fish Silent, cat Tom, dog Woof]
[mice Dr Black, fish Silent, cat Tom, dog Woof]

seed: d5378421-d0ea-4b17-80e9-1de6a163bf38
[bird Carry, dog Woof, fish Silent, raccoon George, mice Dr Black, cat Tom]
[bird Frank, dog Woof, fish Silent, mice Dr Black, cat Tom]
[dog Woof, fish Silent, mice Dr Black, cat Tom]

seed: a5f94f60-1207-4f83-9723-bbab5e3b8075
[cat Tom, raccoon George, mice Dr Black, bird Carry, dog Woof, fish Silent]
[cat Tom, mice Dr Black, bird Frank, dog Woof, fish Silent]
[cat Tom, mice Dr Black, dog Woof, fish Silent]

seed: 4b77a61f-c639-42fc-96b2-e1add9f359e9
[bird Carry, raccoon George, cat Tom, mice Dr Black, dog Woof, fish Silent]
[bird Frank, cat Tom, mice Dr Black, dog Woof, fish Silent]
[cat Tom, mice Dr Black, dog Woof, fish Silent]

seed: 2dd78e21-d4ad-4e8a-b139-5d35fe2b0481
[dog Woof, fish Silent, raccoon George, mice Dr Black, bird Carry, cat Tom]
[dog Woof, fish Silent, mice Dr Black, bird Frank, cat Tom]
[dog Woof, fish Silent, mice Dr Black, cat Tom]

Edit #1编辑#1

For tests I've also implemented hash-based comparator, so would publish it here.对于测试,我还实现了基于哈希的比较器,因此将在此处发布。 Just in case if you don't need affinity (like in my case), but need pure shuffle:以防万一您不需要亲和力(例如我的情况),但需要纯洗牌:

private void magicSort(List<String> list, String seed) {
    list.sort(new HashComparator(seed, "SHA-1"));
}

public class HashComparator implements Comparator<String> {
    private static final long MAGIC = 0x5DEECE66DL;
    private final ThreadLocal<MessageDigest> messageDigest;
    private final byte[] seed;
    private final int seedHash;

    public HashComparator(String seed, String algorithm) {
        this.seed = seed.getBytes(ISO_8859_1);
        this.seedHash = seed.hashCode();
        this.messageDigest = ThreadLocal.withInitial(() -> {
            try {
                return MessageDigest.getInstance(algorithm);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        });
    }

    @Override
    public int compare(String s1, String s2) {
        if (s1.equals(s2)) {
            return 0;
        }
        int diff = getSignature(s1).compareTo(getSignature(s2));
        if (diff != 0) {
            return diff;
        }
        long random = seedHash;
        random = random * MAGIC + s1.hashCode();
        random = random * MAGIC + s2.hashCode();
        return ((random & 1) == 0 ? 1 : -1) * s1.compareTo(s2);

    }

    private ByteBuffer getSignature(String s) {
        MessageDigest digest = messageDigest.get();
        digest.reset();
        digest.update(seed);
        for (int i = 0, size = s.length(); i < size; i++) {
            char c = s.charAt(i);
            digest.update((byte) (c >> 8));
            digest.update((byte) c);
        }
        return ByteBuffer.wrap(digest.digest());
    }
}

Result:结果:

  • You can keep collections shuffle-sorted at all times您可以始终保持 collections 随机排序
  • Pure shuffle (no affinity for items with identical prefix)纯随机播放(对具有相同前缀的项目没有亲和力)
  • The only resource (string seed) is shared between JVMs JVM 之间共享唯一的资源(字符串种子)

Examples:例子:

8d465fde-9310-4b6c-9709-5cc395deb45e
[raccoon George, mice Dr Black, dog Woof, fish Silent, cat Tom, bird Carry]
[bird Frank, mice Dr Black, dog Woof, fish Silent, cat Tom]
[mice Dr Black, dog Woof, fish Silent, cat Tom]

6daa90dd-f7e7-4615-a45c-fefb0de10c20
[bird Carry, mice Dr Black, fish Silent, cat Tom, dog Woof, raccoon George]
[mice Dr Black, bird Frank, fish Silent, cat Tom, dog Woof]
[mice Dr Black, fish Silent, cat Tom, dog Woof]

9f30b259-c8d1-41f5-8221-40b17cb04260
[cat Tom, mice Dr Black, raccoon George, dog Woof, fish Silent, bird Carry]
[bird Frank, cat Tom, mice Dr Black, dog Woof, fish Silent]
[cat Tom, mice Dr Black, dog Woof, fish Silent]

94b6710f-3232-453d-8009-6d81658b2cca
[dog Woof, fish Silent, bird Carry, cat Tom, mice Dr Black, raccoon George]
[dog Woof, fish Silent, cat Tom, mice Dr Black, bird Frank]
[dog Woof, fish Silent, cat Tom, mice Dr Black]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM