算法题,网上给出的解释感觉有点抽象。不知道有哪位能够帮忙详解一下,不甚感谢!
附上搜索到解答:
http://www.7zhang.com/index/c...
http://www.cnblogs.com/bozhou...
算法题,网上给出的解释感觉有点抽象。不知道有哪位能够帮忙详解一下,不甚感谢!
附上搜索到解答:
http://www.7zhang.com/index/c...
http://www.cnblogs.com/bozhou...
借着C++的代码来回答一下,思路就是随着骰子数目的增加,下一组的概率可以由上一组生成:
/* -std=c++11 */
#include <iostream>
#include <map>
#define Pmap std::map<unsigned int, double>
class Dices {
public:
static constexpr double UNIT = 1.0 / 6.0;
private:
Pmap possibles;
size_t count = 0;
void calcNext() {
if (this->possibles.empty()) {
// 初始状态
this->possibles = {
{1, UNIT}, {2, UNIT}, {3, UNIT},
{4, UNIT}, {5, UNIT}, {6, UNIT}
};
} else {
Pmap newMap;
for (auto const &it : this->possibles) {
for (int i = 1; i <= 6; i++) {
unsigned int newSum = it.first + i;
auto addtion = it.second * UNIT;
auto search = newMap.find(newSum);
if (search != newMap.end()) {
search->second += addtion;
} else {
newMap.insert(std::make_pair(newSum, addtion));
}
}
}
this->possibles = newMap;
}
}
public:
Dices () {}
void calc(size_t c) {
count = c;
possibles = Pmap();
if (count == 0) return;
for (int i = 0; i < count; i++) {
calcNext();
}
}
void print() {
std::cout << "all possibilities:" << std::endl;
float sum = 0.0;
for (auto const &it : this->possibles) {
sum += it.second;
std::cout << it.first << "\t" << it.second << std::endl;
}
std::cout << "total: " << sum << std::endl;
}
};
int main(int argc, char **args) {
Dices d = Dices();
d.calc(2);
d.print();
d.calc(12);
d.print();
return 0;
}
4 回答13.2k 阅读✓ 已解决
5 回答7.7k 阅读✓ 已解决
1 回答2.9k 阅读✓ 已解决
1 回答1.5k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
1 回答950 阅读✓ 已解决
1 回答1.4k 阅读
自己写的PHP版本。通过两重循环获取2个数组的键值(骰子点数)及其出现概率。并将其累加。即可获得结果