I run the following code, but Lua keeps giving me "attempt to call a nil value". When I change the _G[fi] to _G.fi it gives me "attempt to call a string value".
i = "0"
j = "0"
k = "0"
fi = "f"..i
fj = "f"..j
fk= "f"..k
functions = {
f1 = function(next, v)
for t = 1, 1, 4 do
v[t] = v[t] + 1
v[t] = v[t] % 3
end
if (next == "0") then return v
else return functions[next](0, v) end
end,
f2 = function(next, v)
for t = 1, 1, 4 do
v[t] = v[t] + 2
v[t] = v[t] % 3
end
if (next == "0") then return v
else return functions[next](0, v) end
end,
f3 = function(next, v)
if (next == "0") then return v
else return functions[next](0, v) end
end,
f4 = function(next, v)
swap(v[2], v[3])
if (next == "0") then return v
else return functions[next](0, v) end
end,
f5 = function(next, v)
swap(v[1], v[3])
if (next == "0") then return v
else return functions[next](0, v) end
end,
f6 = function(next, v)
swap(v[1], v[2])
if (next == "0") then return v
else return functions[next](0, v) end
end,
}
for i = 0, 1, 6 do
for j = 0, 1, 6 do
for k = 0, 1, 6 do
if _G[fi](fj, {1,2,0}) == _G[fj](fk, {1,2,0}) and not _G[fi](-1, {1,2,0}) == _G[fk](-1, {1,2,0}) then
print(i + " " + j + " " + k)
end
end
end
end
The problem is you set fi = "f"..i at the start, which sets fi == "f0", and that never changes for the rest of the program until you later invoke _G[fi]. The value of fi does not automatically change just because you changed the value of i.
You probably want to expand i (and j and k) at the call point, with something more like:
_G["f"..i]("f"..j, {1,2,0})... etc
Related
I am writing a code in julia but I am unable to call a function from another function. Code is:
function add(x, y)
if x == 3 && y ==1
z =0
else x == 0 && y ==0
z =1
end
return z
end
function width(a, b, c)
add(x,y)
.....
end
The variables in add function will be used in width function but as I am new to julia, I am unable to call add in the other function. Kindly guide.
Edit:
I tried declaring with the z but it also didn't worked
struct z
a::Int
b::Int
end
There are two problems in your code that are not related to Julia per se. First problem in the add function: if x == 3 && y == 1 the output should be z = 0, else if x == 0 && y == 0, actually the if was missing, the output should be z = 1. Now what will be the output if, e.g., x = 1 && y == 1? The answer is nothing and z will be undefined.
To fix the add function, you should add a default branch for the if-else.
function add(x, y)
if x == 3 && y == 1
z = 0
elseif x == 0 && y == 0
z = 1
else
z = -1 # some default
end
return z
end
The same function could be written more concisely as:
function add(x, y)
x == 3 && y == 1 && return 0
x == 0 && y == 0 && return 1
return -1 # some default
end
which can even be written in a one-liner like this:
add(x, y) = x == 3 && y == 1 ? 0 : x == 0 && y == 0 ? 1 : -1 # some default
The second problem is with the width function. x and y are not defined inside the body of the width function. So, you can't call add(x, y). It should be z = add(a, b) where z should be used in subsequent calculations. Finally, check what the third argument c is for, otherwise, remove it.
function width(a, b, c)
z = add(a, b)
.....
end
I'm trying to pass a table through several functions and return it, but it only works to a certain degree. I'm almost sure it has to do something with the scoping, but I can't work it out since I'm new with LUA.
I tried putting the table in line 1 and setting it global, but to no avail.
Error: bag argument: expected table but got nil.
function returnToTunnel(movementTable)
for i = table.maxn(movementTable), 1, -1 do --this is where I get the error.
if (movementTable[i] == 1) then
turtle.down()
elseif (movementTable[i] == 2) then
turtle.up()
elseif (movementTable[i] == 3) then
turtle.back()
turtle.turnRight()
elseif (movementTable[i] == 4) then
turtle.back()
turtle.turnLeft()
elseif (movementTable[i] == 5) then
turtle.back()
end
end
end
function mineOre(locationParam, movementTable)
if (locationParam == 1) then
turtle.digUp()
turtle.suckUp()
turtle.up()
table.insert(movementTable, 1)
elseif (locationParam == 2) then
turtle.digDown()
turtle.suckDown()
turtle.down()
table.insert(movementTable, 2)
elseif (locationParam == 3) then
turtle.turnLeft()
turtle.dig()
turtle.suck()
turtle.forward()
table.insert(movementTable, 3)
elseif (locationParam == 4) then
turtle.turnRight()
turtle.dig()
turtle.suck()
turtle.forward()
table.insert(movementTable, 4)
elseif (locationParam == 5) then
turtle.dig()
turtle.suck()
turtle.forward()
table.insert(movementTable, 5)
end
locationParam = oreCheck()
if (locationParam > 0) then
mineOre(locationParam, movementTable)
else
return movementTable
end
end
function digTunnel(tunnelLengthParam)
local oreFound
local movement = {}
for i = 1, tunnelLengthParam do
turtle.dig()
turtle.forward()
oreFound = oreCheck()
if (oreFound > 0) then
movement = mineOre(oreFound, movement)
returnToTunnel(movement)
end
if ((i % 2) == 1) then
turtle.digUp()
turtle.up()
elseif ((i % 2) == 0) then
turtle.digDown()
turtle.down()
end
oreFound = oreCheck()
if (oreFound > 0) then
movement = mineOre(oreFound, movement)
returnToTunnel(movement)
end
end
end
So, the digTunnel function calls the other two functions mineOre and returnToTunnel.
I've been looking in the LUA manual and several websites but can't figure it out.
Thank you for your help!
Your function mineOre does not return a table but nil, when locationParam is > 0.
if (locationParam > 0) then
mineOre(locationParam, movementTable)
else
return movementTable
end
Hence this will cause a nil value end up in table.maxn
movement = mineOre(oreFound, movement)
returnToTunnel(movement)
So what I am trying to do here is for a given json_body which is decoded json into a table using cjson I want to remove a given element by a configurable value conf.remove.json, I feel I am pretty close but its still not working, and is there a better way? Is there a safe way to find the tables "depth" and then reach out like conf.remove.json= I.want.to.remove.this creates the behavior json_table[I][want][to][remove][this] = nil without throwing some kind of NPE?
local configRemovePath= {}
local configRemoveDepth= 0
local recursiveCounter = 1
local function splitString(inputstr)
sep = "%." --Split on .
configRemovePath={}
configRemoveDepth=0
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
configRemovePath[configRemoveDepth + 1] = str
configRemoveDepth = configRemoveDepth + 1
end
end
local function recursiveSearchAndNullify(jsonTable)
for key, value in pairs(jsonTable) do --unordered search
-- First iteration
--Sample Json below, where conf.remove.json = data.id and nothing happened. conf.remove.json=data.id
--{
--"data": {
-- "d": 2,
-- "id": 1
--}
--}
-- value = {"d": 2, "id": 1}, key = "data", configRemovePath[recursiveCounter] = "data" , configRemovePath ['data','id'] , configRemoveDepth = 2
if(type(value) == "table" and value == configRemovePath[recursiveCounter] and recursiveCounter < configRemoveDepth) then --If the type is table, the current table is one we need to dive into, and we have not exceeded the configurations remove depth level
recursiveCounter = recursiveCounter + 1
jsonTable = recursiveSearchAndNullify(value)
else
if(key == configRemovePath[recursiveCounter] and recursiveCounter == configRemoveDepth) then --We are at the depth to remove and the key matches then we delete.
for key in pairs (jsonTable) do --Remove all occurances of said element
jsonTable[key] = nil
end
end
end
end
return jsonTable
end
for _, name in iter(conf.remove.json) do
splitString(name)
if(configRemoveDepth == 0) then
for name in pairs (json_body) do
json_body[name] = nil
end
else
recursiveCounter = 1 --Reset to 1 for each for call
json_body = recursiveSearchAndNullify(json_body)
end
end
Thanks to any who assist, this is my first day with Lua so I am pretty newb.
This is the official answer, found a better way with the help of Christian Sciberras!
local json_body_test_one = {data = { id = {"a", "b"},d = "2" }} --decoded json w cjson
local json_body_test_two = {data = { { id = "a", d = "1" }, { id = "b", d = "2" } } }
local config_json_remove = "data.id"
local function dump(o) --Method to print test tables for debugging
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local function splitstring(inputstr, sep)
if sep == nil then
sep = "%." --Dot notation default
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
local function setjsonprop(json_object, path, newvalue)
local configarray = splitstring(path)
while (#configarray > 1) do
json_object = json_object[table.remove(configarray, 1)]
if(type(json_object) == "table" and #json_object > 0) then
local recursepath = table.concat(configarray, ".")
for _, item in pairs(json_object) do
setjsonprop(item, recursepath, newvalue)
end
return
end
end
json_object[table.remove(configarray, 1)] = newvalue
end
setjsonprop(json_body_test_one, config_json_remove, nil)
print(dump(json_body_test_one))
When I wrote a simple program in python, It creates a question for me! I have a loop and want to run a function's work as loop count. But I get loop number from the user. I want to know which of the following approach is better and why?
First Method:
def game(redCard, blackCard):
global totalRed, totalBlack
redWin = False
if redCard == king and blackCard == king:
redWin = True
elif redCard != king and blackCard != king and redCard != blackCard:
redWin = True
if(redWin):
totalRed += 1
else:
totalBlack += 1
def main():
#start point of program
n = int(input("Please enter 'Rounds' numbers:"))
for i in range(n):
# randint(a,b): Return a random integer N such that a <= N <= b
redCard = random.randint(0, 3)
blackCard = random.randint(0, 3)
game(redCard, blackCard)
main()
Second Method:
def game(count):
global totalRed, totalBlack
for i in range(count):
# randint(a,b): Return a random integer N such that a <= N <= b
redCard = random.randint(0, 3)
blackCard = random.randint(0, 3)
redWin = False
if redCard == king and blackCard == king:
redWin = True
elif redCard != king and blackCard != king and redCard != blackCard:
redWin = True
if(redWin):
totalRed += 1
else:
totalBlack += 1
def main():
#start point of program
n = int(input("Please enter 'Rounds' numbers:"))
game(n)
I am trying to implement Miller-Rabin for the first time. My code is giving correct answer for all the testcases, i tried but still on SPOJ it is giving wrong answer.
Problem Statement: I am supposed to print "YES" if entered number is prime otherwise "NO"
Please help:
Problem Link: http://www.spoj.com/problems/PON/
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LL long long
LL expo(LL a,LL b,LL c)
{
LL x=1,y=a;
if(b==0)
return 1;
while(b)
{
if(b%2==1)
x=(x*y)%c;
y=(y*y)%c;
b=b/2;
}
return x;
}
int main()
{
LL t,s,x,a,n,prime,temp;
scanf("%lld",&t);
srand(time(NULL));
while(t--)
{
scanf("%lld",&n);
if(n<2)
puts("NO");
else if(n==2)
puts("YES");
else if(n%2==0)
puts("NO");
else
{
s=n-1;
prime=1;
while(s%2==0)
s=s/2;
for(int i=0;i<20;i++)
{
a=rand()%(n-1)+1;
x=expo(a,s,n);
temp=s;
while((temp!=n-1)&&(x!=1)&&(x!=n-1))
{
x=(x*x)%n;
temp*=2;
}
if((x!=n-1)&&(temp%2==0))
{
prime=0;
break;
}
}
if(prime==0)
puts("NO");
else
puts("YES");
}
}
return 0;
}
Keep in mind that puts appends a newline character '\n' to the string that you're giving. You can try with printf instead.
I think your calculation of s and d is incorrect:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d % 2 == 0
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1 return ProbablyPrime
t := (t * t) % n
s := s - 1
return Composite
I discuss the Miller-Rabin method in an essay at my blog.
You are getting wrong answer because of integer overflow as you are multiplying 2 long number which can't be holded in a single long long type.
Here is a solution in python to overcome the issue
import random
_mrpt_num_trials = 25 # number of bases to test
def is_probable_prime(n):
assert n >= 2
# special case 2
if n == 2:
return True
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n - 1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2 ** s * d == n - 1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for _ in range(_mrpt_num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
for i in range(int(input())):
a = int(input())
if is_probable_prime(a):
print("YES")
else:
print("NO")