Lua integer won't increment - lua

I have this simple lua function designed to solve the problem of consecutive prime sum.
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
this is my function:
function numOfConsecPrimes(limit)
a = allPrimes(limit/2)
length = table.getn(a)
sumSoFar = 0 innerSum = 0 finalSum = 0
pos = 1
items = 0 innerItems = 0 finalItems = 0
resetpos = pos
while resetpos < length do
pos = resetpos
resetpos = resetpos + 1
items = 0
sumSoFar = 0
while sumSoFar < limit and pos < length do
if isPrime(sumSoFar) == true then innerSum = sumSoFar innerItems = items end
print(sumSoFar)
sumSofar = sumSoFar + a[pos]
print(a[pos] .."->"..sumSoFar)
pos = pos + 1
items = items + 1
end
if innerItems > finalItems then finalItems = innerItems finalSum = innerSum end
end
end
But for some reason, sumSoFar just won't change. I'm printing it before and after the addition of a[pos] and it stays zero always. I'm printing a[pos] as you see and the values are fine. So what's going on?

If this is your exact code then you simply have a typo.
sumSofar = sumSoFar + a[pos]
Capitalize the f in the first sumSofar so it matches all the other ones.

Related

A better way on improving my roman numeral decoder

Quick explanation, I have recently started using codewars to further improve my programming skills and my first challenge was to make a roman numeral decoder, I went through many versions because I wasnt satisfied with what I had, So I am asking if there is an easier way of handling all the patterns that roman numerals have, for example I is 1 but if I is next to another number it takes it away for example V = 5 but IV = 4.
here is my CODE:
function Roman_Numerals_Decoder (roman)
local Dict = {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000}
local number = 0
local i = 1
while i < #roman + 1 do
local letter = roman:sub(i,i) -- Gets the current character in the string roman
if roman:sub(i,i) == "I" and roman:sub(i + 1,i + 1) ~= "I" and roman:sub(i + 1,i + 1) ~= "" then -- Checks for the I pattern when I exists and next isnt I
number = number + (Dict[roman:sub(i +1,i + 1)] - Dict[roman:sub(i,i)]) -- Taking one away from the next number
i = i + 2 -- Increase the counter
else
number = number + Dict[letter] -- Adds the numbers together if no pattern is found, currently checking only I
i = i + 1
end
end
return number
end
print(Roman_Numerals_Decoder("MXLIX")) -- 1049 = MXLIX , 2008 = MMVIII
at the moment I am trying to get 1049 (MXLIX) to work but I am getting 1069, obviously I am not following a rule and I feel like its more wrong then it should be because usually if its not correct its 1 or 2 numbers wrong.
The algorithm is slightly different: you need to consider subtraction when the previous character has less weight than the next one.
function Roman_Numerals_Decoder (roman)
local Dict = {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000}
local num = 0
local i = 1
for i=1, #roman-1 do
local letter = roman:sub(i,i) -- Gets the current character in the string roman
local letter_p = roman:sub(i+1,i+1)
if (Dict[letter] < Dict[letter_p]) then
num = num - Dict[letter] -- Taking one away from the next number
print("-",Dict[letter],num)
else
num = num + Dict[letter] -- Adds the numbers together if no pattern is found, currently checking only I
print("+",Dict[letter],num)
end
end
num = num + Dict[roman:sub(-1)];
print("+",Dict[roman:sub(-1)], num)
return num
end
print(Roman_Numerals_Decoder("MXLIX")) -- 1049 = MXLIX , 2008 = MMVIII

Lua Script: Convert Multiple "if" into simpler form

