From e30c22bcdf3e07694b1d7c01a67f95040b10ab77 Mon Sep 17 00:00:00 2001 From: joachimschmidt557 Date: Sun, 14 Jul 2019 15:15:01 +0200 Subject: [PATCH] No more copying of the entire matrix --- src/nim_word_prediction.nim | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/nim_word_prediction.nim b/src/nim_word_prediction.nim index f52854c..f7b9859 100644 --- a/src/nim_word_prediction.nim +++ b/src/nim_word_prediction.nim @@ -9,11 +9,13 @@ proc predict(word:string, matrix:Matrix[uint16], return "" let w = word2int[word] - rowW = matrix.row(w) var maxI = 0 maxW = 0u16 - for i, x in rowW: + + # Get the maximum of that row + for i in 0 .. matrix.N - 1: + let x = matrix[w, i] if x > maxW: maxI = i maxW = x @@ -22,6 +24,7 @@ proc predict(word:string, matrix:Matrix[uint16], proc updateMatrix(matrix:var Matrix[uint16], word1:string, word2:string, word2int:var TableRef[string, int], int2word:var TableRef[int, string]) = + # Index the words if the aren't in the index yet if not word2int.hasKey(word1): let newIndex = len(word2int) word2int[word1] = newIndex @@ -30,10 +33,14 @@ proc updateMatrix(matrix:var Matrix[uint16], word1:string, word2:string, let newIndex = len(word2int) word2int[word2] = newIndex int2word[newIndex] = word2 + + # Compute the indices let w1 = word2int[word1] w2 = word2int[word2] - if w1 < 20000 and w2 < 20000: + + # Check if the matrix is large enough + if w1 < matrix.ld and w2 < matrix.ld: matrix[w1, w2] += 1 proc interactive(matrix:Matrix[uint16], @@ -50,7 +57,7 @@ proc main() = statistics = false word = "I" texts:seq[string] - matrix = zeros(20000, 20000, uint16) + matrix = zeros(20000, 20000, uint16, rowMajor) word2int = newTable[string, int]() int2word = newTable[int, string]()