java - 如何使用 Java 和两个嵌套的 for 循环计算扑克中的对数
问题描述
我对编程很陌生,我一直在尝试一个练习。基本上我需要计算在 5 张卡片的未排序字符串中找到的卡片对的数量。我解释它的方式可能是错误的,例如,其中一个字符串看起来像这样:'sTh3c9hQ' 其中 s 是黑桃,T 是十,h 是红心等......我不确定为什么我的代码不是工作..可能是出于一个非常合乎逻辑的原因,我对此视而不见。有人可以给我一些建议吗?谢谢。
int count = 0;
for(int i = 0; i<hand.length()-2; i+=2){
for(int j = 1; j<hand.length()-3; j+=2){
if(hand.charAt(i) == hand.charAt(i+2) && hand.charAt(j) ==
hand.charAt(j+3)) {
count++;
}
}
}
return count;
在“sTh3c9hQ”的情况下,所需的输出将为 0,因为没有对。在“sTh3c9sT”的情况下,所需的输出为 1,因为只有一对。等等。如果有两对,计数将是 2。如果有三对,计数将是 3,等等
解决方案
我个人认为您应该将字符串拆分为一个列表,而不是跟踪您在字符串本身中的位置,这使得 for 循环更容易理解。类似的东西看起来像:
public int getPairs(final String hand) {
int count = 0;
List<String> cards = getParts(hand, 2);
for (int i = 0; i < cards.size() - 1; i++) {
for (int j = i + 1; j < cards.size(); j++) {
if (cards.get(i).charAt(1) == cards.get(j).charAt(1)) {
count++;
}
}
}
return count;
}
private static List<String> getParts(final String string,
final int partitionSize) {
List<String> parts = new ArrayList<>();
int len = string.length();
for (int i = 0; i < len; i += partitionSize) {
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
}
return parts;
}
推荐阅读
- c# - 在单个语句中使用 Nunit 测试参数
- c# - 在 ViewModel 中打开 ContextMenu -> RightClick 触发 LeftClickCommand
- python - 如何在文件中复制特定标签及其内容?
- reactjs - React Helmet 不更新元标题标签
- python - 如何高效地语法
- angular - Angular 8,Angular Flex 布局:this._delegate.setClass 不是函数
- sql - 我可以通过使用另一个表的约束来更改一个表的约束吗?
- spring-boot - Spring Kafka 生产者是否默认保证交付?
- android - 有什么办法可以实现这个步骤吧?
- r - R dataframe - 根据两个变量提取一对行,然后根据自定义 colwise 函数组合行