I am trying to make a condition where the percentage would be calculated based on the number of fan operated and the amount of airflow. This is what I come out with
function System01()
CFM_SHOP1 = addr_getword("#W_HDW1")
CFM_SHOP2 = addr_getword("#W_HDW2")
STATUS_SHOP1 = addr_getbit("#B_M1")
STATUS_SHOP2 = addr_getbit("#B_M2")
OUTPUT_SHOP1 = addr_getword("#W_HDW10")
OUTPUT_SHOP2 = addr_getword("#W_HDW11")
CFM_1 = CFM_SHOP1 + CFM_SHOP2
if STATUS_SHOP1 == 1 then
OUTPUT_SHOP1 = CFM_SHOP1 * 10000 / CFM_1
addr_setword("#W_HDW10", OUTPUT_SHOP1)
if STATUS_SHOP2 == 1 then
OUTPUT_SHOP2 = CFM_SHOP2 * 10000 / CFM_1
addr_setword("#W_HDW11", OUTPUT_SHOP2)
end
TOTAL_1 = OUTPUT_SHOP1 + OUTPUT_SHOP2
addr_setword("#W_HDW19", TOTAL_1)
end
if STATUS_SHOP2 == 1 then
OUTPUT_SHOP2 = CFM_SHOP2 * 10000 / CFM_1
addr_setword("#W_HDW11", OUTPUT_SHOP2)
if STATUS_SHOP1 == 1 then
OUTPUT_SHOP1 = CFM_SHOP1 * 10000 / CFM_1
addr_setword("#W_HDW10", OUTPUT_SHOP1)
end
TOTAL_1 = OUTPUT_SHOP1 + OUTPUT_SHOP2
addr_setword("#W_HDW19", TOTAL_1)
end
addr_setbit("#B_M1", STATUS_SHOP1)
addr_setbit("#B_M2", STATUS_SHOP2)
addr_setbit("#B_M3", STATUS_SHOP3)
end
Is there any way that I can simplified it? Please note that this is only two example I give. There is total of 9 fan so it will be really complicated if i just use 'if'. Thanks in advance
To simplify the code use for-loop
function System01()
local CFM_SHOP = {}
local CFM = 0
for j = 1, 9 do
CFM_SHOP[j] = addr_getword("#W_HDW"..tostring(j))
CFM = CFM + CFM_SHOP[j]
end
local STATUS_SHOP = {}
for j = 1, 9 do
STATUS_SHOP[j] = addr_getbit("#B_M"..tostring(j))
end
local OUTPUT_SHOP = {}
for j = 1, 9 do
OUTPUT_SHOP[j] = addr_getword("#W_HDW"..tostring(j+9))
end
local TOTAL = 0
for j = 1, 9 do
if STATUS_SHOP[j] == 1 then
OUTPUT_SHOP[j] = CFM_SHOP[j] * 10000 / CFM
addr_setword("#W_HDW"..tostring(j+9), OUTPUT_SHOP[j])
end
TOTAL = TOTAL + OUTPUT_SHOP[j]
end
addr_setword("#W_HDW19", TOTAL)
for j = 1, 9 do
addr_setbit("#B_M"..tostring(j), STATUS_SHOP[j])
end
end

Check Collision Between Ball And Array Of Bricks

