Attempt to index field ? (a nil value) - arrays

I am writing a small RPG game engine with Lua/love2d, and I need to parse a file to a 2d array, but it don't work, and I am getting errors...
main.lua :
local fmap = love.filesystem.read("map.txt")
map = {}
for c in fmap:gmatch(".") do
if c == "\n" then
y = 0
x = x + 1
else
map[x][y] = c -- this won't work
y = y + 1
end
end
map.txt :
6777633333
6558633333
6555614133
7757711112
2111111112
2111111112
2222222222

You can't use multi-dimensional array like this. See Matrices and Multi-Dimensional Arrays
You can transform your code like this :
local fmap = love.filesystem.read("map.txt")
map = {}
x = 0
y = 0
map[x] = {}
for c in fmap:gmatch(".") do
if c == "\n" then
y = 0
x = x + 1
map[x] = {}
else
map[x][y] = c -- this won't work
y = y + 1
end
end

I know that this has already been answered, but you'd probably find my (in progress) tile tutorial useful. The strings section deals with exactly the issue you are having.

Related

Error while increasing array value size by 1 error

I'm trying to create a program that will take an input of two integers of size 10 and below, that counts the amount of carry operations as a result of summing the input integers.
For example:
Sample Input:
59864417 974709147
Sample Output:
6
The line which returns an error in my program is:
parta[i+1] = ( parta[i+1] + 1 )
There i'm trying to add 1 to the value currently in the next array position.
run = true
while run == true
#input string
text = gets.chomp
#split string and remove space
parta = text.split[0]
partb = text.split[1]
#convert split strings to integers
partf1 = parta.to_i
partf2 = partb.to_i
#check for terminal input of 0
if partf1 + partf2 <= 0
run = false
end
#fill strings with 0s to size 11
parta = sprintf( "%011i", parta )
partb = sprintf( "%011i", partb )
#convert strings to arrays of integers
parta = parta.split("").map(&:to_i)
partb = partb.split("").map(&:to_i)
count = 0
(10).downto(0) do |i|
if ( parta[i] + partb[i] ) > 9
count = count + 1
parta[i+1] = ( parta[i+1] + 1 )
#59864417 974709147 test input should output 6
end
end
if run == true
puts "#{count} carry operations."
end
end
When I run I get the following error message:
test5.ruby:42:in block in <main>': undefined method+' for nil:NilClass (NoMethodError)
from test5.ruby:29:in downto'
from test5.ruby:29:in
Could anyone help me? :)
Expanding my comment into a slightly longer answer:
I suspect there's a simpler approach overall, but for your particular issue: the highest index in the array is 10. In that case, when i is 10, parta[i+1] (on the right side) is nil, because there's no element in the array with that index. When you try to increment nil, you get an error. But it should be parta[i-1] = parta[i-1] + 1 anyway if you're trying to go from right to left. This will cause some odd behavior when i is 0, but you might not care about that.
The problem is on this line
parta[i+1] = ( parta[i+1] + 1 )
In case i == size of the array the expression i + 1 will return nil which causes the error.
Just for fun, here's the rewritten version with Ruby 2.4 (for Intger#digits):
a = 59_864_417
b = 974_709_147
a, b = [a, b].sort
carry = false
count = b.digits.zip(a.digits).count do |m, n|
r = m + (n || 0) + (carry ? 1 : 0)
carry = r > 9
end
p count
#=> 6

Array diagonals python

I have an array 10x10 and I need to address all the points that are on the diagonal between two points and check if there are in a list. I did this but I don't know why it isn't working:
To put you in context:
a = [i,j] b = [i,j], i and j = range(11)
The code below is supposed to work for a = [5,4] b = [8,7] for example.
...
elif (b[1] - a[1]) == (b[0] - a[0]):
#to southeast, code for the other 3 cases are almost the same
if b[0] > a[0] and b[1] > a[1]:
n = a[0]
m = a[1]
while (n != b[0]) and (m != b[1]):
n +=1
m +=1
#don't think this part below is relevant
if board[n][m] in somelist:
mov_inv += 1
else:
mov_inv += 0
This is inside a function that returns False if mov_inv > 1 and True if mov_inv = 0 but it is not working that way. Hope you understand what I mean. Thanks
def diag(pointa, pointb):
""" pointa and pointb are tuples
returns a generator that yields values along the diagonal
from pointa to pointb"""
if abs(pointa[0] - pointb[0]) != abs(pointa[1] - pointb[1]):
#Sanity check. Diagonal are equal along x and y
raise ValueError("Points {} and {} are not diagonal".format(pointa, pointb))
x_dir = 1 if pointa[0] < pointb[0] else -1
y_dir = 1 if pointa[1] < pointb[1] else -1
while pointa != pointb:
pointa = (pointa[0] + x_dir, pointa[1] + y_dir)
yield pointa
The above doesn't yield pointb because you already know it
board=xrange(10*10)
diagonal1=[board[C:(10-C)*10:10+1] for C in xrange(10)]
diagonal2=[board[C:(C*10)+1:10-1] for C in xrange(10)]
print 'diagonal ASC ',diagonal1
print 'diagonal DESC ',diagonal2
then you just check if a and b in same diagonal
assume a,b= [5,4] , [8,7]
def Square(m,n):
return 10*(m-1)+n;
m,n=a
A=Square(m,n)
m,n=b
B=Square(m,n)
**print ('ASCENDENT',[diagonal1[x] for x in xrange(10) if A in diagonal[x] and B in diagonal[x]])**

How can I get result with array in Sympy

