September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -0,0 +1,21 @@
(def lowercase (map char (range (int \a) (inc (int \z)))))
(defn move-to-front [x xs]
(cons x (remove #{x} xs)))
(defn encode [text table & {:keys [acc] :or {acc []}}]
(let [c (first text)
idx (.indexOf table c)]
(if (empty? text) acc (recur (drop 1 text) (move-to-front c table) {:acc (conj acc idx)}))))
(defn decode [indices table & {:keys [acc] :or {acc []}}]
(if (empty? indices) (apply str acc)
(let [n (first indices)
c (nth table n)]
(recur (drop 1 indices) (move-to-front c table) {:acc (conj acc c)}))))
(doseq [word ["broood" "bananaaa" "hiphophiphop"]]
(let [encoded (encode word lowercase)
decoded (decode encoded lowercase)]
(println (format "%s encodes to %s which decodes back to %s."
word encoded decoded))))

View file

@ -0,0 +1,33 @@
Public Sub Main()
Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process
Dim sHold As New String[] 'To store results
Dim siCount, siCounter, siPos As Short 'Various variables
Dim sOutput, sCode, sWork, sEach As String 'Various variables
For siCounter = 0 To sToCode.Max 'To loop through each 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For siCount = 1 To Len(sToCode[siCounter]) 'Loop through each letter in 'Sample'
sWork = Mid(sToCode[siCounter], siCount, 1) 'sWork to store the Letter
siPos = InStr(scode, sWork) - 1 'Find the position of the letter in sCode, -1 for '0' based array
sOutput &= Str(siPos) & " " 'Add the postion to sOutput
sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "") 'sCode = the letter + the rest of sCode except the letter
Next
Print sToCode[siCounter] & " = " & sOutput 'Print the 'Sample' and the coded version
sHold.Add(Trim(sOutput)) 'Add the code to the sHold array
sOutput = "" 'Clear sOutput
Next
Print 'Print a blank line
For siCounter = 0 To sHold.Max 'To loop through each coded 'Sample'
sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting
For Each sEach In Split(sHold[siCounter], " ") 'For each 'code' in coded 'Sample'
sWork = Mid(sCode, Val(sEach) + 1, 1) 'sWork = the decoded letter
sOutput &= sWork 'Add the decoded letter to sOutput
sCode = sWork & Replace(sCode, sWork, "") 'sCode = the decoded letter + the rest of sCode except the letter
Next
Print sHold[siCounter] & " = " & sOutput 'Print the coded and decoded result
sOutput = "" 'Clear sOutput
Next
End

View file

@ -1,19 +1,25 @@
import qualified Data.List as L
import qualified Data.Maybe as M
import Data.List (delete, elemIndex, mapAccumL)
import Data.Maybe (fromJust)
table :: String
table = ['a'..'z']
table = ['a' .. 'z']
encode :: String -> [Int]
encode = snd . L.mapAccumL f table
where
f t s = ((s : L.delete s t), M.fromJust (L.elemIndex s t))
encode =
let f t s = (s : delete s t, fromJust (elemIndex s t))
in snd . mapAccumL f table
decode :: [Int] -> String
decode = snd . L.mapAccumL f table
decode = snd . mapAccumL f table
where
f t i = let s = (t !! i) in ((s : L.delete s t), s)
f t i =
let s = (t !! i)
in (s : delete s t, s)
main :: IO ()
main = mapM_ (\s -> let t@(e, _) = (encode s, decode e) in print t)
["broood", "bananaaa", "hiphophiphop"]
main =
mapM_ print $
(,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x)
((,) <*> (decode . snd) <$>
((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"]))

View file

@ -0,0 +1,48 @@
// version 1.1.2
fun encode(s: String): IntArray {
if (s.isEmpty()) return intArrayOf()
val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
val result = IntArray(s.length)
for ((i, c) in s.withIndex()) {
val index = symbols.indexOf(c)
if (index == -1)
throw IllegalArgumentException("$s contains a non-alphabetic character")
result[i] = index
if (index == 0) continue
for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j]
symbols[0] = c
}
return result
}
fun decode(a: IntArray): String {
if (a.isEmpty()) return ""
val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
val result = CharArray(a.size)
for ((i, n) in a.withIndex()) {
if (n !in 0..25)
throw IllegalArgumentException("${a.contentToString()} contains an invalid number")
result[i] = symbols[n]
if (n == 0) continue
for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j]
symbols[0] = result[i]
}
return result.joinToString("")
}
fun main(args: Array<String>) {
val strings = arrayOf("broood", "bananaaa", "hiphophiphop")
val encoded = Array<IntArray?>(strings.size) { null }
for ((i, s) in strings.withIndex()) {
encoded[i] = encode(s)
println("${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}")
}
println()
val decoded = Array<String?>(encoded.size) { null }
for ((i, a) in encoded.withIndex()) {
decoded[i] = decode(a!!)
print("${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}")
println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}")
}
}

View file

@ -0,0 +1,38 @@
function encode(string s)
string symtab = "abcdefghijklmnopqrstuvwxyz"
sequence res = {}
for i=1 to length(s) do
integer ch = s[i]
integer k = find(ch,symtab)
res &= k-1
for j=k to 2 by -1 do
symtab[j] = symtab[j-1]
end for
symtab[1] = ch
end for
return res
end function
function decode(sequence s)
string symtab = "abcdefghijklmnopqrstuvwxyz"
string res = ""
for i=1 to length(s) do
integer k = s[i]+1
integer ch = symtab[k]
res &= ch
for j=k to 2 by -1 do
symtab[j] = symtab[j-1]
end for
symtab[1] = ch
end for
return res
end function
procedure test(string s)
sequence e = encode(s)
string d = decode(e)
?{s,e,d,{"**ERROR**","ok"}[(s=d)+1]}
end procedure
test("broood")
test("bananaaa")
test("hiphophiphop")

View file

@ -1,18 +1,17 @@
/*REXX program demonstrates the move─to─front algorithm encode/decode symbol table. */
parse arg xxx; if xxx='' then xxx= 'broood bananaaa hiphophiphop' /*use the default?*/
one=1 /*(offset) for this task's requirement.*/
do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */
@= 'abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: the lowercase alphabet */
do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */
@= 'abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: the lowercase alphabet */
$= /*set the decode string to a null. */
do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */
_=pos(z, @); if _==0 then iterate /*the symbol position in symbol table. */
$=$ _ - one; @=z || delstr(@, _, 1) /*adjust the symbol table string. */
end /*k*/ /* [↑] the move─to─front encoding. */
do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */
_=pos(z, @); if _==0 then iterate /*the symbol position in symbol table. */
$=$ _ - one; @=z || delstr(@, _, 1) /*(re-)adjust the symbol table string. */
end /*k*/ /* [↑] the move─to─front encoding. */
!= /*set the encode string to a null. */
do m=1 for words($); n=word($, m) +one /*decode the sequence table string. */
y=substr(@@, n, 1); !=! || y /*the decode symbol for the word. */
@@=y || delstr(@@, n, 1) /*rebuild the symbol table string. */
end /*m*/ /* [↑] the move─to─front decoding. */
do m=1 for words($); n=word($, m) +one /*decode the sequence table string. */
y=substr(@@, n, 1); !=! || y /*the decode symbol for the N word.*/
@@=y || delstr(@@, n, 1) /*rebuild the symbol table string. */
end /*m*/ /* [↑] the move─to─front decoding. */
say ' word: ' left(x, 20) "encoding:" left($, 35) word('wrong OK', 1+(!==x) )
end /*j*/ /*stick a fork in it, we're all done. */
end /*j*/ /*stick a fork in it, we're all done. */

View file

@ -0,0 +1,69 @@
var str="broood"
var number:[Int]=[1,17,15,0,0,5]
//function to encode the string
func encode(st:String)->[Int]
{
var array:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var num:[Int]=[]
var temp:Character="a"
var i1:Int=0
for i in st.characters
{
for j in 0...25
{
if i==array[j]
{
num.append(j)
temp=array[j]
i1=j
while(i1>0)
{
array[i1]=array[i1-1]
i1=i1-1
}
array[0]=temp
}
}
}
return num
}
func decode(s:[Int])->[Character]
{
var st1:[Character]=[]
var alph:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
var temp1:Character="a"
var i2:Int=0
for i in 0...s.character.count-1
{
i2=s[i]
st1.append(alph[i2])
temp1=alph[i2]
while(i2>0)
{
alph[i2]=alph[i2-1]
i2=i2-1
}
alph[0]=temp1
}
return st1
}
var encarr:[Int]=encode(st:str)
var decarr:[Character]=decode(s:number)
print(encarr)
print(decarr)

View file

@ -0,0 +1,6 @@
fcn encode(text){ //-->List
st:=["a".."z"].pump(Data); //"abcd..z" as byte array
text.reduce(fcn(st,c,sink){
n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L());
sink;
}

View file

@ -0,0 +1,6 @@
fcn decode(list){ //-->String
st:=["a".."z"].pump(String); //"abcd..z"
sink:=Sink(String);
list.reduce('wrap(st,n){ c:=st[n]; sink.write(c); c+st.del(n); },st);
sink.close();
}

View file

@ -0,0 +1,6 @@
texts:=T("broood","bananaaa","hiphophiphop");
out:=texts.apply(encode);
texts.zipWith(fcn(t,e){ println(t,"-->",e) },out);
out.apply(decode).println();
texts.zipWith('==,out.apply(decode)).println();