Finish assignments for course 2

This commit is contained in:
2020-12-12 10:53:27 -05:00
parent 99ef6d4d1c
commit 77828d0eb9
3 changed files with 54 additions and 4 deletions

25
misc/two_sums.py Normal file
View File

@@ -0,0 +1,25 @@
def two_sum(t, xs_list, xs_set):
for x in xs:
y = t - x
if x != y and y in xs_set:
return True
return False
if __name__ == "__main__":
with open("../data/c2a4.txt") as f:
xs = list(map(int, f.readlines()))
xs_min = [x for x in xs if x < 0]
xs_max_set = set([x for x in xs if x > 0])
limit = 10000
two_sums = 0
for t in range(-limit, limit + 1):
if t % 10 == 0:
print(t)
if two_sum(t, xs_min, xs_max_set):
two_sums += 1
print(two_sums)

View File

@@ -83,6 +83,11 @@ fn c2a4() {
println!("c2a4={:?}", r);
}
#[allow(dead_code)]
fn c3a1() {
println!("continue here");
}
fn main() {
// c1a2();
// c1a3();
@@ -90,5 +95,6 @@ fn main() {
// c2a1();
// c2a2();
// c2a3();
c2a4();
// c2a4();
c3a1();
}

View File

@@ -1,13 +1,32 @@
use std::collections::HashSet;
use std::iter::FromIterator;
fn two_sum(t: i64, xs_vec: &Vec<i64>) {
fn two_sum(t: i64, xs: &Vec<i64>, ys: &HashSet<i64>) -> bool {
for &x in xs {
let y = t - x;
if x != y && ys.contains(&y) {
return true;
}
}
false
}
pub fn find_two_sums(xs: Vec<i64>) -> usize {
let mut xs_min: Vec<i64> = xs.to_vec();
xs_min.retain(|&i| i < 0);
let mut xs_max: Vec<i64> = xs.to_vec();
xs_max.retain(|&i| i >= 0);
let xs_max_set: HashSet<i64> = HashSet::from_iter(xs_max);
0
let mut r: usize = 0;
for t in -10000..10001 {
if two_sum(t, &xs_min, &xs_max_set) {
r += 1
}
}
r
}