AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-839733

Abhijit Sarkar's questions

Martin Hope
Abhijit Sarkar
Asked: 2025-04-30 04:34:21 +0800 CST

从哈希图中获取排序顺序时 PriorityQueue Comparator 的行为很奇怪

  • 3

在学习LeetCode 675时,我遇到了一种PriorityQueue Comparator无法解释的奇怪行为。

为了简洁起见,我将陈述问题陈述的要点;感兴趣的人可以在 LeetCode 上阅读全文。

给定一个名为 的 mxn 矩阵forest,其中某些单元格被指定为trees。问题是找到按树​​高升序访问(截断)所有树单元格所需的最少步数。

为了解决这个问题,我找到了所有的树,并按高度升序排列。然后,我使用启发式函数运行 A* 搜索,计算每棵树到下一棵树的最小距离:distance from source + Manhattan distance from the goal

切断所有树的最小步数是所有 A* 距离的总和。如果 A* 搜索在任何时候未能返回路径,我就中止搜索。

class Solution {
  private final int[][] dx = new int[][] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

  public int cutOffTree(List<List<Integer>> forest) {
    int[] curr = new int[] {0, 0};
    int dist = 0;

    for (int[] next : getTreesSortedByHeight(forest)) {
      int d = minDist(forest, curr, next);
      if (d < 0) {
        return -1;
      }
      curr = next;
      dist += d;
    }

    return dist;
  }

  private List<int[]> getTreesSortedByHeight(List<List<Integer>> forest) {
    List<int[]> trees = new ArrayList<>();
    for (int row = 0; row < forest.size(); row++) {
      for (int col = 0; col < forest.get(0).size(); col++) {
        if (forest.get(row).get(col) > 1) {
          trees.add(new int[] {row, col});
        }
      }
    }
    trees.sort(Comparator.comparingInt(a -> forest.get(a[0]).get(a[1])));
    return trees;
  }

  int minDist(List<List<Integer>> forest, int[] start, int[] goal) {
    int m = forest.size();
    int n = forest.get(0).size();
    Map<Integer, Integer> costs = new HashMap<>();
    costs.put(start[0] * n + start[1], manhattanDist(start[0], start[1], goal));
    // GOTCHA: Fetching the distance from the cost map using the coordinates doesn't work!
    Queue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
    heap.offer(new int[] {0, 0, start[0], start[1]}); // [cost, distance, row, column]

    while (!heap.isEmpty()) {
      int[] curr = heap.poll();
      int dist = curr[1];
      int row = curr[2];
      int col = curr[3];

      if (row == goal[0] && col == goal[1]) {
        return dist;
      }
      for (int[] d : dx) {
        int r = row + d[0];
        int c = col + d[1];
        if (r >= 0 && r < m && c >= 0 && c < n && forest.get(r).get(c) > 0) {
          int cost = dist + 1 + manhattanDist(r, c, goal);
          if (cost < costs.getOrDefault(r * n + c, Integer.MAX_VALUE)) {
            costs.put(r * n + c, cost);
            heap.offer(new int[] {cost, dist + 1, r, c});
          }
        }
      }
    }
    return -1;
  }

  private int manhattanDist(int row, int col, int[] goal) {
    return Math.abs(goal[0] - row) + Math.abs(goal[1] - col);
  }
}

请注意,每个堆条目都包含启发式成本。从逻辑上讲,这是不必要的,因为条目还包含单元格坐标(行和列),我们可以使用这些坐标从地图中获取距离costs,如下所示:

Queue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> costs.get(a[1] * n + a[2]);
  • 在没有成本的情况下,堆条目由[距离,行,列]组成。

但这不起作用,并且其中一个测试用例失败了。这个测试用例太大了,所以我觉得没有必要贴在这里,毕竟不太可能有人有时间去调试它。

我想知道为什么会出现这种奇怪的现象。

编辑: 根据评论中的要求添加了完整的代码。

java
  • 1 个回答
  • 78 Views
Martin Hope
Abhijit Sarkar
Asked: 2024-12-21 17:55:51 +0800 CST

鉴于以“with”开头的成员定义不再受支持

  • 5

给出以下代码(不是双关语):

trait Display[A]:
  def display(value: A): String


object Display:
  given stringDisplay: Display[String] with
    def display(input: String) = input

IntelliJ 显示以下警告:

鉴于以 开头的成员定义with不再受支持;请改用{...}或:后跟换行符。

这很奇怪,因为官方文档仍然显示given...with,并且我在网上找不到与此消息相对应的任何内容。

此外,我不知道如何应用该建议,因为以下内容均无法编译:

given stringDisplay: Display[String] {
    def display(input: String) = input
}

given stringDisplay: Display[String]:
  def display(input: String) = input

应用 IntelliJ 建议的正确语法是什么?使用 Scala 3.6.2。

scala
  • 1 个回答
  • 29 Views
Martin Hope
Abhijit Sarkar
Asked: 2024-10-18 19:45:32 +0800 CST

mypy 关于 numpy.apply_along_axis 的警告

  • 5

编辑 2024 年 10 月 18 日:

下面显示了该问题的一个更为简单的重现。

mypy_arg_type.py:

import numpy as np
from numpy.typing import NDArray
import random

