把字符串随机打散并平均分成N份

import java.security.MessageDigest;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;

import org.springframework.util.StringUtils;

import sun.misc.BASE64Encoder;

public class StringUtil {

	/**
	 * 对字符串进行MD5哈希散列后编码为字符串返回
	 * @param str 原始字符串
	 * @return 新字符串
	 */
	public static String encodeMD5(String str) {
		if (StringUtils.isEmpty(str)) {
			throw new RuntimeException("can not encodeMD5 empty string");
		}
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md5.digest(str.getBytes("utf-8"));
			BASE64Encoder base64Encoder = new BASE64Encoder();
			String encodeStr = base64Encoder.encode(md5Bytes);
			return encodeStr;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * 
	 * @param str
	 * @param baseModulo
	 * @return
	 */
	public static int hashAndModulo(String str, int baseModulo) {
		if (StringUtils.isEmpty(str)) {
			throw new RuntimeException("can not hashAndModulo empty string");
		}
		if (baseModulo <= 0) {
			throw new RuntimeException("can not hashAndModulo when baseModulo<=0");
		}
		int hashCode = str.hashCode();
		if (hashCode < 0) {
			hashCode *= -1;
		}
		int mod = hashCode % baseModulo;
		return mod;
	}

	public static void main(String[] args) {
		// 验证能否把随机字符串打散后均匀分布到每个模中
		Map<Integer, Integer> modMap = new TreeMap<Integer, Integer>();
		int baseModulo = 10;// 对baseModulo取模
		for (int i = 0; i < baseModulo; i++) {
			modMap.put(i, 0);
		}
		int total = 1000000;// 样本数量
		for (int i = 0; i < total; i++) {
			String encodeMD5 = encodeMD5(UUID.randomUUID().toString());
			int hashAndModulo = hashAndModulo("testStr_" + encodeMD5, baseModulo);
			Integer integer = modMap.get(hashAndModulo);
			modMap.put(hashAndModulo, 1 + integer);
		}
		Set<Entry<Integer, Integer>> entrySet = modMap.entrySet();
		for (Entry<Integer, Integer> entry : entrySet) {
			System.out.println(entry.getKey() + "-->" + 100 * ((double) (entry.getValue())) / total + "%");
		}
	}
}

大样本下得到的测试结果:

0-->9.9504%
1-->9.9833%
2-->9.9965%
3-->9.9593%
4-->10.0141%
5-->10.0054%
6-->10.0816%
7-->10.007%
8-->10.0161%
9-->9.9863%

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值