Browse Source

Merge pull request #3 from themultiplexer/hw2

hw2
Vausra 8 years ago
parent
commit
8ed5b7621f
No account linked to committer's email address

+ 9
- 0
hw2/simu1/ANSWERS.md View File

@@ -0,0 +1,9 @@
1
+## Antworten zur Simulation 1 (hw2)
2
+
3
+1. Beim Ausführen stürzt das Programm mit der Fehlermeldung `Segmentation Fault` ab.
4
+2. GDB gibt den Hinweis `Program received signal SIGSEGV, Segmentation fault.` aus.
5
+3. Valgrind zeigt den Fehler `Invalid Read` und sowohl die Adresse im Speicher als auch die Zeile im Code, in der der Fehler auftritt. Das bedeutet, dass auf eine undefinierte Adresse zugegriffen wird. Da die Zeile im Code auch ausgegeben wird, lässt sich der Ursprung des Fehlers leicht eingrenzen.
6
+4. Das Programm `malloc` erzeugt keine Ausgabe und crasht nicht. GDB bestätigt das: `Inferior 1 (process 2982) exited normally`. Mithilfe von Valgrind sehen wir, dass 10 Bytes nicht freigegeben wurden: `LEAK SUMMARY: definitely lost: 10 bytes in 1 blocks`.
7
+5.
8
+6. Das Programm (`intArray2`) gibt den Wert `0` aus und läuft ohne Fehler. Valgrind weist uns auf einen `invalid read` an der betreffenden Stelle hin.
9
+

+ 11
- 0
hw2/simu1/Makefile View File

@@ -0,0 +1,11 @@
1
+CC=gcc
2
+CFLAGS=-g
3
+RM=rm -f
4
+TARGET=null malloc intArray1 intArray2 free
5
+.PHONY: all clean
6
+all: $(TARGET)
7
+clean:
8
+	$(RM) null malloc intArray1 intArray2 free
9
+
10
+$(TARGET): $(TARGET).c
11
+	$(CC) $< $(CFLAGS) -o $@

+ 7
- 0
hw2/simu1/free.c View File

@@ -0,0 +1,7 @@
1
+/* free.c */
2
+#include <stdlib.h>
3
+int main(char* argv[], int argc) {
4
+  char* testString = malloc(10 * sizeof(char));
5
+  free(testString[10]);
6
+  free(testString);
7
+}

+ 7
- 0
hw2/simu1/intArray1.c View File

@@ -0,0 +1,7 @@
1
+/* intArray1.c */
2
+#include <stdlib.h>
3
+int main(char* argv[], int argc) {
4
+  int* intArray = malloc(100 * sizeof(int));
5
+  intArray[100] = 0;
6
+  free(intArray);
7
+}

+ 8
- 0
hw2/simu1/intArray2.c View File

@@ -0,0 +1,8 @@
1
+/* intArray2.c */
2
+#include <stdlib.h>
3
+#include <stdio.h>
4
+int main(char* argv[], int argc) {
5
+  int* intArray = malloc(100 * sizeof(int));
6
+  free(intArray);
7
+  printf("%d", intArray[10]);
8
+}

+ 5
- 0
hw2/simu1/malloc.c View File

@@ -0,0 +1,5 @@
1
+/* malloc.c */
2
+#include <stdlib.h>
3
+int main(char* argv[], int argc) {
4
+  char* testString = malloc(sizeof(char) * 10);
5
+}

+ 12
- 0
hw2/simu1/null.c View File

@@ -0,0 +1,12 @@
1
+#include <stdlib.h>
2
+#include <stdio.h>
3
+int main(char* argv[], int argc)
4
+{
5
+  int i, j;
6
+  int* iPointer;
7
+
8
+  i = 10;
9
+  iPointer = &i;
10
+  iPointer = NULL;
11
+  j = *iPointer;
12
+}

+ 6
- 0
hw2/task1/Cargo.toml View File

@@ -0,0 +1,6 @@
1
+[package]
2
+name = "task1"
3
+version = "0.1.0"
4
+authors = ["Lorenz Bung <lorenz.bung@googlemail.com>"]
5
+
6
+[dependencies]

+ 22
- 0
hw2/task1/src/lib.rs View File

@@ -0,0 +1,22 @@
1
+#[cfg(test)]
2
+mod tests {
3
+    #[test]
4
+    fn it_works() {
5
+        assert_eq!(2 + 2, 4);
6
+    }
7
+}
8
+pub fn hamming_distance(s1: &str, s2: &str) -> Result<usize, String> {
9
+    //Check if the given Strings are of different length
10
+    if s1.len() != s2.len() {
11
+        return Err("Strings must be of equal length!".to_string());
12
+    }
13
+    let mut dist: usize = 0;
14
+    for i in 0..s1.len() {
15
+        //Compare each character of the Strings
16
+        if s1.chars().nth(i) != s2.chars().nth(i) {
17
+            //If they don't match, increment hamming distance
18
+            dist += 1
19
+        }
20
+    }
21
+    Ok(dist)
22
+}

+ 10
- 0
hw2/task2/Cargo.toml View File

@@ -0,0 +1,10 @@
1
+[package]
2
+name = "task2"
3
+version = "0.1.0"
4
+authors = ["Joshua Rutschmann <joshua.rutschmann@gmx.de>"]
5
+
6
+[dependencies]
7
+
8
+[[bin]]
9
+doc = false
10
+name = "task2"

+ 1
- 1
hw2/task2/README.md View File

@@ -204,7 +204,7 @@ fn parse_arguments(args: &Vec<String>) -> Result<Config, xx >
204 204
 Implementieren Sie die folgende Fehlerbehandlung:
205 205
 
206 206
 - Werden vom Benutzer zuwenig übergeben, so gibt die Funktion den Fehlerstring
207
-  "not enough parameters" zurück. Werden vom Benutzer zu viele Parameter
207
+  "not enough arguments" zurück. Werden vom Benutzer zu viele Parameter
208 208
   übergeben, so wertet die Funktion nur die ersten beiden aus. In der API der
209 209
   Funktion oben ist als Typ xx für den 'String' angedeutet und muss entsprechend
210 210
   von Ihnen mit dem richtigen Typen versehen werden.

+ 86
- 0
hw2/task2/src/lib.rs View File

@@ -0,0 +1,86 @@
1
+/// a struct to hold all of our configuration
2
+#[derive(Debug, PartialEq)]
3
+pub struct Config {
4
+    pub search: char,
5
+    pub line: String,
6
+}
7
+
8
+pub fn run(conf: &Config) -> i32 {
9
+    let mut count = 0;
10
+    for c in conf.line.chars() {
11
+        if c == conf.search {
12
+            count = count + 1;
13
+        }
14
+    }
15
+    count
16
+}
17
+
18
+/// Parses relevant arguments, returning the filled Config in Result
19
+///
20
+///
21
+/// This function will parse the relevant arguments from the
22
+/// given <Strings>.
23
+/// Returns Config or Error Message in Result
24
+#[allow(dead_code)]
25
+fn parse_arguments(args: &Vec<String>) -> Result<Config, String> {
26
+
27
+    if args.len() < 3 {
28
+        return Err("not ennugh parameters".to_string());
29
+    }
30
+
31
+    match args[1].chars().nth(0) {
32
+        Some(value) => {
33
+            Ok(Config {
34
+                search: value,
35
+                line: args[2].clone(),
36
+            })
37
+        }
38
+        None => Err("char mismatch".to_string()),
39
+    }
40
+}
41
+
42
+/// Parses relevant arguments, returning the filled Config
43
+///
44
+///
45
+/// This function will parse the relevant arguments from the
46
+/// given <Strings>.
47
+/// Returns Config
48
+#[allow(dead_code)]
49
+fn parse_arguments_simple(args: &Vec<String>) -> Config {
50
+    Config {
51
+        search: args[1].chars().nth(0).unwrap(),
52
+        line: args[2].clone(),
53
+    }
54
+}
55
+
56
+/// Prints elements of Vec
57
+///
58
+///
59
+/// This function will print all elements of Vec with "args found: <elem>" in
60
+/// each line
61
+///
62
+/// Returns nothing
63
+#[allow(dead_code)]
64
+fn print_arguments(args: &Vec<String>) {
65
+    for s in args {
66
+        println!("args found: {}", s);
67
+    }
68
+}
69
+
70
+impl Config {
71
+    pub fn new(args: &Vec<String>) -> Result<Config, &str> {
72
+        if args.len() < 3 {
73
+            return Err("not enough arguments");
74
+        }
75
+
76
+        match args[1].chars().nth(0) {
77
+            Some(value) => {
78
+                Ok(Config {
79
+                    search: value,
80
+                    line: args[2].clone(),
81
+                })
82
+            }
83
+            None => Err("char mismatch"),
84
+        }
85
+    }
86
+}

