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

如何在战舰游戏的20个位置中随机放置5艘不重复战舰?

问题分析

原代码的核心问题在于:

  • 随机生成的是0-5的数值,既没有保证1-5每个编号仅出现一次,也没有控制战舰的总数量(需要恰好5艘不同编号的战舰)
  • 遍历数组直接赋值的逻辑,必然导致编号重复,完全不符合需求
修正后的完整代码
import java.util.Random;

public class BattleshipSetup {
    private static final Random rnd = new Random();

    static void inicializarBarcosComputadora(int[] barcosComputadora) {
        // 先将数组所有位置初始化为0
        for (int i = 0; i < barcosComputadora.length; i++) {
            barcosComputadora[i] = 0;
        }

        // 用布尔数组标记已使用的位置,避免重复放置
        boolean[] usedPositions = new boolean[barcosComputadora.length];
        
        // 为1-5号战舰分别找不重复的随机位置
        for (int shipId = 1; shipId <= 5; shipId++) {
            int randomPos;
            // 循环直到找到未被占用的位置
            do {
                randomPos = rnd.nextInt(barcosComputadora.length);
            } while (usedPositions[randomPos]);
            
            usedPositions[randomPos] = true;
            barcosComputadora[randomPos] = shipId;
        }
    }

    static void imprimirArreglo(int[] pValores) {
        for (int valor : pValores) {
            System.out.print(valor + "\t");
        }
    }

    public static void main(String[] args) {
        int tam = 20;
        int[] barcosComputadora = new int[tam];
        inicializarBarcosComputadora(barcosComputadora);
        System.out.println("Valores del arreglo: ");
        imprimirArreglo(barcosComputadora);
    }
}
关键逻辑说明
  • 全局初始化:先把数组所有元素设为0,确保未放置战舰的位置都是默认值
  • 位置去重:通过usedPositions布尔数组记录已被占用的索引,每次生成随机位置后检查是否已使用,直到找到可用位置
  • 唯一编号赋值:从1到5依次给选中的位置赋值,保证每个战舰编号仅出现一次,且恰好生成5艘战舰
输出示例

运行后会得到符合需求的结果,例如:

0 0 5 0 0 0 2 0 0 0 1 0 0 0 3 0 0 4 0 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:40:25