Я использовал эту функцию str_shuffle () в PHP и мека этот API Мне нужно сделать ту же идею, перетасовать буквы с пробелом между ними, но с lua по работе с телеграм-ботами много искал и ничего похожего не нашел
Спасибо, чувак, жду тебя
Я работаю над этим, но это сложно, и сначала мне нужно было что-то сделать
Вот код, который делает то, что вы хотите, с комментариями, чтобы объяснить, как это работает:
function tablelength(table) -- to calculate the length of a table
local count = 0
for _ in pairs(table) do count = count + 1 end -- loop through each of its items and add to a counter
return count
end
function stringtoletters(text) -- split a string into its individual characters
local letters = {}
for a = 1, string.len(text) do -- loop through each character in the string and add it to the table
table.insert(letters, string.sub(text, a, a))
end
return letters
end
function randomlyreorganizetext(text) -- the function that actually does the stuff AKA the meat
local letters = stringtoletters(text)
local n = tablelength(letters)
math.randomseed(os.time()) -- initialize the random number generator
math.random(); math.random(); math.random() -- the first few numbers are apparently not very random so get rid of them
for i=n,1,-1 do -- go through each character and switch it out with another one of the of the characters at random
local j = math.floor(math.random() * (i-1)) + 1 -- decide which character to swap with
local tmp = letters[i] -- make a backup of the current value
letters[i] = letters[j] -- change to random characters value
letters[j] = tmp -- put what used to be the current value into the random characters position
end
return table.concat(letters, " ") -- turn the table back into a string and put spaces between each element
end
print(randomlyreorganizetext("hello"))
Вызовите math.randomseed
только один раз в своей программе, а не в библиотечной функции.
Спасибо, чувак, это круто работает как по волшебству :) за исключением того, что проблема с арабскими буквами не работает. Вы можете мне с этим помочь?
@Destroyer, вам, вероятно, стоит задать еще один вопрос, потому что я не знаю Lua, и я думаю, что это проблема с материалами Unicode, и я тоже ничего об этом не знаю.
@RaphaelFacredyn Спасибо, чувак, да, из-за строки арабских букв длиной 2, спасибо за все и за ваше время очень вам благодарен ♥
Вот мое мнение. Первый gsub
индексирует буквы в строке в том порядке, в котором они появляются в ней. Затем мы тасовать индексы и используем перетасованные индексы для переназначения букв с другим gsub
.
s = "How to shuffle the letters of a word using lua"
t = {}
n=0
s:gsub("%a",function (c)
if t[c]==nil then
n=n+1
t[n]=c
t[c]=n
end
end)
math.randomseed(os.time())
for i=n,2,-1 do
local j=math.random(i)
t[i],t[j]=t[j],t[i]
end
z=s:gsub("%a",function (c) return t[t[c]] end)
print(s)
print(z)
Теперь это работает, но не с арабскими словами, а также без пробелов между буквами
@Destroyer, для добавления пробелов используйте z=s:gsub("%a",function (c) return t[t[c]].." " end)
math.randomseed(os.time())
local function shuffle(str)
local letters = {}
for letter in str:gmatch'.[\128-\191]*' do
table.insert(letters, {letter = letter, rnd = math.random()})
end
table.sort(letters, function(a, b) return a.rnd < b.rnd end)
for i, v in ipairs(letters) do letters[i] = v.letter end
return table.concat(letters)
end
print(shuffle("How to shuffle the whole UTF-8 string"))
Вы можете реализовать это в lua. Я собираюсь попробовать, однако я не знаю lua, поэтому это может занять некоторое время.