利用marscode ai快速编程

250 阅读2分钟

提问

比如一个数组有三个range,list = [[0,1,1,1], [1,1,3,1],[2,1,5,1]],range四个元素表示行起点、列起点,行终点,列终点。在只考虑行合并情况下,将连续行的range合并成一个新的range,比如上面list可以合并为list = [[0,1,5,1]]

选择Deepseek R1模型

image.png

回答1

1.思考过程

image.png 从思考过程,我们可以学习一下此模型的推理逻辑

2.给出示例代码

function mergeRowRanges(ranges) {
    if (ranges.length === 0) return [];
    
    // 按行起点排序
    const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
    const merged = [sorted[0]];
    
    for (let i = 1; i < sorted.length; i++) {
        const current = sorted[i];
        const last = merged[merged.length - 1];
        
        // 检查列坐标是否相同,且行是否连续
        if (last[1] === current[1] && 
            last[3] === current[3] &&
            last[2] + 1 === current[0]) {
            // 合并行终点
            last[2] = Math.max(last[2], current[2]);
        } else {
            merged.push(current);
        }
    }
    
    return merged;
}

主要实现逻辑:

  1. 先对范围数组按行起点排序

  2. 遍历时检查相邻范围:

    • 列起点和终点必须相同
    • 前一个范围的行终点+1等于当前范围的行起点
  3. 满足条件时合并行终点,否则作为新范围添加

    特殊处理:

  • 自动处理乱序输入(通过预先排序)
  • 保留最大的行终点值(使用Math.max)
  • 保持原有列坐标不变

该实现可以处理包含重叠或非连续范围的情况,输出最优合并结果。

3.测试验证

我们将代码放在某个js文件,用node执行 image.png 发现结果其实是不对的,对此,我们回复ai

你这个答案有问题,示例结果还是输入数据,没有变化哦

回答2

1.思考过程

image.png

2.修复代码

...
// 修改判断条件:允许行区间有重叠或相邻
if (last[1] === current[1] && 
    last[3] === current[3] &&
    current[0] <= last[2] + 1) {  // 原条件 last[2] + 1 === current[0]
    last[2] = Math.max(last[2], current[2]);
} else {
    merged.push(current);
}
...

关键修改说明:  将严格连续判断 last[2] + 1 === current[0] 改为范围连接判断 current[0] ≤ last[2] + 1,这样可以处理:

  • 首尾相连的区间(如[0-1]和[1-3])
  • 有重叠的区间(如[1-3]和[2-5])

3.再次测试验证

image.png

结果是符合预期的,我们可以基于此,让MarsCode生成测试用例,进一步测试

describe('mergeRowRanges', () => {
  beforeEach(() => {
    // 导入待测函数
    mergeRowRanges = require('./mergeRowRanges');
  });

  test('should merge ranges correctly', () => {
    const ranges = [
      [1, 2, 3, 4],
      [2, 2, 4, 4],
      [3, 2, 5, 4],
    ];
    const expected = [
      [1, 2, 5, 4],
    ];
    expect(mergeRowRanges(ranges)).toEqual(expected);
  });

  test('should handle empty ranges', () => {
    const ranges = [];
    const expected = [];
    expect(mergeRowRanges(ranges)).toEqual(expected);
  });

  test('should handle single range', () => {
    const ranges = [
      [1, 2, 3, 4],
    ];
    const expected = [
      [1, 2, 3, 4],
    ];
    expect(mergeRowRanges(ranges)).toEqual(expected);
  });

  test('should handle non-continuous ranges', () => {
    const ranges = [
      [1, 2, 3, 4],
      [5, 2, 6, 4],
    ];
    const expected = [
      [1, 2, 3, 4],
      [5, 2, 6, 4],
    ];
    expect(mergeRowRanges(ranges)).toEqual(expected);
  });
});

最后

AI的发展,提升快速编码能力,有优有缺,取长补短,节省个人编码时间,学习更有价值的东西,快乐摸鱼 [不看]