Converting integer value to a string - string

Below is code to encode an integer value into an ASCII string. It is written in Python, and works fine from my testings.
def encode(value):
code = ''
while value%254 != value:
code = code + chr(value%254)
value = value/254
code = code + chr(value)
return code
def decode(code):
value = 0
length = len(code)
for i in range(0, length):
print code[i]
value = value * 254 + ord(code[length-1-i])
return value
code = encode(123456567)
print code
print decode(code)
However when I try the same implementation in Lua, the values encoded and decoded do not match up. Here is my Lua version:
function encode(value)
code = ''
while value%254 ~= value do
code = code .. string.char(value%254)
value = value/254
end
code = code .. string.char(value)
return code
end
function decode(code)
value = 0
code = string.reverse(code)
for i=1, #code do
local c = code:sub(i,i)
print(c)
value = value*254 + string.byte(c)
end
return value
end
code = encode(2555456)
print(decode(code))
Please note that I am trying to using mod 254 so that I can used 255 as a delimiter.

Use local whenever you are creating variables with similar names (for eg. code and value in your code).
When you use value = value / 254, you need to take only the integer part of the division and not the entire number.
Therefore:
function encode(value)
local code = ''
while value % 254 ~= value do
code = code .. string.char( value % 254 )
value = math.floor( value / 254 )
end
code = code .. string.char( value )
return code
end
function decode(code)
local value = 0
code = code:reverse()
for i = 1, #code do
local c = code:sub( i, i )
value = value * 254 + c:byte()
end
return value
end

Related

What is a alternative for python classes in lua?

