Created
March 6, 2019 16:58
-
-
Save guillem/28cf6fbe8db8990e10c47f6c6692591d to your computer and use it in GitHub Desktop.
Guessing Game (Rust vs. Go)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "os" | |
import "bufio" | |
import "strconv" | |
func main() { | |
f := bufio.NewWriter(os.Stdout) | |
defer f.Flush() | |
const MIN = 1 | |
const MAX = 1000001 | |
for secret := MIN; secret <= MAX-1; secret++ { | |
f.WriteString(strconv.Itoa(secret)) | |
min := MIN | |
max := MAX | |
for { | |
guess := (min + max) / 2 | |
if guess < secret { | |
f.WriteString("<") | |
min = guess | |
} else if guess > secret { | |
f.WriteString(">") | |
max = guess | |
} else { | |
f.WriteString(".\n") | |
break | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::Ordering; | |
use std::io::{self, Write}; | |
const MIN: u32 = 1; | |
const MAX: u32 = 1_000_001; | |
fn main() { | |
let mut out = io::stdout(); | |
for secret in MIN..MAX { | |
out.write(secret.to_string().as_bytes()).unwrap(); | |
let mut min = MIN; | |
let mut max = MAX; | |
loop { | |
let guess = (min + max) / 2; | |
match guess.cmp(&secret) { | |
Ordering::Less => { | |
out.write("<".as_bytes()).unwrap(); | |
min = guess; | |
}, | |
Ordering::Greater => { | |
out.write(">".as_bytes()).unwrap(); | |
max = guess; | |
}, | |
Ordering::Equal => { | |
out.write(".\n".as_bytes()).unwrap(); | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment