File size: 6,463 Bytes
d5bfab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use crate::common::RecordTrigram;
use super::random_indexes_with_distance;
use loda_rust_core::parser::{InstructionId, ParseInstructionId};
use std::collections::HashMap;
use rand::Rng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand::rngs::StdRng;

type HistogramKey = (String,String);
type InstructionAndWeight = (InstructionId,u32);
type HistogramValue = Vec<InstructionAndWeight>;

#[derive(Clone, Debug)]
pub struct SuggestInstruction {
    histogram: HashMap<HistogramKey, HistogramValue>
}

impl SuggestInstruction {
    pub fn new() -> Self {
        Self {
            histogram: HashMap::new()
        }
    }

    const SHUFFLE_COUNT: usize = 0;

    pub fn populate(&mut self, records_original: &Vec<RecordTrigram>) {
        let mut records: Vec<RecordTrigram> = records_original.clone();
        let seed: u64 = 1;
        let mut rng = StdRng::seed_from_u64(seed);
        let indexes: Vec<usize> = random_indexes_with_distance(&mut rng, records.len(), Self::SHUFFLE_COUNT);
        for index in indexes {
            records[index].count = records_original[index].count;
        }

        for record in records {
            let key: HistogramKey = (record.word0.clone(), record.word2.clone());
            let instruction_id: InstructionId = match InstructionId::parse(&record.word1, 0) {
                Ok(instruction_id) => instruction_id,
                Err(_) => {
                    continue;
                }
            };
            if instruction_id == InstructionId::LoopBegin ||
                instruction_id == InstructionId::LoopEnd ||
                instruction_id == InstructionId::EvalSequence {
                // Don't suggest these instructions
                continue;
            }
            let instruction_and_weight: InstructionAndWeight = (instruction_id, record.count);
            let item = self.histogram.entry(key).or_insert(vec!());
            (*item).push(instruction_and_weight);
        }
    }

    /// If it's the beginning of the program then set `prev_word` to `None`.
    /// 
    /// If it's the end of the program then set `next_word` to `None`.
    fn candidates(&self, prev_word: Option<InstructionId>, next_word: Option<InstructionId>) -> Option<&HistogramValue> {
        let word0: String = match prev_word {
            Some(instruction_id) => instruction_id.to_string(),
            None => "START".to_string()
        };
        let word2: String = match next_word {
            Some(instruction_id) => instruction_id.to_string(),
            None => "STOP".to_string()
        };
        let key: HistogramKey = (word0, word2);
        self.histogram.get(&key)
    }

    #[allow(dead_code)]
    pub fn best_instruction(&self, prev_word: Option<InstructionId>, next_word: Option<InstructionId>) -> Option<InstructionId> {
        let histogram_value: &HistogramValue = match self.candidates(prev_word, next_word) {
            Some(value) => value,
            None => {
                return None;
            }
        };
        let instruction_id: InstructionId = match histogram_value.first() {
            Some(value) => value.0,
            None => {
                return None;
            }
        };
        Some(instruction_id)
    }

    #[allow(dead_code)]
    pub fn choose_weighted<R: Rng + ?Sized>(&self, rng: &mut R, prev_word: Option<InstructionId>, next_word: Option<InstructionId>) -> Option<InstructionId> {
        let histogram_value: &HistogramValue = match self.candidates(prev_word, next_word) {
            Some(value) => value,
            None => {
                return None;
            }
        };
        let value: InstructionId = histogram_value.choose_weighted(rng, |item| item.1).unwrap().0;
        Some(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::SeedableRng;
    use rand::rngs::StdRng;

    fn mockdata() -> Vec<RecordTrigram> {
        let v = vec![
            RecordTrigram {
                count: 1000,
                word0: "mov".to_string(),
                word1: "div".to_string(),
                word2: "mul".to_string()
            },
            RecordTrigram {
                count: 1000,
                word0: "START".to_string(),
                word1: "sub".to_string(),
                word2: "add".to_string()
            },
            RecordTrigram {
                count: 1000,
                word0: "gcd".to_string(),
                word1: "min".to_string(),
                word2: "STOP".to_string()
            },
            RecordTrigram {
                count: 1000,
                word0: "START".to_string(),
                word1: "max".to_string(),
                word2: "STOP".to_string()
            },
        ];
        v
    }

    fn exercise_choose_weighted(prev_word: Option<InstructionId>, next_word: Option<InstructionId>) -> Option<InstructionId> {
        let mock = mockdata();
        let mut si = SuggestInstruction::new();
        si.populate(&mock);
        let mut rng = StdRng::seed_from_u64(0);
        let actual: Option<InstructionId> = si.choose_weighted(
            &mut rng, prev_word, next_word
        );
        actual
    }

    #[test]
    fn test_10000_choose_weighted_surrounded_by_other_words() {
        let actual: Option<InstructionId> = exercise_choose_weighted(
            Some(InstructionId::Move), Some(InstructionId::Multiply)
        );
        assert_eq!(actual, Some(InstructionId::Divide));
    }

    #[test]
    fn test_10001_choose_weighted_start_of_program() {
        let actual: Option<InstructionId> = exercise_choose_weighted(
            None, Some(InstructionId::Add)
        );
        assert_eq!(actual, Some(InstructionId::Subtract));
    }

    #[test]
    fn test_10002_choose_weighted_end_of_program() {
        let actual: Option<InstructionId> = exercise_choose_weighted(
            Some(InstructionId::GCD), None
        );
        assert_eq!(actual, Some(InstructionId::Min));
    }

    #[test]
    fn test_10003_choose_weighted_start_and_end_of_program() {
        let actual: Option<InstructionId> = exercise_choose_weighted(
            None, None
        );
        assert_eq!(actual, Some(InstructionId::Max));
    }

    #[test]
    fn test_10004_choose_weighted_unrecognized_input() {
        let actual: Option<InstructionId> = exercise_choose_weighted(
            Some(InstructionId::DivideIf), Some(InstructionId::DivideIf)
        );
        assert_eq!(actual, None);
    }
}