Advertisement
cwchen

[Rust] non-redundent-digit numbers demo

Aug 23rd, 2017
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.40 KB | None | 0 0
  1. use std::io;
  2. use std::io::Write;
  3. use std::process;
  4. use std::collections::HashSet;
  5.  
  6. fn main() {
  7.     // Prompt for user input
  8.     print!("Input a number: ");
  9.     let _ = io::stdout().flush();
  10.  
  11.     // Receive user input
  12.     let mut input = String::new();
  13.     io::stdin()
  14.         .read_line(&mut input)
  15.         .expect("failed to read from stdin");
  16.  
  17.     // Parse the number
  18.     let n = match input.trim().parse::<u32>() {
  19.         Ok(i) => i,
  20.         Err(_) => {
  21.             println!("Invalid integer");
  22.  
  23.             // Exit the program with abnormal status code
  24.             process::exit(1);
  25.         }
  26.     };
  27.  
  28.     let x: i32 = 10;
  29.     for i in 1..(x.pow(n)) {
  30.         /* Convert number to an iterator of char.
  31.            Then, insert char to set. */
  32.         let num_string = i.to_string();
  33.         let mut chars = num_string.chars();
  34.         let mut set = HashSet::new();
  35.         let mut c = chars.next();
  36.         while c != None {
  37.             set.insert(c);
  38.             c = chars.next();
  39.         }
  40.  
  41.         // Get the digit number of i
  42.         let mut digit = 0;
  43.         let mut j = i;
  44.         while j > 0 {
  45.             j = j / 10;
  46.             digit += 1;
  47.         }
  48.  
  49.         // Check whether i fits our criteria
  50.         if set.len() as i32 >= digit {
  51.             // Show i in console
  52.             print!("{} ", i);
  53.         }
  54.     }
  55.  
  56.     // Print tailing newline
  57.     println!("");
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement