Skip to content

Instantly share code, notes, and snippets.

@Krelix
Last active May 13, 2016 10:25
Show Gist options
  • Save Krelix/d2ab6912a4048794f9ee5e6c3c527f32 to your computer and use it in GitHub Desktop.
Save Krelix/d2ab6912a4048794f9ee5e6c3c527f32 to your computer and use it in GitHub Desktop.
Reddit Programming Challenge 266
fn bonus (input: &String) {
// input is the same as in the main.rs
let mut adj_mat:Vec<usize> = Vec::new();
let mut length = 0;
for line in input.split('\n') {
let connections: Vec<_> = line.split_whitespace().collect();
let conn_to:usize = parse_int(connections[0].to_string());
// Tabs from input not handled...
if conn_to <= 0 {
continue;
} else if connections.len() < 2 {
// First line used to create a vector of size length*length
length = conn_to;
for _ in 0..length*length {
adj_mat.push(0)
};
continue;
}
let conn_to = parse_int(connections[1].to_string());
let ij = (conn_from -1) * length + (conn_to - 1);
let ji = (conn_to -1) * length + (conn_from - 1);
if ij < adj_mat.len() {
adj_mat[ij] += 1;
}
if ji < adj_mat.len() {
adj_mat[ji] += 1;
}
}
for i in 0..adj_mat.len() {
print!("{} ", adj_mat[i]);
if (i +1)%length == 0 {
println!("");
}
}
}
// char to int parsing method
fn parse_int(str: String) -> usize {
str.chars().fold(0, |val, c| (val*10 + (c.to_digit(10).unwrap()) as usize))
}
// Read input, build an array of connections and prints it
fn build_edges(input: &String) {
let mut edges:Vec<usize> = Vec::new();
for line in input.split('\n') {
for connection in line.split(' ') {
let index = parse_int(connection.to_string());
if index >= edges.len() {
edges.push(1);
} else {
edges[index] += 1;
}
}
}
for i in 1..edges.len() {
println!("Node {} has a degree of {}", i, edges[i]);
}
}
fn main() {
let input:String = "16
1 2
1 3
2 3
1 4
3 4
1 5
2 5
1 6
2 6
3 6
3 7
5 7
6 7
3 8
4 8
6 8
7 8
2 9
5 9
6 9
2 10
9 10
6 11
7 11
8 11
9 11
10 11
1 12
6 12
7 12
8 12
11 12
6 13
7 13
9 13
10 13
11 13
5 14
8 14
12 14
13 14
1 15
2 15
5 15
9 15
10 15
11 15
12 15
13 15
1 16
2 16
5 16
6 16
11 16
12 16
13 16
14 16
15 16".to_string();
build_edges(&input);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment