MinMax
2 minutos de lectura
Se nos proporciona el siguiente sitio web para escribir una solución de un reto de programación:
Problema
Necesitamos escribir un programa que tome una lista de números separados por espacios y muestre los valores mínimo y máximo. Por ejemplo:
"4.23 0.25 2.4 7.35 3.78"
->"0.25 7.35"
Solución
Como nos dejan usar C, C ++, Python y Rust, vamos a escribir una solución en cada lenguaje, porque sí.
C
#include <float.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
// take in the numbers
char input[4096] = { 0 };
fgets(input, sizeof(input), stdin);
double numbers[1024] = { 0 };
char* token = strtok(input, " ");
int i = 0;
while (token != NULL) {
numbers[i++] = atof(token);
token = strtok(NULL, " ");
}
int length = i;
// calculate answer
double min = DBL_MAX;
double max = DBL_MIN;
for (i = 0; i < length; i++) {
min = numbers[i] < min ? numbers[i] : min;
max = numbers[i] > max ? numbers[i] : max;
}
char answer_min[1024] = { 0 };
snprintf(answer_min, sizeof(answer_min), "%.2lf", min);
i = strlen(answer_min) - 1;
while (answer_min[i] == '0') {
answer_min[i--] = '\0';
}
char answer_max[1024] = { 0 };
snprintf(answer_max, sizeof(answer_max), "%.2lf", max);
i = strlen(answer_max) - 1;
while (answer_max[i] == '0') {
answer_max[i--] = '\0';
}
// print answer
printf("%s\n%s\n", answer_min, answer_max);
return 0;
}
C++
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
int main() {
// take in the numbers
std::string s;
std::vector<double> numbers;
double n;
std::getline(std::cin, s);
std::istringstream iss(s);
while (iss >> n) {
numbers.push_back(n);
}
// calculate answer
double min = std::numeric_limits<double>::max();
double max = std::numeric_limits<double>::min();
for (double n : numbers) {
min = n < min ? n : min;
max = n > max ? n : max;
}
// print answer
std::cout << min << "\n" << max << std::endl;
return 0;
}
Python
# take in the numbers
numbers = list(map(float, input().split()))
# calculate answer
answer = f'{min(numbers)}\n{max(numbers)}'
# print answer
print(answer)
Rust
use std::io;
fn main() {
// take in the numbers
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let numbers: Vec<f64> = input
.split(" ")
.map(|s| s.parse().expect("Please enter a valid number"))
.collect();
// calculate answer
let min = numbers
.iter()
.min_by(|a, b| a.partial_cmp(b).expect("Minimum not found"))
.unwrap();
let max = numbers
.iter()
.max_by(|a, b| a.partial_cmp(b).expect("Maximum not found"))
.unwrap();
let answer = format!("{}\n{}", min, max);
// print answer
println!("{}", answer);
}
Flag
Usando cualquiera de estos programas, podemos resolver el reto y capturar la flag:
HTB{aLL_maX3d_0uT_but_n3v3r_l3ft_0ut}