You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrabble作业:字符计分与ArrayList排序技术咨询

Scrabble作业问题解决方案

一、遍历字符计算单词分值

首先定义Scrabble字母分值映射,用数组实现效率最高(字母范围固定,索引对应字母顺序),之后遍历单词的每个字符,统一转换为大写避免大小写干扰,再匹配对应分值累加即可。

示例代码:

// 索引0对应A,1对应B,依此类推,对应Scrabble官方分值
private static final int[] LETTER_VALUES = {
    1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3,
    1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10
};

// 计算单个单词的Scrabble总分
public static int calculateScore(String word) {
    int total = 0;
    String upperWord = word.toUpperCase();
    // 增强for循环遍历字符数组
    for (char c : upperWord.toCharArray()) {
        if (Character.isLetter(c)) {
            // 通过ASCII码差值获取数组索引
            int index = c - 'A';
            total += LETTER_VALUES[index];
        }
    }
    return total;
}

二、使用Comparator接口按分值排序

完全可以用Comparator实现按分值排序,根据Java版本不同有两种简洁写法:

1. 匿名内部类(兼容Java 8之前)

ArrayList<String> wordList = new ArrayList<>();
// 假设已从文件读取并填充wordList

Collections.sort(wordList, new Comparator<String>() {
    @Override
    public int compare(String w1, String w2) {
        // 降序排序,若需升序则交换w1和w2的计分位置
        return Integer.compare(calculateScore(w2), calculateScore(w1));
    }
});

2. Lambda表达式(Java 8及以上推荐)

// 直接调用List的sort方法更简洁
wordList.sort((w1, w2) -> 
    Integer.compare(calculateScore(w2), calculateScore(w1))
);

如果需要处理分值相同的单词按字母顺序排序,可以扩展逻辑:

wordList.sort((w1, w2) -> {
    int scoreDiff = Integer.compare(calculateScore(w2), calculateScore(w1));
    if (scoreDiff != 0) {
        return scoreDiff;
    }
    // 分值相同时按字母忽略大小写升序排列
    return w1.compareToIgnoreCase(w2);
});

内容的提问来源于stack exchange,提问作者ScarletCas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:30:50