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
    • 最新
    • 标签
主页 / coding / 问题

问题[recursion](coding)

Martin Hope
Wayne Riesterer
Asked: 2025-01-12 17:12:37 +0800 CST

递归、参数和返回类型

  • 1

如何才能将输入参数n更改为i8并且该代码仍然有效?

fn fact(n: i128) -> i128 {
    if n != 1 { n * fact(n - 1) } else { 1 }
}
recursion
  • 2 个回答
  • 78 Views
Martin Hope
pkra2
Asked: 2024-06-01 16:48:59 +0800 CST

为什么通过引用传递会改变答案,同时产生唯一的子集?

  • 5

这是生成数组的唯一子集问题的解决方案nums:

#include <bits/stdc++.h>
using namespace std;
void solveRec(vector<int> ss, set<vector<int>> &ans, vector<int> &nums, int i)
{
    if (i == nums.size())
    {
        sort(ss.begin(), ss.end());
        ans.insert(ss);
        return;
    }

    ss.push_back(nums[i]);
    solveRec(ss, ans, nums, i + 1);
    ss.pop_back();

    solveRec(ss, ans, nums, i + 1);
}

该函数采用整数数组nums作为输入以及一组向量ans来存储唯一子集。虽然传递ss用于按值存储当前子集的向量会产生正确的答案,但通过引用传递它却不会,为什么会这样呢?

就nums这样吧4 4 4 1

通过引用传递(不正确)会产生:

1 
1 1 
1 1 4 
1 4 
1 4 4 
1 4 4 4

按值传递(正确)会产生:

1 
1 4 
1 4 4 
1 4 4 4 
4 
4 4 
4 4 4

请帮忙!!!

recursion
  • 1 个回答
  • 15 Views
Martin Hope
ThoBo
Asked: 2024-03-27 18:51:38 +0800 CST

可以采用什么结构来避免使用 RefCell?

  • 6

我在 Rust 中创建了一些代码,应该允许我设置递归端口、具有源的端口、可以具有源的端口等。但是,由于借用问题,我实现此结构的唯一方法是通过 RefCell,实际上我不想使用 RefCell (它允许我编译在运行时可能会出现恐慌的代码)或 std 中的任何其他库。

问题是,由于借用问题,我似乎无法为我的端口设置值。

struct Port<'a> {
    value: i32,
    source: Option<&'a Port<'a>>,
}

impl<'a> Port<'a> {
    fn new(value: i32) -> Port<'a> {
        Port { value, source: None }
    }

    fn link(&mut self, source: &'a Port<'a>) {
        self.source = Some(source);
    }

    fn get_source_value(&self) -> Option<i32> {
        match self.source {
            Some(port) => {
                let inner_source_value = port.get_source_value();
                match inner_source_value {
                    Some(value) => Some(value),
                    None => Some(port.value),
                }
            }
            None => None,
        }
    }
}

fn main() {
    let mut top_port = Port::new(10);
    let mut sub_port = Port::new(20);
    let mut sub_sub_port = Port::new(30);

    sub_port.link(&top_port);
    sub_sub_port.link(&sub_port);

    top_port.value = 400; // can't do this because top_port is borrowed

    println!("Value of sub_sub_port's source's source's source: {:?}", sub_sub_port.get_source_value());
}

出现问题的原因是当 sub_port 和 sub_sub_port 链接到 top_port 时,top_port 被借用。发生这种情况对我来说并不奇怪,我可以使用 RefCell 和 RC 来解决这个问题。

use std::cell::RefCell;

struct Port<'a> {
    value: i32,
    source: Option<&'a RefCell<Port<'a>>>,
}

impl<'a> Port<'a> {
    fn new(value: i32) -> RefCell<Port<'a>> {
        RefCell::new(Port { value, source: None })
    }

    fn link(&mut self, source: &'a RefCell<Port<'a>>) {
        self.source = Some(source);
    }

    fn get_source_value(&self) -> Option<i32> {
        match self.source {
            Some(port_ref) => {
                let port = port_ref.borrow();
                let inner_source_value = port.get_source_value();
                match inner_source_value {
                    Some(value) => Some(value),
                    None => Some(port.value),
                }
            }
            None => None,
        }
    }
}

fn main() {
    let top_port = Port::new(10);
    let sub_port = Port::new(20);
    let sub_sub_port = Port::new(30);

    sub_sub_port.borrow_mut().link(&sub_port);
    sub_port.borrow_mut().link(&top_port);

    top_port.borrow_mut().value = 400;

    println!("Value of sub_sub_port's source's source's source: {:?}", sub_sub_port.borrow().get_source_value());
}

然而,我的目标是不使用任何标准库功能,并且仅以安全的方式使用 Rust。我可以通过什么方式重组我的代码以避免使用 RefCell 或任何其他标准库?或者更好的是,我可以使用更多的生命周期来修复我的原始代码吗?

先感谢您!

recursion
  • 1 个回答
  • 62 Views
Martin Hope
Praveen Perera
Asked: 2024-03-16 02:31:18 +0800 CST

如何修复递归函数溢出错误?

  • 3

该程序旨在计算质子穿过铝时对 20000 片 0.025μm 铝片的不同阻止本领。每个切片的阻止本领都会发生变化,因此必须按每个切片计算阻止本领和能量减法。

即使在尝试增加递归限制后,我也会收到堆栈溢出错误。任何援助将不胜感激!distance(x,E,n)有变量x,即步长,E即能量,n即停止本领。distance(0,13000,0.13124)第一步、能量和停止力也是如此。

这是我的代码:

import sys

sys.setrecursionlimit(10**9)

def distance(x,E,n): 
    step = x + 1 
    if (step >= 20000):
        return E
    
    energy = E - 0.025 * 1/n #E - distance interval per step * stopping power
    stop = -0.0079199 + 0.040703 * energy**(-0.4) + 0.0022677 * energy**(0.25) + 0.000058309 * energy**(0.8) #1/stopping power
   
    return distance(step,energy,stop)

print(distance(0,13000,0.131234))
recursion
  • 1 个回答
  • 19 Views
Martin Hope
user3758232
Asked: 2024-03-02 00:28:32 +0800 CST

JSON 架构中的递归项

  • 5

我正在设计一个带有递归元素的 JSON 模式。该元素不在根,而是在子模式中:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "http://example.org/json-schema/struct.schema.json",
    "type": "array",
    "items": {
        "title": "Structure",
        "type": "object",
        "properties": {
            "id": {
                "title": "ID",
                "type": "string"
            },
            "label": {
                "title": "Label",
                "type": "string"
            },
            "children": {
                "$anchor": "children",
                "title": "Children",
                "type": "array",
                "items": {
                    "title": "Structure Item",
                    "type": "object",
                    "properties": {
                        "id": {
                            "title": "ID",
                            "type": "string"
                        },
                        "href": {
                            "title": "Reference",
                            "type": "string"
                        },
                        "label": {
                            "title": "Structure Item Label",
                            "type": "string"
                        },
                        "sort_label": {
                            "title": "Sort Label",
                            "type": "string"
                        },
                        "children": {"$ref": "children"}
                    }
                },
                "anyOf": [
                    {"required": ["id", "href"]},
                    {"required": ["id", "children"]}
                ]
            }
        },
        "required": ["id", "label", "children"]
    }
}

当我尝试编译模式时,python-fastjsonschema由于items.properties.children.

从https://json-schema.org/understanding-json-schema/structuring#recursion中的示例中,我不清楚什么是允许递归的,什么是不允许的。不允许$ref在 s 内递归s,但s 到根锚点会在有效示例中列出。它们都创建了一个循环(这确实是递归的目的!)。我认为对于非根锚点来说是可以的,但显然不是。$def$ref$ref

我还尝试使用未命名的锚点,如"children": {"$ref": "#/items/properties/children"},并且模式编译,但在验证时抛出错误。

我该如何建模这个模式?

recursion
  • 1 个回答
  • 19 Views
Martin Hope
Istvan
Asked: 2024-01-14 03:56:43 +0800 CST

如何在递归函数中累加值?[复制]

  • 5
这个问题在这里已经有了答案:
将 mut 引用传递给函数,然后将其取回 (2 个答案)
5 小时前关闭。

我试图了解借用检查器在递归函数调用情况下的工作原理:

fn visit_dirs_rec(dir: &Path, mut acc: Vec<PathBuf>) -> Result<Vec<PathBuf>, io::Error> {
    if dir.is_dir() {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs_rec(&path, &acc)?;
            } else if path.is_file() {
                acc.push(path)
            } else {
                error!("{:?}", path);
            }
        }
    }
    Ok(acc)
}

fn visit_dirs(dir: &Path) -> Result<Vec<PathBuf>, io::Error> {
    visit_dirs_rec(dir, vec![])
}
error[E0382]: use of moved value: `acc`
  --> src/main.rs:16:39
   |
10 | fn visit_dirs_rec(dir: &Path, mut acc: Vec<PathBuf>) -> Result<Vec<PathBuf>, io::Error> {
   |                               ------- move occurs because `acc` has type `Vec<PathBuf>`, which does not implement the `Copy` trait
11 |     if dir.is_dir() {
12 |         for entry in std::fs::read_dir(dir)? {
   |         ------------------------------------ inside of this loop
...
16 |                 visit_dirs_rec(&path, acc)?;
   |                                       ^^^ value moved here, in previous iteration of loop
   |
note: consider changing this parameter type in function `visit_dirs_rec` to borrow instead if owning the value isn't necessary
  --> src/main.rs:10:40
   |
10 | fn visit_dirs_rec(dir: &Path, mut acc: Vec<PathBuf>) -> Result<Vec<PathBuf>, io::Error> {
   |    -------------- in this function     ^^^^^^^^^^^^ this parameter takes ownership of the value
help: consider cloning the value if the performance cost is acceptable
   |
16 |                 visit_dirs_rec(&path, acc.clone())?;
   |                                          ++++++++

For more information about this error, try `rustc --explain E0382`.
warning: `api` (bin "api") generated 1 warning
error: could not compile `api` (bin "api") due to previous error; 1 warning emitted

有没有办法让借用检查员在没有 .clone 的情况下感到满意?

recursion
  • 1 个回答
  • 42 Views
Martin Hope
J.B
Asked: 2023-11-28 03:28:09 +0800 CST

OCaml 高阶函数

  • 5

有人请解释一下 OCaml 问题中的算法。

我有解决方案,但我不明白。

定义 iterup:(int * 𝛼 → 𝛼) → int → int → 𝛼 → 𝛼。Iterup 采用一个接收当前数字和累加器的函数。它从给定的开始到给定的结束递增计数器编号,并每次应用该函数。最后一个参数是累加器的起始值。

解决办法是

let rec iterup f st ed acc = 
  if st > ed then 
    acc 
  else 
    iterup f (st+1) ed (f st acc)

我不明白的是为什么我们在最后一部分(fns)中同时采用 n 和 s 作为 f 的参数。当我们谈论尾递归时,这意味着什么?

recursion
  • 1 个回答
  • 32 Views
Martin Hope
Philippe Fanaro
Asked: 2023-11-16 21:13:36 +0800 CST

如何使用 Cypher 递归创建树 (Neo4j)

  • 6

我正在尝试使用 Cypher 在 Neo4j 上复制 SGF 游戏树。这棵树的形状是这样的:

type GameTree = {
  id: number;
  data: { [key: string]: string[] };
  parentId: number | null;
  children: GameTree[];
};

这是我正在尝试解决的创建查询:

UNWIND $moves AS move

MATCH (parent)

WHERE ((parent:GameNode) OR (parent:MoveNode))
  AND parent.game_id = $gameId
  AND parent.id = move.parentId

CREATE   (parent)
        -[:NEXT_MOVE]
       ->(:MoveNode{
           game_id: $gameId,
           id:      move.id
         })

最初,树的根是 a GameNode,我单独创建它,因为它包含有趣的元数据。无论如何,这不会像这样工作,因为在UNWINDandMATCH子句时,只存在一个父级,其余的将/应该递归创建。

有没有办法在 Cypher 中进行这种递归创建?也许有一些我似乎找不到的递归关键字(这似乎是一个常见的问题......)?也许某处有一个有用的 APOC 程序?

作为解决方法,我正在考虑MoveNode首先创建所有 s,然后使用上面的查询将它们重新串在一起。它看起来像这样:

// 1. Create All The Move Nodes

UNWIND $moveNodes AS move

CREATE (:MoveNode{
         game_id: move.game_id,
         id:      move.id
       })

// 2. Tie them to their Parents

WITH move

MATCH (parent{
        game_id: move.game_id,
        id:      move.parentId
      }),
      (m:MoveNode{
        game_id: move.game_id,
        id:      move.id
      })

WHERE parent:GameNode
   OR parent:MoveNode
  
CREATE (parent)-[:NEXT_MOVE]->(m)
recursion
  • 1 个回答
  • 25 Views
Martin Hope
Alibi Tolebay
Asked: 2023-10-25 01:21:48 +0800 CST

递归求幂中的浮点精度 MIPS

  • 5

我正在尝试编写 MIPS 代码来递归计算数字的幂。一切似乎都是正确的,但在一个测试用例中我得到了5^-2 = 0.04000000000000001. 我认为这是由于我的计算机的体系结构造成的。我是对的还是我的代码有问题?

为了更好地理解,数据段中有一个双精度数组和一个整数幂数组。

这是代码:

.data
double_array: .double 5.0 2.0 -3.0 -3.0 -4.2 5.0 -2.0 0.0 0.0
power_array: .word -2 -4 2 1 0 -2 -3 0 10
N_OF_CASES: .word 9
str_case: .asciiz "case_"
str_colon: .asciiz ": "
str_equal: .asciiz " = "
str_power: .asciiz "^"
str_newLine: .asciiz "\n"
one: .double 1.0
zero: .double 0.0

main:
    lw $t1, N_OF_CASES
    la $t2, double_array
    la $t3, power_array
    li $t4, 0

loop:
    lw $a1, ($t3)
    lw $t0, ($t3)
    l.d $f14, ($t2)
    l.d $f16, ($t2)
    jal power
    
    li $v0, 3
    mov.d $f12, $f16
    syscall
    
    li $v0, 4
        la $a0, str_power
        syscall
        
        li $v0, 1
        move $a0, $t0
        syscall
        
        li $v0, 4
        la $a0, str_equal
        syscall
        
        li $v0, 3
        mov.d $f12, $f0
        syscall
        
        la $v0, 4
        la $a0, str_newLine
        syscall
    
    addi $t2, $t2, 8
    addi $t3, $t3, 4
    addi $t4, $t4, 1
    subi $t1, $t1, 1
    
    bnez $t1, loop
    
    li $v0 10
    syscall
power:
    andi $sp 0xfffffff8
    addi $sp $sp -16
    s.d $f20 ($sp)
    sw $ra 8($sp)
    
    li $t7, 0
    beq $a1, $t7, base_case
    
    bgez $a1, not_negative
    
    l.d $f2, one
    div.d $f14, $f2, $f14
    li $t6, -1
    mul $a1, $a1, $t6
    j power

not_negative:
    mov.d $f2, $f14
    subi $a1, $a1, 1
    jal power
    mul.d $f0, $f0, $f2

power_done:
    l.d $f20, ($sp)
    lw $ra, 8($sp)
    addi $sp, $sp, 16
    
    jr $ra
    
base_case:
    l.d, $f0, one
    j power_done
recursion
  • 1 个回答
  • 35 Views
Martin Hope
Лука
Asked: 2023-08-20 16:07:18 +0800 CST

在循环中调用自身的递归函数的时间复杂度

  • 6

给定函数

void function(n) 
{        
for (int i = n; i > 0; i = floor(i/2))
 {            
  function(floor(i/2));
 }               
} 

我很难找到此类函数的时间复杂度。Chatgpt 说它是log(n)但我相信它必须更大。如何写递推方程或者解决这个问题的正确方法是什么?

recursion
  • 1 个回答
  • 37 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