Since I have a collision check function in Lua:
function onCollision(obj1,obj2)
obj1x = obj1.left
obj1y = obj1.top
obj1w = obj1.width
obj1h = obj1.height
obj2x = obj2.left
obj2y = obj2.top
obj2w = obj2.width
obj2h = obj2.height
if obj2x + obj2w >= obj1x and obj2y + obj2h >= obj1y and obj2y <= obj1y + obj1h and obj2x <= obj1x + obj1w then
return true
end
end
And I did make some panels as bricks using array table on my form, with this function, I did collision check between ball with each form sides without problems.
function createBricks()
for row = 1, brickRows do
bricks[row] = {}
for col = 1, brickColumns do
local x = (col - 1) * (width + gap) -- x offset
local y = (row - 1) * (height + gap) -- y offset
local newBrick = createPanel(gamePanel)
newBrick.width = brickWidth
newBrick.height = brickHeight
newBrick.top = y + 15
newBrick.left = x + 15
newBrick.BorderStyle = 'bsNone'
if level == 1 then newBrick.color = '65407' -- green
elseif level == 2 then newBrick.color = '858083' -- red
elseif level == 3 then newBrick.color = '9125192' -- brown
elseif level == 4 then newBrick.color = math.random(8,65255) end
bricks[row][col] = newBrick
end
end
end
Next how to detect if the ball collided with the bricks?. So far I did:
for row = 1, brickRows do
bricks[row] = {}
for col = 1, brickColumns do
dBrick = bricks[row][col]
if onCollision(gameBall,dBrick) then
dBrick.destroy() -- destroy the collided brick
end
end
end
I want to learn how to implement this collision logic in VB Net script which VB script easier for me, I did the whole game project using VB Net, now I try to re-write the project using CE Lua.
Private brickArray(brickRows, brickColumns) As Rectangle
Private isBrickEnabled(brickRows, brickColumns) As Boolean
For rows As Integer = 0 To brickRows
For columns As Integer = 0 To brickColumns
If Not isBrickEnabled(rows, columns) Then Continue For
If gameBall.IntersectsWith(brickArray(rows, columns)) Then
isBrickEnabled(rows, columns) = False
If gameBall.X + 10 < brickArray(rows, columns).X Or _
gameBall.X > brickArray(rows, columns).X + brickArray(rows, columns).Width _
Then
xVel = -xVel
Else
yVel = -yVel
End If
End If
Next
Next
And also this private sub, how to write it CE Lua?
Sub loadBricks()
Dim xOffset As Integer = 75, yOffset As Integer = 100
For row As Integer = 0 To brickRows
For column As Integer = 0 To brickColumns
brickArray(row, column) = New Rectangle(xOffset, yOffset, brickWidth, brickHeight)
xOffset += brickWidth + 10
isBrickEnabled(row, column) = True
Next
yOffset += brickHeight + 10
xOffset = 75
Next
End Sub
Function getBrickCount() As Integer
Dim Count As Integer = 0
For Each brick As Boolean In isBrickEnabled
If brick = True Then Count += 1
Next
Return Count
End Function
function onCollision(obj1,obj2)
obj1x = obj1.left
obj1y = obj1.top
obj1w = obj1.width
obj1h = obj1.height
obj2x = obj2.left
obj2y = obj2.top
obj2w = obj2.width
obj2h = obj2.height
if obj2x + obj2w >= obj1x and obj2y + obj2h >= obj1y and obj2y <= obj1y + obj1h and obj2x <= obj1x + obj1w then
return true
end
end
Then to detect collision the collision and remove from the table:
-- Drawback table
local function tcount( t )
local c = 0
for k,v in pairs(t) do
c = c + 1
end
return c
end
local count = #brickArray
for x = 1, count do
if onCollision(gameBall, brickArray[x]) then
if gameBall.Left + 10 < brickArray[x].Left or gameBall.Left > brickArray[x].Left + brickArray[x].Width then
xVel = -xVel else yVel = -yVel
end
playSound(findTableFile('strikeball.wav'))
brickArray[x] = brickArray[count]
brickArray[x] = x
brickArray[count] = nil
brickArray[x].Visible = false
tcount(brickArray)
end
end
The code above detected the collision and remove the object from the table, but that is not removed from display. How to remove the bricks from the table and display, using Cheat Engine Lua script?.

Lua (Lapis) random values returns the same result even using randomseed

