Skip to content

Commit 461aa1b

Browse files
committed
[julia] add comments, reduce getindex(), use MVector to speed up
1 parent 61ab148 commit 461aa1b

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

julia/related.jl

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ StructTypes.StructType(::Type{PostData}) = StructTypes.Struct()
3636
function fastmaxindex!(xs::Vector{Int64}, topn, maxn, maxv)
3737
maxn .= 1
3838
maxv .= 0
39+
top = maxv[1]
3940
for (i, x) in enumerate(xs)
40-
if x > maxv[1]
41+
if x > top
4142
maxv[1] = x
4243
maxn[1] = i
4344
for j in 2:topn
@@ -46,6 +47,7 @@ function fastmaxindex!(xs::Vector{Int64}, topn, maxn, maxv)
4647
maxn[j-1], maxn[j] = maxn[j], maxn[j-1]
4748
end
4849
end
50+
top = maxv[1]
4951
end
5052
end
5153

@@ -56,6 +58,8 @@ end
5658

5759
function related(posts)
5860
topn = 5
61+
# key is every possible "tag" used in all posts
62+
# value is indicies of all "post"s that used this tag
5963
tagmap = Dict{String,Vector{Int64}}()
6064
for (idx, post) in enumerate(posts)
6165
for tag in post.tags
@@ -69,27 +73,30 @@ function related(posts)
6973
relatedposts = Vector{RelatedPost}(undef, length(posts))
7074
taggedpostcount = Vector{Int64}(undef, length(posts))
7175

72-
maxn = Vector{Int64}(undef, topn)
73-
maxv = Vector{Int64}(undef, topn)
76+
maxn = MVector{topn, Int64}(undef)
77+
maxv = MVector{topn, Int64}(undef)
7478

7579
for (i, post) in enumerate(posts)
7680
taggedpostcount .= 0
81+
# for each post (`i`-th)
82+
# and every tag used in the `i`-th post
83+
# give all related post +1 in `taggedpostcount` shadow vector
7784
for tag in post.tags
7885
for idx in tagmap[tag]
7986
taggedpostcount[idx] += 1
8087
end
8188
end
8289

90+
# don't self count
8391
taggedpostcount[i] = 0
8492

8593
fastmaxindex!(taggedpostcount, topn, maxn, maxv)
8694

87-
relatedpost = RelatedPost(post._id, post.tags, SVector{topn}(posts[ix] for ix in maxn))
95+
relatedpost = RelatedPost(post._id, post.tags, SVector{topn}(@view posts[maxn]))
8896
relatedposts[i] = relatedpost
8997
end
9098

9199
return relatedposts
92100
end
93101

94102
const res = relatedIO()
95-

0 commit comments

Comments
 (0)