I am tring to get countour chart with sympy
I'm tring something like below but subs does not take array
and I tried for lambapy but lamdafy does not take 2 symbols or I don't know how to.
X,Y, formula = symbols('X Y formula')
formula = sp.sympify('X*2 + Y*3 +7*X*Y +34')
x = numpy.arange(1,10,1)
y = numpy.arange(1,10,1)
XValue,YValue = meshgrid(x,y)
ZValue = formula.sub([(X,XValue),(Y,YValue)])
Plot.contour(XValue, YValue, ZValue)
Are there any way to get result form 2 or more symbol with arrays
Answer was to lambdify the formula and get the result Z first. Then put XYZ value into the chart
X,Y, formula = symbols('X Y formula')
formula = sp.sympify('X*2 + Y*3 +7*X*Y +34')
x = numpy.arange(1,10,1)
y = numpy.arange(1,10,1)
XValue,YValue = meshgrid(x,y)
T = lambdify((x,y), formula,'numpy')
ZValue = T(XValue,YValue )
Plot.contour(XValue, YValue, ZValue)

Count items in one cell array in another cell array matlab

I have 2 cell arrays which are "celldata" and "data" . Both of them store strings inside. Now I would like to check each element in "celldata" whether in "data" or not? For example, celldata = {'AB'; 'BE'; 'BC'} and data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '}. I would like the expected output will be s=3 and v= 1 for AB, s=2 and v=2 for BE, s=2 and v=2 for BC, because I just need to count the sequence of the string in 'celldata'
The code I wrote is shown below. Any help would be certainly appreciated.
My code:
s=0; support counter
v=0; violate counter
SV=[]; % array to store the support
VV=[]; % array to store the violate
pairs = ['AB'; 'BE'; 'BC']
%celldata = cellstr(pairs)
celldata = {'AB'; 'BE'; 'BC'}
data={'ABCD' 'BCDE' 'ACBE' 'ADEBC '} % 3 AB, 2 BE, 2 BC
for jj=1:length(data)
for kk=1:length(celldata)
res = regexp( data(jj),celldata(kk) )
m = cell2mat(res);
e=isempty(m) % check res array is empty or not
if e == 0
s = s + 1;
SV(jj)=s;
v=v;
else
s=s;
v= v+1;
VV(jj)=v;
end
end
end
If I am understanding your variables correctly, s is the number of cells which the substring AB, AE and, BC does not appear and v is the number of times it does. If this is accurate then
v = cellfun(#(x) length(cell2mat(strfind(data, x))), celldata);
s = numel(data) - v;
gives
v = [1;1;3];
s = [3;3;1];

Signal created with matlab function block in simulink

I want to generate an arbitrary linear signal from matlab function block in simulink. I have to use this block because then, I want to control when i generate the signal by a sequence in Stateflow. I try to put the out of function as a structure with a value field and another time as the following code:
`function y = sig (u)
if u == 1
t = ([0 10 20 30 40 50 60]);
T = [(20 20 40 40 60 60 0]);
S.time = [t '];
S.signals (1) values ​​= [T '].;
S.signals (1) = 1 dimensions.;
else
N = ([0 0 0 0 0 0 0]);
S.signals (1) values ​​= [N '].;
end
y = S.signals (1). values
end `
the idea is that u == 1 generates the signal, u == 0 generates a zero output.
I also try to put the output as an array of two columns (one time and another function value) with the following code:
function y = sig (u)
if u == 1
S = ([0, 0]);
cant = input ('Number of points');
for n = Drange (1: cant)
S (n, 1) = input ('time');
S (n, 2) = input ('temperature');  
end
y = [S]
else
y = [0]
end
end
In both cases I can not generate the signal.
In the first case I get errors like:
This structure does not have a field 'signals'; new fields can not be added When structure has-been read or used
or
Error in port widths or dimensions. Output port 1 of 'tempstrcutsf2/MATLAB Function / u' is a one dimensional vector with 1 elements.
or
Undefined function or variable 'y'. The first assignment to a local variable Determines its class.
And in the second case:
Try and catch are not supported for code generation,
Errors occurred During parsing of MATLAB function 'MATLAB Function' (# 23)
Error in port widths or dimensions. Output port 1 of 'tempstrcutsf2/MATLAB Function / u' is a one dimensional vector with 1 elements.
I'll be very grateful for any contribution.
PD: sorry for my English xD
You have many mistakes in your code
you have to read more about arrays and structs in matlab
here S = ([0, 0]); you're declare an array with only two elements so the size will be static
There is no function called Drange in mtlab except if it's yours
See this example with strcuts and how they are created for you function
function y = sig(u)
if u == 1
%%getting fields size
cant = input ('Number of points\r\n');
%%create a structure of two fields
S = struct('time',zeros(1,cant),'temperature',zeros(1,cant));
for n =1:cant
S.time(n) = input (strcat([strcat(['time' num2str(n)]) '= ']));
S.temperature(n) = input (strcat([strcat(['temperature'...
num2str(n)]) '= ']));
end
%%assign output as cell of struct
y = {S} ;
else
y = 0 ;
end
end
to get result form y just use
s = y{1};
s.time;
s.temperature;
to convert result into 2d array
2dArray = [y{1}.time;y{1}.temperature];
Work with arrays
function y = sig(u)
if u == 1
cant = input ('Number of points\r\n');
S = [];
for n =1:cant
S(1,n) = input (strcat([strcat(['time' num2str(n)]) '= ']));
S(2,n) = input (strcat([strcat(['temperature'...
num2str(n)]) '= ']));
end
y = S;
else
y = 0 ;
end
end

Resources