+ 28
- 0
hw2/task2/src/main.rs View File

@@ -0,0 +1,28 @@
1
+use std::env;
2
+use std::process;
3
+use task2::Config;
4
+extern crate task2;
5
+
6
+fn main() {
7
+    let args = env::args().collect();
8
+
9
+    let res = Config::new(&args);
10
+    match res {
11
+        Ok(conf) => {
12
+            println!(
13
+                "You asked me to count all '{}' in '{}'",
14
+                conf.search,
15
+                conf.line
16
+            );
17
+            let occ = task2::run(&conf);
18
+            println!("Found {} '{}' in '{}'", occ, conf.search, conf.line);
19
+        }
20
+        Err(message) => {
21
+            println!("{}", message);
22
+            process::exit(1)
23
+        }
24
+    }
25
+
26
+
27
+
28
+}

+ 6
- 0
hw2/task3/Cargo.toml View File

@@ -0,0 +1,6 @@
1
+[package]
2
+name = "task3"
3
+version = "0.1.0"
4
+authors = ["Lorenz Bung <lorenz.bung@googlemail.com>"]
5
+
6
+[dependencies]

+ 45
- 0
hw2/task3/src/lib.rs View File

@@ -0,0 +1,45 @@
1
+
2
+#[cfg(test)]
3
+mod tests {
4
+    #[test]
5
+    fn it_works() {
6
+        assert_eq!(2 + 2, 4);
7
+    }
8
+}
9
+
10
+pub struct PascalsTriangle {
11
+    height: u32,
12
+}
13
+
14
+impl PascalsTriangle {
15
+    pub fn new(i: u32) -> Self {
16
+        PascalsTriangle { height: i }
17
+    }
18
+    pub fn rows(&self) -> Vec<Vec<u32>> {
19
+        let rows = self.height as usize;
20
+        let mut matrix = Vec::with_capacity(rows);
21
+
22
+        for line in 0..rows {
23
+            let current = line as usize;
24
+            matrix.push(Vec::with_capacity(current + 1));
25
+            matrix[current].push(1);
26
+
27
+            if current > 1 {
28
+                let previous = current - 1;
29
+                for index in 1..current {
30
+                    let add = matrix[previous][index - 1] + matrix[previous][index];
31
+                    matrix[current].push(add);
32
+                }
33
+            }
34
+
35
+            if current > 0 {
36
+                matrix[current].push(1);
37
+            }
38
+
39
+        }
40
+
41
+        println!("{:?}", matrix);
42
+
43
+        matrix
44
+    }
45
+}

+ 7
- 0
hw2/task3/src/main.rs View File

@@ -0,0 +1,7 @@
1
+extern crate task3;
2
+use task3::PascalsTriangle;
3
+
4
+fn main() {
5
+    let p = PascalsTriangle::new(10);
6
+    p.rows();
7
+}

Loading…
Cancel
Save