Telegram Group & Telegram Channel
🦀 Задача на Rust: "Найди пропавшее число"

Условие
У тебя есть Vec<String>, в котором находятся строки от "1" до "100", но одно число отсутствует.
Найди его без использования sort, HashMap, iter().sum() и т. д.
Можно использовать parse::<u32>().

Формат функции:


fn find_missing_number(data: &Vec<String>) -> u32


Решение через XOR:


fn find_missing_number(data: &Vec<String>) -> u32 {
let mut xor_full = 0;
let mut xor_data = 0;

for i in 1..=100 {
xor_full ^= i;
}

for s in data {
if let Ok(n) = s.parse::<u32>() {
xor_data ^= n;
}
}

xor_full ^ xor_data
}


Пример использования:


fn main() {
let mut data: Vec<String> = (1..=100)
.filter(|&x| x != 42)
.map(|x| x.to_string())
.collect();

use rand::seq::SliceRandom;
let mut rng = rand::thread_rng();
data.shuffle(&mut rng);

let missing = find_missing_number(&data);
println!("Пропущено: {}", missing); // Ожидается 42
}


Зависимости в `Cargo.toml`:


[dependencies]
rand = "0.8"


Объяснение:
XOR всех чисел от 1 до 100 ⊕ XOR из входных данных → пропущенное число.
Работает, потому что a ^ a = 0, 0 ^ b = b.
👍22



tg-me.com/rust_code/956
Create:
Last Update:

🦀 Задача на Rust: "Найди пропавшее число"

Условие
У тебя есть Vec<String>, в котором находятся строки от "1" до "100", но одно число отсутствует.
Найди его без использования sort, HashMap, iter().sum() и т. д.
Можно использовать parse::<u32>().

Формат функции:


fn find_missing_number(data: &Vec<String>) -> u32


Решение через XOR:


fn find_missing_number(data: &Vec<String>) -> u32 {
let mut xor_full = 0;
let mut xor_data = 0;

for i in 1..=100 {
xor_full ^= i;
}

for s in data {
if let Ok(n) = s.parse::<u32>() {
xor_data ^= n;
}
}

xor_full ^ xor_data
}


Пример использования:


fn main() {
let mut data: Vec<String> = (1..=100)
.filter(|&x| x != 42)
.map(|x| x.to_string())
.collect();

use rand::seq::SliceRandom;
let mut rng = rand::thread_rng();
data.shuffle(&mut rng);

let missing = find_missing_number(&data);
println!("Пропущено: {}", missing); // Ожидается 42
}


Зависимости в `Cargo.toml`:


[dependencies]
rand = "0.8"


Объяснение:
XOR всех чисел от 1 до 100 ⊕ XOR из входных данных → пропущенное число.
Работает, потому что a ^ a = 0, 0 ^ b = b.

BY Rust


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/rust_code/956

View MORE
Open in Telegram


Rust Telegram | DID YOU KNOW?

Date: |

NEWS: Telegram supports Facetime video calls NOW!

Secure video calling is in high demand. As an alternative to Zoom, many people are using end-to-end encrypted apps such as WhatsApp, FaceTime or Signal to speak to friends and family face-to-face since coronavirus lockdowns started to take place across the world. There’s another option—secure communications app Telegram just added video calling to its feature set, available on both iOS and Android. The new feature is also super secure—like Signal and WhatsApp and unlike Zoom (yet), video calls will be end-to-end encrypted.

If riding a bucking bronco is your idea of fun, you’re going to love what the stock market has in store. Consider this past week’s ride a preview.The week’s action didn’t look like much, if you didn’t know better. The Dow Jones Industrial Average rose 213.12 points or 0.6%, while the S&P 500 advanced 0.5%, and the Nasdaq Composite ended little changed.

Rust from sa


Telegram Rust
FROM USA