crdsClear={{y=56,x=50,symbolName=3,},
{y=56,x=29,symbolName=2,},
{y=56,x=99,symbolName=2,},
{y=56,x=9,symbolName=5,},
{y=56,x=69,symbolName=5,},
{y=56,x=19,symbolName=4,},
{y=56,x=59,symbolName=4,},
{y=56,x=89,symbolName=4,},
{y=56,x=40,symbolName=7,},
{y=56,x=80,symbolName=6,},}
tmp2={}
ywf = 1
table.sort(crdsClear,
function(a,b)
tmp2[ywf]=""
for i=1, #crdsClear, 1 do tmp2[ywf] = tmp2[ywf].."\t"..crdsClear[i].x end
ywf = ywf + 1
if a.x <= b.x then print(a.x.." <= "..b.x.." true") else print(a.x.." <= "..b.x.." false") end
return a.x <= b.x -- a.y <= b.y and
end
)
-- Create string
order=""
print(#crdsClear)
result = {[1]=""}
for i=1, #crdsClear, 1 do
order = order..crdsClear[i].x.." "
result[1] = result[1].. crdsClear[i].symbolName
end
print(order)
print(result[1])
I have .x order after sorting:
9 19 59 29 40 50 69 80 89 99
and string:
5442735642
Why i have incorrect order?
If i change:
return a.x <= b.x
to:
return a.x < b.x
then order full correctly.
From the Lua reference manual:
If comp is given, then it must be a function that receives two list
elements and returns true when the first element must come before the
second in the final order (so that, after the sort, i < j implies not
comp(list[j],list[i])).
Using <= here results in an invalid sort function which in some cases will invoke an error message and/or an incomplete sort result.
Use return a.x < b.x instead.
Related
The following is the code to convert a number to binary string. Can anyone tell me how ans.push_back((char)('0' + rem)) works?
class Solution {
public:
string findDigitsInBinary(int n) {
string ans;
if (n == 0) return "0";
while (n > 0) {
int rem = n % 2;
ans.push_back((char)('0' + rem));
n /= 2;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
To understand it, you just need to know that you can do arithmetic operations on char variables too. So, the simple loop below is valid and will print 0123456789.
for(char c = '0'; c <= '9'; ++c)
cout << c;
In you code, rem is either 0 or 1. So, (char)('0'+rem) is either '0' or '1' as desired, corresponding to rem=0, 1, respectively.
while (n > 0) {
int rem = n % 2;
ans.push_back((char)('0' + rem));
n /= 2;
}
Focus on this loop. Suppose n is 5
n > 0 true so enter into loop. rem = n % 2 so rem = 5 % 2 = 1
ans.push_back((char)('0' + rem)) here ('0' + rem) is (48 + 1) ASCII of '0' is 48
Now convert 48 + 1 = 49 into char that is '1'. Now push '1' into ansand then n /= 2 is 5 /= 2 that is 2. Now go back and check the condition in while loop. After loop reverse the content of ans and you have binary string of number n
First you get rem as %2. Thus the value of rem can either be 0 or 1.
In ans.push_back((char)('0' + rem)); you need to add the corresponding character to the string, that is either 0 or 1. For this you have considered '0' as base character and you simply add the rem to it, using its ASCII int. When doing such integer operation, the ASCII value of character '0' is considered, which is 48. Thus after adding rem to it, it can either be 48 + 0 = 48 or 48 + 1 = 49.
Finally, this value is type casted back to char, with 48 being '0' and 49 being '1'
WARNING: This question is only for Touch Lua users who have purchased and have knowledge of the Draw Library.
PLEASE REFER TO THE BOTTOM PORTION OF THIS QUESTION TO SEE THE FULL PROGRAM. THE SNIPPETS I USE IN THE BEGINNING ARE PART OF THAT PROGRAM (NUMPAD.LUA)
Okay, so now for the questions:
•What's the use of "." between "b" and "x"? Or "b" and "draw"? Etc...
•How does the table set up the button? Please be super specific?
•Why is there a "+", "*", and "(j-1)" in lines 7 and 8?
•What's height and width doing in there? I thought there were only x and y.
function createButtons()
buttons = { }
local c = 1
for i = 1, 4 do
for j = 1, 3 do
local b = { }
b.x = 80 + 60 * (j-1)
b.y = 160 + 60 * (i-1)
b.width = 40
b.height = 40
b.color = draw.blue
b.draw = drawButton
b.action = digitAction
buttons[c] = b
c = c + 1
end
end
buttons[1].title = '7'
buttons[2].title = '8'
buttons[3].title = '9'
buttons[4].title = '4'
buttons[5].title = '5'
buttons[6].title = '6'
buttons[7].title = '1'
buttons[8].title = '2'
buttons[9].title = '3'
buttons[10].title = '0'
buttons[11].title = '.'
buttons[11].action = dotAction
buttons[12].title = 'C'
buttons[12].color = draw.orange
buttons[12].action = clearAction
end
Lastly, referencing the program as a whole...
•How does the button know when you tap on it? Specifically what are the lines of code and how does it work? (I have a very faint understanding of track touches btw)
function digitAction(button)
if string.len(display.title) < 16 then
sys.alert('tock')
if display.started then
display.title = display.title .. button.title
else
if button.title ~= '0' then
display.title = button.title
display.started = true
end
end
else
sys.alert('tink')
end
end
function dotAction(button)
if string.find(display.title, '.', 1, true) then
sys.alert('tink')
else
display.title = display.title .. '.'
display.started = true
sys.alert('tock')
end
end
function clearAction(button)
sys.alert('tock')
display.title = '0'
display.started= false
end
function createDisplay()
display = { }
display.x = 60
display.y = 100
display.width = 200
display.height = 40
display.title = '0'
display.color = draw.red
display.started = false
end
function createButtons()
buttons = { }
local c = 1
for i = 1, 4 do
for j = 1, 3 do
local b = { }
b.x = 80 + 60 * (j-1)
b.y = 160 + 60 * (i-1)
b.width = 40
b.height = 40
b.color = draw.blue
b.draw = drawButton
b.action = digitAction
buttons[c] = b
c = c + 1
end
end
buttons[1].title = '7'
buttons[2].title = '8'
buttons[3].title = '9'
buttons[4].title = '4'
buttons[5].title = '5'
buttons[6].title = '6'
buttons[7].title = '1'
buttons[8].title = '2'
buttons[9].title = '3'
buttons[10].title = '0'
buttons[11].title = '.'
buttons[11].action = dotAction
buttons[12].title = 'C'
buttons[12].color = draw.orange
buttons[12].action = clearAction
end
function drawDisplay()
draw.setfont('Helvetica', 20)
draw.setlinestyle(2, 'butt')
local x1, y1 = display.x, display.y
local x2, y2 = x1 + display.width, y1 + display.height
draw.roundedrect(x1, y1, x2, y2, 10, display.color)
local w, h = draw.stringsize(display.title)
local x = x2 - 10 - w
local y = y1 + (display.height - h)/2
draw.string(display.title, x, y, draw.black)
end
function drawButton(b)
draw.setfont('Helvetica', 18)
draw.setlinestyle(2, 'butt')
local x1, y1 = b.x, b.y
local x2, y2 = x1+b.width, y1+b.height
draw.roundedrect(x1, y1, x2, y2, 10, b.color)
local w, h = draw.stringsize(b.title)
local x = b.x + (b.width - w)/2
local y = b.y + (b.height - h)/2
draw.string(b.title, x, y, draw.black)
end
function drawButtons()
for i = 1, #buttons do
buttons[i].draw(buttons[i])
end
end
function lookupButton(x, y)
for i = 1, #buttons do
local b = buttons[i]
if x > b.x and x < b.x+b.width and y > b.y and y < b.y+b.height then
return b
end
end
return nil
end
function drawScreen()
draw.beginframe()
draw.clear()
drawDisplay()
drawButtons()
draw.endframe()
end
function touchBegan(x, y)
local b = lookupButton(x, y)
if b then
b.action(b)
end
end
function touchMoved(x, y)
end
function touchEnded(x, y)
end
function init()
draw.setscreen(1)
draw.settitle('Num Pad')
draw.clear()
draw.tracktouches (touchBegan, touchMoved, touchEnded)
createButtons()
createDisplay()
end
function mainloop()
while true do
draw.doevents()
drawScreen()
draw.sleep(30)
end
end
function main()
init()
mainloop()
end
-- start program
main()
Thank you so much for any help you can offer! I know this is a lot of questions, but this knowledge can really help propel me forward!
WARNING: This question is only for Touch Lua users who have purchased
and have knowledge of the Draw Library
Since when do you have to purchase something to answer programming questions? All your questions are on absolute Lua basics anyway.
What's the use of "." between "b" and "x"? Or "b" and "draw"? Etc...
The dot operator is used to index table members. So b.x will give you the value that belongs to key "x" in table b. Its syntactic sugar for b["x"].
How does the table set up the button? Please be super specific?
The function createButtons creates an empty table and fills it with buttons represented by a table b that stores various button properties.
Why is there a "+", "*", and "(j-1)" in lines 7 and 8?
Because the author of that program wants to add and multiply. Here the coordinates b.x and b.y are calculated. (j-1) is used because j starts at 1, but he needs it to start at 0 for this calculation.
The 2 for loops will create 4 rows of buttons, each containing 3 buttons as the x coordinate depends on parameter j while y depends on parameter i.
What's height and width doing in there? I thought there were only x
and y.
The button needs dimensions, not only a location. As b is created as a local variable within the for loop all its properties are set here. They may be changed later.
How does the button know when you tap on it? Specifically what are the
lines of code and how does it work?
Your mainloop will call draw.doevents() every cycle. So at some point there will be an event that will cause touchBegan to be called.
The button itself does not know that it was tapped. function touchBegan(x,y) will search if one of the buttons was hit at x,y by calling lookupButton(x,y) and call its action function. action is either one of dotAction, digitAction or clearAction. So if you tap on a digit button digitAction() will be called e.g.
Do yourself a favour and read a book on Lua or at least do a Lua tutorial. Befor diving into third party libraries. If you don't know how to index the most common Lua type or that + and * are arrithmetic operators, you will have a very hard time understanding code and you will not be productive in any way.
This program in particular uses tables to represent buttons, it does this to make it more manageable. The height and width are the same way. If you are new to the draw library, reviewing code like this is only going to confuse you. Most of your questions are actually about OOP honestly
Also this question probably isn't suitable for Stack Overflow right now. If you want help/a small tutorial on the subject feel free to PM me on the Touch Lua forum, my username is warspyking, but as it stands you need to either revise or delete this question.
I am very new to Lua, so please be gentle.
I want a sorted results based on the "error" key. For this example, the output should be:
c 50 70
d 25 50
b 30 40
a 10 20
Here is my script:
records = {}
records["a"] = {["count"] = 10, ["error"] = 20}
records["b"] = {["count"] = 30, ["error"] = 40}
records["c"] = {["count"] = 50, ["error"] = 70}
records["d"] = {["count"] = 25, ["error"] = 50}
function spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
for k, v in pairs(records) do
for m, n in pairs(v) do
for x, y in spairs(v, function(t,a,b) return t[b] < t[a] end) do
line = string.format("%s %5s %-10d", k, n, y)
end
end
print(line)
end
I found this about sorting a table and tried to implement it. But it does not work, results are not sorted.
table.sort only works when the table elements are integrally indexed. In your case; when you try to call spairs, you are actually calling table.sort on the count and error indices.
First off; remove the ugly, irrelevant nested for..pairs loops. You only need the spairs for your task.
for x, y in spairs(records, function(t, a, b) return t[b].error < t[a].error end) do
print( x, y.count, y.error)
end
And that is all.
I want to see if a variable is between a range of values, for example if x is between 20 and 30 return true.
What's the quickest way to do this (with any C based language)?
It can obviously be done with a for loop:
function inRange(x, lowerbound, upperbound)
{
for(i = lowerbound; i < upperbound; i++)
{
if(x == i) return TRUE;
else return FALSE;
}
}
//in the program
if(inRange(x, 20, 30))
//do stuff
but it's awful tedious to do if(inRange(x, 20, 30)) is there simpler logic than this that doesn't use built in functions?
The expression you want is
20 <= x && x <= 30
EDIT:
Or simply put in in a function
function inRange(x, lowerbound, upperbound)
{
return lowerbound <= x && x <= upperbound;
}
Python has an in operator:
>>> r = range(20, 31)
>>> 19 in r
False
>>> 20 in r
True
>>> 30 in r
True
>>> 31 in r
False
Also in Python, and this is pretty cool -- comparison operators are chained! This is totally unlike C and Java. See http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators
So you can write
low <= x <= high
In Python -10 <= -5 <= -1 is True, but in C it would be false. Try it. :)
Why not just x >= lowerbound && x <= upperbound ?
I want a Linq Expression which dynamically compiles at runtime
I have a value and if than value greater than say for e.g. 5000 and another value > 70 then it should return a constant x
else
value greater than say 5000 and another value < 70 it returns y
How do I create an expression tree
a > 5000 & b < 70 then d
else
a > 5000 & b > 70 then e
You can use a lambda expression with the ternary operator (?:).
var d = 1;
var e = 2;
var f = 3;
Expression<Func<int,int,int>> expression =
(a, b) => (a > 5000 && b < 70) ? d :
(a > 5000 && b > 70) ? e :
f; // If b == 70
var func = expression.Compile();
var val = func(5432, 1);