So i'm trying to convert python to lua but a road block i have right now is the class i'm not sure how i would convert a class to lua does anyone know how i would go about converting a class from python to lua?
python class
class
The OOP magic can be done with Lua tables and metatables.
Python
Look at The __init__() Function example here...
https://www.w3schools.com/python/python_classes.asp
Lets implement this with Lua...
( Lua 5.4 interactive console )
> _VERSION
Lua 5.4
> Person = setmetatable({},{
__call = function(self, name, age)
self.name = name
self.age = age
return {name = self.name, age = self.age}
end
})
> p1 = Person("John", 36)
> print(p1.name, p1.age)
John 36
So, some readers would ask: Why a metatabled table?
A simple function could do the same job.
Once a table has a metatable it is quit simple to add methods...
> Person = setmetatable({},{
__call = function(self, name, age)
self.name, self.age = name, age
table.insert(self, {name = self.name, age = self.age}) -- Numbered keys are the Data part
return {name = self.name, age = self.age}
end,
__index = {list = function(self) for i = 1, #self do print(self[i].name, self[i].age) end end}
})
> Person("John", 31);
> Person("Jack", 32);
> Person("Jim", 33);
> Person:list()
John 31
Jack 32
Jim 33
...that can handle the data of the table by itself.
Its a great benefit that the behaviour of a table can be controlled with metatables/methods.
And above example is only the tip of the iceberg.
Have a look at the __index of a string...
> for key, value in pairs(getmetatable(_VERSION).__index) do print(key, "=", value) end
byte = function: 0x565d6f20
lower = function: 0x565d4d90
len = function: 0x565d4750
sub = function: 0x565d7210
dump = function: 0x565d5d00
gsub = function: 0x565d7dc0
char = function: 0x565d5060
unpack = function: 0x565d6530
match = function: 0x565d7da0
packsize = function: 0x565d6420
pack = function: 0x565d6950
upper = function: 0x565d4ac0
format = function: 0x565d52d0
reverse = function: 0x565d4b50
find = function: 0x565d7db0
gmatch = function: 0x565d70d0
rep = function: 0x565d4be0
Therefore this is possible...
> print(("koyaanisqatsi"):upper():reverse())
ISTAQSINAAYOK
Means: Methods can be chained if their returning datatype has a method
Exceptions are: len() accept but dont return a string and sub() needs numbers before it returns a string also dump() needs a self defined function and returns a binary (almost unreadable) string.

Why am I not getting an expected output using logical operators and indexing?

I am having trouble achieving an expected output. I am trying to create a byte adder using logical operators such as AND, XOR and OR. I have taken the minimal code required to reproduce the problem out of code, so assume that finalfirstvalue = "1010" and finalsecondvalue = "0101".
secondvalueindex = (len(finalsecondvalue) - 1)
carry, finalans = False, []
for i in range(-1, -len(finalfirstvalue) - 1, -1):
andone = (bool(finalfirstvalue[i])) & (bool(finalsecondvalue[secondvalueindex]))
xorone = (bool(finalfirstvalue[i])) ^ (bool(finalsecondvalue[secondvalueindex]))
andtwo = (bool(carry)) & (bool(xorone))
xortwo = (bool(carry)) ^ (bool(xorone))
orone = (bool(andone)) | (bool(andtwo))
carry = (bool(orone))
finalans.append(xortwo)
secondvalueindex -= 1
answer = ''.join(str(e) for e in finalans)
print (answer)
Actual Output: FalseTrueTrueTrue
Expected Output: TrueTrueTrueTrue
The code then follows to change back into zeroes and ones.
Because its missing a single boolean I feel like the issue is with my indexing. Although I've played around with it a bit and not had any luck.
I need to carry out these operations on the two variables mentioned at the start, but for the right most elements, and then move to the left by one for the next loop and so on.
First mistake is You are representing your binary numbers as string values.
finalfirstvalue = "1010"
finalsecondvalue = "0101"
secondvalueindex = (len(finalsecondvalue) - 1) == 3
So in second for loop you will get the result as
(finalsecondvalue[secondvalueindex]) == '0'
If you check in your Idle
>>> bool('0')
True
>>>
Because '0' is not actual 0 it is an non-empty string so it return True.
You need to cast your result to int before checking them with bool
Like this
(bool(int(finalsecondvalue[secondvalueindex])))
EDIT 2 Adding with variable lenghts
Full adder with verification using bin() function
a="011101"
b="011110"
if a>b:
b=b.zfill(len(a))
if a<b:
a=a.zfill(len(b))
finalfirstvalue = a
finalsecondvalue = b
carry, finalans = 0, []
secondvalueindex = (len(finalsecondvalue))
for i in reversed(range(0, len(finalfirstvalue))):
xorone = (bool(int(finalfirstvalue[i]))) ^ (bool(int(finalsecondvalue[i])))
andone = (bool(int(finalfirstvalue[i]))) & (bool(int(finalsecondvalue[i])))
xortwo = (carry) ^ (xorone)
andtwo = (carry) & (xorone)
orone = (andone) | (andtwo)
carry = (orone)
finalans.append(xortwo)
finalans.reverse()
answer=(''.join(str(e) for e in finalans))
print(str(carry)+answer)
print(bin(int(a,2) + int(b,2))) #verification
So I found the issue was to do with carry. I changed my code to look like the following. Prior to this code below, is code to convert binary values to boolean. For instance, all ones will equal True and all zeroes will equal False.
carry, finalans = False, []
indexvalue = (len(finalfirstvalue)-1)
while indexvalue >= 0:
andone = (firstvaluelist[indexvalue]) & (secondvaluelist[indexvalue])
xorone = (firstvaluelist[indexvalue]) ^ (secondvaluelist[indexvalue])
andtwo = (carry) & (xorone)
xortwo = (carry) ^ (xorone)
orone = (andone) | (andtwo)
carry = (orone)
if (carry == True) & (indexvalue == 0):
finalans.append(xortwo)
finalans.append(True)
else:
finalans.append(xortwo)
indexvalue -= 1
for n, i in enumerate(finalans):
if i == False:
finalans[n] = "0"
if i == True:
finalans[n] = "1"
finalans.reverse()
answer = ''.join(str(e) for e in finalans)
print (answer)
So if there was a single value missing, it was still stored in carry from the final loop but did not get the opportunity to be appended to the final result. To fix this, I added in an if statement to check if carry is containing anything (True) and if the loop is on its final loop by checking if indexvalue is at 0. This way, if the inputs are 32 and 32, rather than getting [False, False, False, False, False, False] as the output, the newly entered if statement will add the missing value in.

Making and using an object-style Module in Lua

I've been trying to take a module in Lua and use it to imitate an object. i.e. I made a deck of cards:
local Card = require("Card")
local function firstCard()
Card.newDeck()
Card.drawCard()
return Card.getCard()
end
local function secondCard()
Card.newDeck()
Card.drawCard()
return Card.getCard()
end
first = firstCard()
second = secondCard()
print(first)
print(second)
I set first = firstCard() and second = secondCard() but when I print the two variables second occasionally results as nil. I'm honestly lost. Here's the actual module itself.
local Card = {}
local deck
local value
local number, suit
local index = 0
local getCard
local getValue
function Card.newDeck()
deck = {}
value = {}
for x = 1, 13 do
if x == 1 then
number = "Ace"
elseif x == 11 then
number = "Jack"
elseif x == 12 then
number = "Queen"
elseif x == 13 then
number = "King"
else
number = x
end
for x1 = 1, 4 do
if x1 == 1 then
suit = "Clubs"
elseif x1 == 2 then
suit = "Diamonds"
elseif x1 == 3 then
suit = "Hearts"
else
suit = "Spades"
end
index = index + 1
deck[index] = number.." of "..suit
value[index] = x
end
end
end
function Card.drawCard()
index = math.random(52)
getCard = deck[index]
getValue = value[index]
end
function Card.getCard()
return getCard
end
function Card.getValue()
return getValue
end
function Card.getIndex()
return index
end
return Card
I have limited knowledge of Lua when it comes to Object-Oriented programming and to be honest, I typically only use it for calculations or small games to keep me occupied I'm class- I'm only 16. I'm more used to Java, even though I started using Lua well before I picked up Java. I just want to know if and how I can make this work. For the most part it works, just those occasional nil values.
The problem is that you have declared the index variable local at the top level of your module. That means that the random value of index that you have calculated in your first drawCard() is reused in your second call to newDeck(). You can add print(index) at the start of newDeck() to see what I mean.
There are several ways to solve the problem. One would be to add index = 0 at the top of newDeck(). A better one would be to declare your variables with smaller scoping, i.e. make index local to each function that uses it.
Try to use this instead, seems to work fine, it should print "ERROR NO VALUE" if there is some issue with the index, if that occurs (it shouldn't though), just print the index (in the generateCard() function).
This is the test
local Card = require("Card");
local function firstCard()
Card.newDeck()
return Card.generateCard(); -- two parameters, deck and value
end
local function secondCard()
Card.newDeck()
return Card.generateCard();
end
first = firstCard()
second = secondCard()
print(first)
print(second)
This is the module
local Card = {deck={};value={};};
function Card.newDeck()
local self = Card
local deck = self.deck;
local value = self.value;
local cards = {[1]="Ace",[11]="Jack",[12]="Queen",[13]="King"};
local types = {[1]="Clubs",[2]="Diamonds",[3]="Hearts",[4]="Spades"};
for x = 1, 13 do
for i = 1, 4 do
local _card,_type=(cards[x] or x),types[i];
deck[#deck+1] = _card.." of ".._type
value[#deck+1] = x
end
end
end
function Card.generateCard()
local self = Card;
if(not math.round) then
math.round = function(value) local mi,ma=math.floor(value),math.ceil(value)return(mi+0.5>value and mi or ma)end;
end
local index = math.round(math.random(1000, 52000)/1000);
return (self.deck[index] or "NO VALUE FOR CARD"),(self.value[index] or "NO DECK FOR CARD");
end
return Card

match check in matlab

i have strings like these:
s{1,2} = 'string';
s{2,2} = 'string2';
and in workspace structure like this
U.W.string = [2 2.5 3]
I want to check (in loop) s{1,2} or s{2,2} or s{i,2} matches any structure with the same name. If so, assign values from this structure to some variable var(i). How can it be done?
Use isfields to check, if a string is the name of a field in a struct. Then use the syntax struct.(name), where name is a string to access the field. Your code might look something like:
test = struct('hello', 'world', 'count', 42, 'mean', 10);
fields = {'test', 'count';
'hello', 'text';
'more', 'less'};
values = {pi, 'dummy', -1};
for row = 1 : size(fields, 1)
for column = 1 : size(fields, 2)
if isfield(test, fields{row, column})
test.(fields{row, column}) = values{row};
end
end
end
This converts the initial struct
test =
hello: 'world'
count: 42
mean: 10
to this one
test =
hello: 'dummy'
count: 3.1416
mean: 10
A shorter implementation is achieved by removing the inner loop and giving a cell-array to isfields:
for row = 1 : size(fields, 1)
%# Note the parenthesis instead of curly braces in the next statement.
match = isfield(test, fields(row, :));
if any(match)
test.(fields{row, match}) = values{row};
end
end
Use isfield(structName,fieldName). This should do the trick:
strings{1,1} = 'foo';
strings{1,2} = 'bar';
strings{1, 3} = 'foobar';
U.W.foo = 1;
U.W.foobar = 5;
for idx = 1:length(strings)
if(isfield(U.W,strings{1,idx}))
expression = sprintf('outvar(idx) = U.W.%s',strings{1,idx});
eval(expression);
end
end

Groovy: indexes of substrings?

How do I find the indexes of all the occurances of a substring in a large string -
(so basically ,and extension of the "indexOf" function) . Any ideas?
Current situation:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexOf(sub)
// = 9
I want something like:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
// = [9,15]
Is there such a function? How should I implement it otherwise? (in a non trivial way)
You could write a new addition to the String metaClass like so:
String.metaClass.indexesOf = { match ->
def ret = []
def idx = -1
while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
ret << idx
}
ret
}
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
There is nothing I know of that exists in groovy currently that gets you this for free though
This is a relatively easy approach:
String.metaClass.indexesOf = { arg ->
def result = []
int index = delegate.indexOf(arg)
while (index != -1) {
result.add(index);
index = delegate.indexOf(arg, index+1);
}
return result;
}
Note that this will find overlapping instances (i.e. "fooo".indexesOf("oo") will return [1, 2]). If you don't want this, replace index+1 with index+arg.length().

Resources