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

数组同名字符串数量限制及码头泊位分配逻辑技术问询

解答你的两个编程问题

Hey there! Let's tackle your two questions one by one with straightforward, practical solutions that you can adapt to your codebase.

问题1:如何限制同一数组内相同字符串名称的数量不超过指定值?

核心思路

要实现这个需求,关键是实时跟踪每个字符串的出现次数,在添加新元素前先校验是否已达上限。具体步骤:

  • 维护一个计数对象(或字典),记录数组中每个字符串的当前出现次数
  • 每次添加新字符串时,先检查计数:
    • 若未达上限,就将字符串加入数组并更新计数
    • 若已达上限,就拒绝添加并给出提示

代码示例(JavaScript)

// 初始化存储数组和计数映射
let stringArray = [];
let countTracker = {};
const MAX_ALLOWED = 3; // 你指定的最大重复次数

function addStringToArr(str) {
  // 初始化该字符串的计数(如果之前没记录过)
  countTracker[str] = countTracker[str] || 0;

  if (countTracker[str] < MAX_ALLOWED) {
    stringArray.push(str);
    countTracker[str]++;
    console.log(`✅ 添加成功!当前"${str}"的数量:${countTracker[str]}`);
    return true;
  } else {
    console.log(`❌ 无法添加"${str}",已达到上限${MAX_ALLOWED}`);
    return false;
  }
}

// 测试一下
addStringToArr("apple"); // 成功
addStringToArr("apple"); // 成功
addStringToArr("apple"); // 成功
addStringToArr("apple"); // 失败,提示已达上限

如果用Python,逻辑是一样的,只是语法不同:

string_array = []
count_tracker = {}
MAX_ALLOWED = 3

def add_string_to_arr(string):
    count_tracker[string] = count_tracker.get(string, 0)
    if count_tracker[string] < MAX_ALLOWED:
        string_array.append(string)
        count_tracker[string] += 1
        print(f"✅ 添加成功!当前'{string}'的数量:{count_tracker[string]}")
        return True
    else:
        print(f"❌ 无法添加'{string}',已达到上限{MAX_ALLOWED}")
        return False

问题2:船舶泊位停靠逻辑实现

需求梳理

先明确规则:

  • 总泊位:10个(5个小型泊位、5个中型泊位)
  • cargo船:可停靠任意可用泊位(优先小型也可以,看你需求)
  • container船:仅能停靠中型泊位
  • 核心校验:
    • 停靠cargo时,检查所有泊位是否还有空位
    • 停靠container时,检查中型泊位是否还有空位

代码示例(JavaScript)

这里我们用两个数组分别记录小型和中型泊位的占用状态(false表示未占用,true表示已占用),逻辑更直观:

// 初始化泊位:5个小型、5个中型,初始状态都是未占用
const smallBerths = new Array(5).fill(false);
const mediumBerths = new Array(5).fill(false);

function dockShip(shipName, shipType) {
    if (shipType === "cargo") {
        // 先尝试停靠小型泊位(可选优先级,也可以先看中型)
        const emptySmallIndex = smallBerths.indexOf(false);
        if (emptySmallIndex !== -1) {
            smallBerths[emptySmallIndex] = true;
            console.log(`✅ ${shipName}(cargo)已停靠小型泊位${emptySmallIndex + 1}`);
            return true;
        }
        // 小型泊位满了,尝试中型泊位
        const emptyMediumIndex = mediumBerths.indexOf(false);
        if (emptyMediumIndex !== -1) {
            mediumBerths[emptyMediumIndex] = true;
            console.log(`✅ ${shipName}(cargo)已停靠中型泊位${emptyMediumIndex + 1}`);
            return true;
        }
        // 所有泊位都满了
        console.log(`❌ 抱歉,${shipName}(cargo)无法停靠,所有泊位已满`);
        return false;
    } else if (shipType === "container") {
        // 只能停靠中型泊位
        const emptyMediumIndex = mediumBerths.indexOf(false);
        if (emptyMediumIndex !== -1) {
            mediumBerths[emptyMediumIndex] = true;
            console.log(`✅ ${shipName}(container)已停靠中型泊位${emptyMediumIndex + 1}`);
            return true;
        }
        console.log(`❌ 抱歉,${shipName}(container)无法停靠,中型泊位已满`);
        return false;
    } else {
        console.log(`❌ 未知船舶类型:${shipType}`);
        return false;
    }
}

// 测试用例
dockShip("SeaStar", "container"); // 成功停靠中型泊位1
dockShip("CargoMaster", "cargo"); // 成功停靠小型泊位1
// 连续添加5艘container船
dockShip("BigContainer1", "container");
dockShip("BigContainer2", "container");
dockShip("BigContainer3", "container");
dockShip("BigContainer4", "container");
dockShip("BigContainer5", "container"); // 第5艘,成功停靠
dockShip("BigContainer6", "container"); // 失败,中型泊位已满

补充说明

如果不需要跟踪具体泊位编号,也可以用两个计数变量简化逻辑:occupiedSmall(已占用小型泊位数量)和occupiedMedium(已占用中型泊位数量),判断逻辑是一样的,代码会更简洁。


内容的提问来源于stack exchange,提问作者S.smith94

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:15:50