Three word location: Difference between revisions

Content added Content deleted
Line 225: Line 225:
</pre>
</pre>


=== Idiomatic version ===
=== Idiomatic version with scrambling===
<lang julia>using Random
Output is the same as direct translation version.

<lang julia>
const LAT = 28.3852
const LAT = 28.3852
const LON = -81.5638
const LON = -81.5638
Line 234: Line 234:
const wordarray = ["W" * string(x, pad=5) for x in 0:28125]
const wordarray = ["W" * string(x, pad=5) for x in 0:28125]


function threewordencode(lat, lon) # returns vector of 3 strings
function threewordencode(lat, lon, seed=0) # returns vector of 3 strings
arr = wordarray
if seed != 0
rng = MersenneTwister(seed)
arr = shuffle(rng, deepcopy(wordarray))
end
i = (Int(lat * 10000 + 900000) << 22) | Int(lon * 10000 + 1800000)
i = (Int(lat * 10000 + 900000) << 22) | Int(lon * 10000 + 1800000)
return map(x -> wordarray[x + 1], [(i >> 28) & 0xefff, (i >> 14) & 0x7fff, i & 0x7fff])
return map(x -> arr[x + 1], [(i >> 28) & 0xefff, (i >> 14) & 0x7fff, i & 0x7fff])
end
end


function threeworddecode(w1, w2, w3, seed=0) # returns pair of Float64
words = threewordencode(LAT, LON)
arr = wordarray
println(join(words, " "))
if seed != 0

rng = MersenneTwister(seed)
function threeworddecode(w1, w2, w3) # returns pair of Float64
(i1, i2, i3) = indexin([w1, w2, w3], wordarray) .- 1
arr = shuffle(rng, deepcopy(wordarray))
end
(i1, i2, i3) = indexin([w1, w2, w3], arr) .- 1
latlon = (i1 << 28) | (i2 << 14) | i3
latlon = (i1 << 28) | (i2 << 14) | i3
ilon, ilat = latlon & 0xfffff, latlon >> 22
ilon, ilat = latlon & 0xfffff, latlon >> 22
return (ilon - 1800000) / 10000, (ilat - 900000) / 10000
return (ilon - 1800000) / 10000, (ilat - 900000) / 10000
end
end

words = threewordencode(LAT, LON)
println(join(words, " "))


lat, lon = threeworddecode(words...)
lat, lon = threeworddecode(words...)
println("latitude = $lat longitude = $lon")
println("latitude = $lat longitude = $lon")

</lang>
println("\nWith scramble using key 12345678:")
words = threewordencode(LAT, LON, 12345678)
println(join(words, " "))
lat, lon = threeworddecode(words..., 12345678)
println("latitude = $lat longitude = $lon")
</lang>{{out}}
<pre>
W18497 W27708 W01322
latitude = -81.5638 longitude = 28.3852

With scramble using key 12345678:
W20242 W23427 W16215
latitude = -81.5638 longitude = 28.3852
</pre>


=={{header|Symsyn}}==
=={{header|Symsyn}}==