如何创建ArrayList并通过循环处理实现卡牌游戏的颜色ID计数功能
实现逻辑
- 首先确认
colors列表元素与下标的对应关系,你示例里的colors下标0对应颜色ID-1、下标1对应颜色ID0,以此类推,计数规则就是玩家持有的颜色ID对应colors里的下标,buffer对应下标的数值加1 - 先初始化长度为8、全为0的
buffer列表 - 遍历玩家持有的卡牌颜色ID,匹配到
colors中的对应下标后更新buffer计数
基础实现代码
直接用ArrayList自带的indexOf方法找下标,适合数据量小的场景:
import java.util.ArrayList; import java.util.Arrays; public class CardCountTest { public static void main(String[] args) { // 初始化颜色ID列表 ArrayList<Integer> colors = new ArrayList<>(Arrays.asList(-1, 0, 1, 2, 3, 4, 5, 6)); // 初始化玩家持有卡牌列表(Java变量名不能带空格,这里调整为playerProperties) ArrayList<Integer> playerProperties = new ArrayList<>(Arrays.asList(0, 4, 6)); // 初始化计数buffer,填充8个0 ArrayList<Integer> buffer = new ArrayList<>(); for (int i = 0; i < 8; i++) { buffer.add(0); } // 遍历玩家卡牌做计数 for (Integer cardColor : playerProperties) { int targetIndex = colors.indexOf(cardColor); // 校验下标合法性,避免数组越界异常 if (targetIndex >= 0 && targetIndex < buffer.size()) { buffer.set(targetIndex, buffer.get(targetIndex) + 1); } } // 示例输入对应的输出为 [0, 1, 0, 0, 0, 1, 0, 1] System.out.println(buffer); } }
优化方案
如果后续卡牌数量大,每次调用indexOf都要遍历colors列表性能较差,可以提前构建颜色ID到下标的映射表,查询效率更高:
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class OptimizedCardCount { public static void main(String[] args) { ArrayList<Integer> colors = new ArrayList<>(Arrays.asList(-1, 0, 1, 2, 3, 4, 5, 6)); ArrayList<Integer> playerProperties = new ArrayList<>(Arrays.asList(0, 4, 6)); ArrayList<Integer> buffer = new ArrayList<>(); for (int i = 0; i < 8; i++) { buffer.add(0); } // 提前构建颜色ID到下标的映射 HashMap<Integer, Integer> colorIndexMap = new HashMap<>(); for (int i = 0; i < colors.size(); i++) { colorIndexMap.put(colors.get(i), i); } // 遍历计数 for (Integer cardColor : playerProperties) { if (colorIndexMap.containsKey(cardColor)) { int targetIndex = colorIndexMap.get(cardColor); buffer.set(targetIndex, buffer.get(targetIndex) + 1); } } System.out.println(buffer); } }
内容的提问来源于stack exchange,提问作者Yama Lomama
相关产品推荐
相关产品推荐