At first, I use this:
math.randomseed(os.time())
This function to check:
function makeString(l)
if l < 1 then return nil end
local s = ""
for i = 0, l do
n = math.random(0, 61)--61
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end
If I use this function:
app:match("/tttt", function()
local ss = ""
for i=1,10 do ss = ss .. makeString(30) .. "\n" end
return ss
end)
I receive good different values.
If I use this:
app:match("/ttt", function()
return makeString(30)
end)
and JavaScript jQuery,
:
$("#button5").click(function(){
var ss = ""
for(var i = 0; i < 10; i++)
{
$("#div1").load("/ttt", function() {
ss = ss + $(this).text()
alert(ss);
});
}
$("#div1").text(ss);
});
I recieve the same random strings every one second.
How to fix it? I tried to create database with different random data but I recieve the same strings!!! This is just example I wrote but filling the database gives the same result!##%%
Any ideas to fix it?
I found that this is "feature" of lua to generate random using seconds. Use this link to read more: http://lua-users.org/wiki/MathLibraryTutorial
But the solution which can help is to user /dev/urandom
The link to describe:
http://lua-users.org/lists/lua-l/2008-05/msg00498.html
In my case example:
local frandom = io.open("/dev/urandom", "rb")
local makeString
makeString = function(l)
local d = frandom:read(4)
math.randomseed(d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
if l < 1 then return nil end
local s = ""
for i = 0, l do
local n = math.random(0, 61)
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end

Bit operations in Lua

I try to parse gpx files and to output encoded polylines (Google algorithm)
test.gpx
<trkseg>
<trkpt lon="-120.2" lat="38.5"/>
<trkpt lon="-120.95" lat="40.7"/>
<trkpt lon="-126.453" lat="43.252"/>
</trkseg>
I managed most of it, but have trouble with encoding the numbers
gpx2epl:
file = io.open(arg[1], "r")
io.input(file)
--
function round(number, precision)
return math.floor(number*math.pow(10,precision)+0.5) / math.pow(10,precision)
end
function encodeNumber(number)
return number
end
--
local Olatitude = 0
local Olongitude = 0
--
while true do
local line = io.read()
if line == nil
then
break
end
if string.match(line, "trkpt") then
local latitude
local longitude
local encnum
latitude = string.match(line, 'lat="(.-)"')
longitude = string.match(line, 'lon="(.-)"')
latitude = round(latitude,5)*100000
longitude = round(longitude,5)*100000
encnum = encodeNumber(latitude-Olatitude)
print(encnum)
encnum = encodeNumber(longitude-Olongitude)
print(encnum)
Olatitude = latitude
Olongitude = longitude
end
end
This script produces the expected output (see: Google Link), with the exception of encoded latitude and longitude.
3850000
-12020000
220000
-75000
255200
-550300
Mapquest provides an implementation in Javascript:
function encodeNumber(num) {
var num = num << 1;
if (num < 0) {
num = ~(num);
}
var encoded = '';
while (num >= 0x20) {
encoded += String.fromCharCode((0x20 | (num & 0x1f)) + 63);
num >>= 5;
}
encoded += String.fromCharCode(num + 63);
return encoded;
}
Can this be done in Lua? Can somebody please help me out. I have no idea how to implement this in Lua.
Edit:
Based on Doug's advice, I did:
function encodeNumber(number)
local num = number
num = num * 2
if num < 0
then
num = (num * -1) - 1
end
while num >= 32
do
local num2 = 32 + (num % 32) + 63
print(string.char(num2))
num = num / 32
end
print(string.char(num + 63) .. "\n-----")
end
encodeNumber(3850000) -- _p~iF
encodeNumber(-12020000) -- ~ps|U
encodeNumber(220000) -- _ulL
encodeNumber(-75000) -- nnqC
encodeNumber(255200) -- _mqN
encodeNumber(-550300) -- vxq`#
It's near expected output, but only near ... Any hint?
Taking encodeNumber piecemeal...
var num = num << 1;
This is just num = num * 2
num = ~(num);
This is num = (- num) - 1
0x20 | (num & 0x1f)
Is equivalent to 32 + (num % 32)
num >>= 5
Is equivalent to num = math.floor(num / 32)
ADDENDUM
To concatenate the characters, use a table to collect them:
function encodeNumber(number)
local num = number
num = num * 2
if num < 0
then
num = (num * -1) - 1
end
local t = {}
while num >= 32
do
local num2 = 32 + (num % 32) + 63
table.insert(t,string.char(num2))
num = math.floor(num / 32) -- use floor to keep integer portion only
end
table.insert(t,string.char(num + 63))
return table.concat(t)
end

Resources