def winner(_: NDArray[np.bytes_]) -> bytes | None:
    return b"." if bool(random.randint(0, 1)) else None

board = np.full((2, 2), ".", "|S1")
for w in np.apply_along_axis(winner, 0, board):
    print(w)

>> python mypy_arg_type.py

b'.'
None

>> mypy mypy_arg_type.py

mypy_arg_type.py:9: error: Argument 1 to "apply_along_axis" has incompatible type "Callable[[ndarray[Any, dtype[bytes_]]], bytes | None]"; expected "Callable[[ndarray[Any, dtype[Any]]], _SupportsArray[dtype[Never]] | _NestedSequence[_SupportsArray[dtype[Never]]]]"  [arg-type]
mypy_arg_type.py:9: note: This is likely because "winner" has named arguments: "_". Consider marking them positional-only
Found 1 error in 1 file (checked 1 source file)

原始问题:

我正在研究一个问题,即根据棋盘上棋子的位置来确定四子连珠A游戏的获胜者。棋盘尺寸为 6x7,每列标有从到 的字母G。如果有获胜者,则在一行、一列、对角线或反对角线上有 4 个相同颜色的棋子。

例子:

输入:["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"]

木板:

R Y . . . . R
R Y . . . . .
R Y . . . . .
. Y . . . . .
. . . . . . .
. . . . . . .

优胜者:Yellow

以下代码决定获胜者。

import itertools
import numpy as np
from numpy.typing import NDArray

def who_is_winner(pieces: list[str]) -> str:
    def parse_board() -> NDArray[np.bytes_]:
        m, n = 6, 7
        indices = [0] * n
        # https://numpy.org/doc/stable/user/basics.strings.html#fixed-width-data-types
        # One-byte encoding, the byteorder is ‘|’ (not applicable)
        board = np.full((m, n), ".", "|S1")
        for p in pieces:
            col = ord(p[0]) - ord("A")
            board[indices[col], col] = p[2]
            indices[col] += 1

        return board

    def winner(arr: NDArray[np.bytes_]) -> np.bytes_ | None:
        i = len(arr)
        xs = next(
            (xs for j in range(i - 3) if (xs := set(arr[j : j + 4])) < {b"R", b"Y"}),
            {None},
        )
        return xs.pop()

    def axis(x: int) -> np.bytes_ | None:
        # https://numpy.org/doc/2.0/reference/generated/numpy.apply_along_axis.html#numpy-apply-along-axis
        # Axis 0 is column-wise, 1 is row-wise.
        return next(
            (w for w in np.apply_along_axis(winner, x, board) if w is not None), None
        )

    def diag(d: int) -> np.bytes_ | None:
        # https://numpy.org/doc/stable/reference/generated/numpy.diagonal.html#numpy-diagonal
        # Diagonal number is w.r.t. the main diagonal.
        b = board if bool(d) else np.fliplr(board)
        return next(
            (w for d in range(-3, 4) if (w := winner(b.diagonal(d))) is not None), None
        )

    board = parse_board()
    match next(
        (
            w
            for f, i in itertools.product((axis, diag), (0, 1))
            if (w := f(i)) is not None
        ),
        None,
    ):
        case b"Y":
            return "Yellow"
        case b"R":
            return "Red"
        case _:
            return "Draw"

但是,这会产生如下的 mypy 违规:

error: Argument 1 to "apply_along_axis" has incompatible type "Callable[[ndarray[Any, dtype[bytes_]]], bytes_ | None]"; expected "Callable[[ndarray[Any, dtype[Any]]], _SupportsArray[dtype[bytes_]] | _NestedSequence[_SupportsArray[dtype[bytes_]]]]"  [arg-type]
note: This is likely because "winner" has named arguments: "arr". Consider marking them positional-only

根据apply_along_axis的文档,它应该返回一个值,这与上面的代码一致。

如何修复此违规?使函数winner仅定位于某一位置并没有什么区别,只是建议消失了。

我正在使用 Python 3.12.5 和 mypy 1.11.2。

python
  • 2 个回答
  • 63 Views
Martin Hope
Abhijit Sarkar
Asked: 2024-09-15 20:22:46 +0800 CST

来源 ~/.bashrc 没有来源包含的脚本[重复]

  • 5
这个问题已经有答案了:
脚本中的源 .bashrc 不起作用 (1 个回答)
49 分钟前关闭。

我有一个安装 rvm的 Docker 映像。在 中Dockerfile,我将以下几行附加到~/.bashrc用户的 中。

export PATH="$PATH:$HOME/.rvm/bin"
source "$HOME/.rvm/scripts/rvm"

我还让 bash 充当登录 shell。

SHELL ["/bin/bash", "-lc"]

稍后,我使用 Docker Compose 创建一个容器,并以相关用户的身份运行 shell 脚本。

entrypoint:
  - /bin/bash
  - '-lc'
command:
  - ~/.local/bin/ci

在脚本中ci,如果我执行source ~/.bashrc,脚本将无法找到rvm可执行文件。但是,如果我明确执行source "$HOME/.rvm/scripts/rvm",脚本将成功运行。

我的问题是,.rvm/scripts是的一部分.bashrc,那么,为什么采购.bashrc不起作用?

bash
  • 2 个回答
  • 54 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve