TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Polyglot Maxxie and Minnie

6 点作者 0823498723498727 个月前

1 comment

lifthrasiir7 个月前
As the author has correctly wondered, the Rust solution can be made much simpler especially when itertools are available (playground [1]):<p>[1] <a href="https:&#x2F;&#x2F;play.rust-lang.org&#x2F;?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=4d4f33c018dc4732996d8163f98182b7" rel="nofollow">https:&#x2F;&#x2F;play.rust-lang.org&#x2F;?version=stable&amp;mode=debug&amp;editio...</a><p><pre><code> fn from_digits(v: Vec&lt;u8&gt;) -&gt; u32 { v.into_iter() .map(|x| (x + b&#x27;0&#x27;) as char) .collect::&lt;String&gt;() .parse() .unwrap() } fn maxmin(num: u32) -&gt; (u32, u32) { let num = num.to_string(); let n = num.len(); let mut numv: Vec&lt;u8&gt; = num.chars().map(|c| c as u8 - b&#x27;0&#x27;).collect(); let mut new: Vec&lt;Vec&lt;u8&gt;&gt; = Vec::new(); new.push(numv.clone()); for (a, b) in (0..n).tuple_combinations() { numv.swap(a, b); new.push(numv.clone()); } let (min, max) = new .into_iter() .filter(|x| x[0] != 0) .minmax() .into_option() .unwrap(); (from_digits(min), from_digits(max)) } </code></pre> The first and foremost, `Itertools::minmax` is a thing. So the entire min&#x2F;max thing can be collapsed into a single method call. Since it naturally operates on an iterator, which is inherently lazily evaluated, it makes sense to make the whole thing amenable to be an iterator.<p>I tried to be faithful enough to the original solution, because there are many corners to cut if you know what you&#x27;re looking for. It is possible to generate every number on demand without `new`, but I stopped here for the clarity. I intentionally retained the conversion between ASCII digits and actual digits to be faithful to the original approach, but that can be also eliminated easily. I did make use of the fact that all numeric strings contain ASCII digits b&#x27;0&#x27; through b&#x27;9&#x27;, in order to show that vectors can be lexicographically compared just like strings.