{"action":"opened","issue":{"url":"https://api.github.com/repos/WhaleChen/enjoy_stats/issues/1","labels_url":"https://api.github.com/repos/WhaleChen/enjoy_stats/issues/1/labels{/name}","comments_url":"https://api.github.com/repos/WhaleChen/enjoy_stats/issues/1/comments","events_url":"https://api.github.com/repos/WhaleChen/enjoy_stats/issues/1/events","html_url":"https://github.com/WhaleChen/enjoy_stats/issues/1","id":124548538,"number":1,"title":"尝试解释微信随机红包的玄机","user":{"login":"WhaleChen","id":11818114,"avatar_url":"https://avatars.githubusercontent.com/u/11818114?v=3","gravatar_id":"","url":"https://api.github.com/users/WhaleChen","html_url":"https://github.com/WhaleChen","followers_url":"https://api.github.com/users/WhaleChen/followers","following_url":"https://api.github.com/users/WhaleChen/following{/other_user}","gists_url":"https://api.github.com/users/WhaleChen/gists{/gist_id}","starred_url":"https://api.github.com/users/WhaleChen/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/WhaleChen/subscriptions","organizations_url":"https://api.github.com/users/WhaleChen/orgs","repos_url":"https://api.github.com/users/WhaleChen/repos","events_url":"https://api.github.com/users/WhaleChen/events{/privacy}","received_events_url":"https://api.github.com/users/WhaleChen/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":0,"created_at":"2016-01-01T15:48:41Z","updated_at":"2016-01-01T15:48:41Z","closed_at":null,"body":"# 尝试解释微信随机红包的玄机\r\n\r\n## 问题重构：\r\n\r\n- Q1. 抢包和拆包中红包在什么时候被计算？\r\n- Q2. 红包在每次过程中金额的计算的方式？\r\n- Q3. 如果两个用户同时抢到包，如何处理？\r\n- Q4. 随机数如何储存并显示给用户？\r\n\r\n## 解决方式： 当然首先google\r\n- [微信红包金额分配的算法](http://timyang.net/architecture/wechat-red-packet/) 对三个问题都有回到。\r\n- A1. 据某架构群腾讯财付通专家反馈，红包的金额是拆的时候实时计算。认为如果你抢到包，但是不拆，是有可能无法拆到的。这是可以通过实验证实的。\r\n- A2. 系统取0.01到剩余平均值*2之间作为红包的金额。\r\n- A3. 为了保证每次操作的原子性，拆包过程中使用了CAS。[CAS](https://zh.wikipedia.org/wiki/%E6%AF%94%E8%BE%83%E5%B9%B6%E4%BA%A4%E6%8D%A2) \r\n- A4. 可以用python 中 random.seed 来模拟。对于同样的seed。输出顺序相同。\r\n\r\n\r\n## 模拟数据：python \r\n源码：\r\n```\r\nimport random \r\n\r\nsharing_persons = int(raw_input(\"pls input persons number u wnt to share with 1 to 100 > \"))\r\ntotal_seeds = raw_input(\"pls input seeds number 1 to 100, ENTER r for random > \")\r\nif total_seeds in [\"r\",\"R\",\"random\",\"Random\"]:\r\n    total_seeds = random.randint(1,100)\r\nrandom.seed(int(total_seeds))\r\nfor i in range(0, sharing_persons):\r\n     a= random.randint(1,100)\r\n     print a\r\n```\r\n![show_same_pattern](https://cloud.githubusercontent.com/assets/11818114/12071344/055d97f4-b0e2-11e5-9413-cbde48bd47a4.png)\r\n可以看到，这里显示的随机代码在seeds 相同下是具有相同值的。\r\n"}}