Skip to content
This repository has been archived by the owner on Aug 11, 2022. It is now read-only.

elbaro/project-euler-100

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Project Euler 100 - in Rust

How to run

cargo run --bin 123 --release

To generate the status table below,

cargo run --bin status --release

Status

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100

To repect the PE's no spoiler policy, this repo does not provide solutions after the first hundred problems.

(The problem 1~100 are coding rather than math)

Still, these solutions provide examples of how things are implmeneted in rust:

  • initializing constant table
  • recursive call
  • big int
  • parallel computation
  • iterator techniques (iproduct, permutation, etc)
  • short-circuit the computation (label-break-with-value)
  • 2d array

Rust Features I need

  • no aggregation for num-bigint
(1..=100).map(|x| BigUint::new(x)).sum() // no sum or product for BigInt
(1..=100).map(|x| BigUint::new(x)).fold(BigUint::new(0), ..) // you need fold
  • Easier type casting in aggregation (e.g. sum of u32 to u64)
let a:Vec<i32> = ...;
let sum:i64 = a.iter().map(|x| x as i64).sum(); // ugly casting step
let sum:i64 = a.iter().cast(i64).sum(); // looks good
let sum:i64 = a.iter().sum(); // better: sum<i32, i64>
  • iterator for multiple variables
// convert this to iterator
// which enables `sum`, `max_by_key`, `par_iter`, etc.

for i in 0..100 {
    for j in 0..100 {
        do(i,j);
    }
}

// ok: (0..100) x (0..100)
iproduct!(0..100, 0..100).for_each(|&(i,j)| { .. });

// error: (0..100) x [2, 3, 5, 7, 11, ..]
iproduct!(0..100,
           primal::Primes::all().take_while(|&x| x<=1_000))
    .for_each(|&(i,j)| { .. });
    
// ok: [2, 3, 5, 7, 11, ..] x (0..100) 
iproduct!(primal::Primes::all().take_while(|&x| x<=1_000), 0..100)
    .for_each(|&(i,j)| { .. });
    

// flat_map is hard to write & read
// imagine adding third loop with k.
(0..100).flat_map(|i| (0..100).iter().map(|j| (i,j)))..    
  • rustc does not infer array length
// compile error
let coins:[usize;] = [1, 2, 5, 10, 20, 50, 100, 200usize];

// vec as an wrapper around my raw fixed-size data
// the set of coins is never going to change
let coins = vec![1, 2, 5, 10, 20, 50, 100, 200usize];

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages