add initial data
This commit is contained in:
commit
c4e841b4bc
43 files changed
+5284
No files matched your search
@@ -0,0 +1,104 @@
|
||||
use std::convert::TryInto;
|
||||
|
||||
trait Matrix {
|
||||
fn column_sums(&self) -> Vec<i32>;
|
||||
fn gamma_epsilon_rate(&self) -> (i32, i32);
|
||||
fn power_consumption(&self) -> i32;
|
||||
}
|
||||
|
||||
struct Data {
|
||||
data: Vec<Vec<i32>>,
|
||||
rows: i32,
|
||||
columns: i32,
|
||||
}
|
||||
|
||||
impl Matrix for Data {
|
||||
|
||||
fn column_sums(&self) -> Vec<i32> {
|
||||
let mut result: Vec<i32> = Vec::new();
|
||||
|
||||
for c in 0..self.columns {
|
||||
let mut column_result = 0;
|
||||
for r in 0..self.rows {
|
||||
column_result += self.data
|
||||
.iter()
|
||||
.nth(r as usize)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.nth(c
|
||||
.try_into()
|
||||
.unwrap()
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
result.push(column_result);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn gamma_epsilon_rate(&self) -> (i32, i32) {
|
||||
let mut result: Vec<i32> = Vec::new();
|
||||
for value in self.column_sums() {
|
||||
if value > self.rows / 2 {
|
||||
result.push(1)
|
||||
} else {
|
||||
result.push(0)
|
||||
}
|
||||
}
|
||||
return (bin2dec(complement(&result)), bin2dec(result));
|
||||
}
|
||||
|
||||
fn power_consumption(&self) -> i32 {
|
||||
let (gamma, epsilon) = self.gamma_epsilon_rate();
|
||||
gamma * epsilon
|
||||
}
|
||||
}
|
||||
|
||||
fn bin2dec(bin: Vec<i32>) -> i32 {
|
||||
let mut result = 0;
|
||||
let length = bin.len() as u32;
|
||||
for i in 0..length {
|
||||
result += 2_i32.pow(length-i-1) * bin.
|
||||
iter()
|
||||
.nth(i.try_into().unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fn complement(input: &Vec<i32>) -> Vec<i32> {
|
||||
let mut result: Vec<i32> = Vec::new();
|
||||
for value in input {
|
||||
if value.to_owned() == 0 {
|
||||
result.push(1);
|
||||
} else {
|
||||
result.push(0)
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read_data(filename: &str) -> Data {
|
||||
let content = std::fs::read_to_string(filename).unwrap();
|
||||
let mut data: Vec<Vec<i32>> = Vec::new();
|
||||
for line in content.lines() {
|
||||
let mut row: Vec<i32> = Vec::new();
|
||||
for char in line.chars() {
|
||||
row.push(char as i32 - 0x30);
|
||||
}
|
||||
data.push(row);
|
||||
}
|
||||
let rows = data.len() as i32;
|
||||
let columns = data.iter().nth(0).unwrap().len() as i32;
|
||||
return Data{data, rows, columns};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let data = read_data("data.txt");
|
||||
|
||||
println!("{:?}", data.gamma_epsilon_rate());
|
||||
println!("{:?}", data.power_consumption());
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user