如何才能将输入参数n
更改为i8
并且该代码仍然有效?
fn fact(n: i128) -> i128 {
if n != 1 { n * fact(n - 1) } else { 1 }
}
如何才能将输入参数n
更改为i8
并且该代码仍然有效?
fn fact(n: i128) -> i128 {
if n != 1 { n * fact(n - 1) } else { 1 }
}
这是生成数组的唯一子集问题的解决方案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
请帮忙!!!
我在 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 或任何其他标准库?或者更好的是,我可以使用更多的生命周期来修复我的原始代码吗?
先感谢您!
该程序旨在计算质子穿过铝时对 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))
我正在设计一个带有递归元素的 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"}
,并且模式编译,但在验证时抛出错误。
我该如何建模这个模式?
我试图了解借用检查器在递归函数调用情况下的工作原理:
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 的情况下感到满意?
有人请解释一下 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 的参数。当我们谈论尾递归时,这意味着什么?
我正在尝试使用 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
,我单独创建它,因为它包含有趣的元数据。无论如何,这不会像这样工作,因为在UNWIND
andMATCH
子句时,只存在一个父级,其余的将/应该递归创建。
有没有办法在 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)
我正在尝试编写 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
给定函数
void function(n)
{
for (int i = n; i > 0; i = floor(i/2))
{
function(floor(i/2));
}
}
我很难找到此类函数的时间复杂度。Chatgpt 说它是log(n)但我相信它必须更大。如何写递推方程或者解决这个问题的正确方法是什么?