Integer fun(Node *p) //Linked list
while(p not equals NULL)
print p-> data
p=p->next
End loop
Well, that's a common linked list function. Here is a common linked list architecture:
The idea is that you have blocks with two contents: the actual data and the pointer to the next object of the list.
In the posted code, p is the pointer to the first element of the list.
The intention is to print all the list. So, it follows the steps:
Print the first element's data.
Update p to point to the next element.
Print this element's data.
and so on until there are no more elements.
Related
a=[1,2,3,4,5,6,7,8]
w=a.collect{|i| i%2==0}
p w
The result is coming to be
[false,true,false,true]
why?
When i am doing
w=a.collect{|i| i+2}
Result is an array like
[3,4,5,6,7,8,9,10,11]
Why? What am i doing wrong?
You don't need map / collect (they are aliases), you need
array.select(&:even?)
or
array.reject(&:odd?)
These methods filter original array, unlike map that performs actions with every element and returns new array of the same length
That's why you get boolean array same length instead of filtering
Please read more in docs:
Array#map, Array#select, Array#reject
Our task is create a table, and read values to the table using a loop. Print the values after the process is complete. - Create a table. - Read the number of values to be read to the table. - Read the values to the table using a loop. - Print the values in the table using another loop. for this we had written code as
local table = {}
for value in ipairs(table) do
io.read()
end
for value in ipairs(table) do
print(value)
end
not sure where we went wrong please help us. Our exception is
Input (stdin)
3
11
22
abc
Your Output (stdout)
~ no output ~
Expected Output
11
22
abc
Correct Code is
local table1 = {}
local x = io.read()
for line in io.lines() do
table.insert(table1, line)
end
for K, value in ipairs(table1) do
print(value)
end
Let's walk through this step-by-step.
Create a table.
Though the syntax is correct, table is a reserved pre-defined global name in Lua, and thus cannot should not be declared a variable name to avoid future issues. Instead, you'll need to want to use a different name. If you're insistent on using the word table, you'll have to distinguish it from the function global table. The easiest way to do this is change it to Table, as Lua is a case-sensitive language. Therefore, your table creation should look something like:
local Table = {}
Read values to the table using a loop.
Though Table is now established as a table, your for loop is only iterating through an empty table. It seems your goal is to iterate through the io.read() instead. But io.read() is probably not what you want here, though you can utilize a repeat loop if you wish to use io.read() via table.insert. However, repeat requires a condition that must be met for it to terminate, such as the length of the table reaching a certain amount (in your example, it would be until (#Table == 4)). Since this is a task you are given, I will not provide an example, but allow you to research this method and use it to your advantage.
Print the values after the process is complete.
You are on the right track with your printing loop. However, it must be noted that iterating through a table always returns two results, an index and a value. In your code, you would only return the index number, so your output would simply return:
1
2
3
4
If you are wanting the actual values, you'll need a placeholder for the index. Oftentimes, the placeholder for an unneeded variable in Lua is the underscore (_). Modify your for loop to account for the index, and you should be set.
Try modifying your code with the suggestions I've given and see if you can figure out how to achieve your end result.
Edited:
Thanks, Piglet, for corrections on the insight! I'd forgotten table itself wasn't a function, and wasn't reserved, but still bad form to use it as a variable name whether local or global. At least, it's how I was taught, but your comment is correct!
I'm trying to write a simply lua filter for pandoc in order to do some macro expansion for the elements in a ReST Table.
filter.lua
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
function Table(table)
elems=pandoc.Table(table)["rows"]
print(tablelength(table))
for v in pairs(elems) do
print(v) -- Prints nothings
end
return table
end
test.rst
======= =========
A B
======= =========
{{x}} {{y}}
======= =========
Now, if I run pandoc.exe -s --lua-filter filter.lua test.rst -t rst the program says that there are 5 elements in elems, but the for loop is just skipped and I really don't know what I'm doing wrong here.
I'm very new to Lua and also know pandoc very litte. How can I iterate over the elements in elems?
Pandoc lua-filters provide the handy walk_block helper, that recursively walks the document tree down and applies a function to the elements that match the key.
In the example below, we give walk_block a lua table (what's a map or dict in other languages) with only one key (the key Str), and the value of the table is the function to apply. The function checks for the braces, strips them and prepends foo.
function Table(table)
return pandoc.walk_block(table, {
Str = function(el)
if el.text:sub(1,2) == '{{' then
txt = 'foo' .. el.text:sub(3, -3)
else
txt = el.text
end
return pandoc.Str(txt)
end
})
end
There are a couple of areas of misunderstanding in your code. First you need to remember that everything in lua is a table (implemented as an associative array or dictionary), and arrays are just a special case of a table where the keys are integers. To avoid confusion, for the rest of this answer I will use Table when I'm referring to the pandoc document element, and table when I'm referring to the lua data structure.
Your tablelength function is just counting the number of elements in the pandoc table that represents a Table. If you look in https://www.pandoc.org/lua-filters.html#type-ref-Block you will see that a Table has 5 properties- caption, aligns, widths, headers and rows. The return value of this function is 5 because of this. If you print out the values in the loop inside tablelength then you will confirm this. If you want to count the rows then you will need to pass the rows array into the function, not the table.
The second problem is that you are creating a new table rather than using the one passed in by pandoc. Instead of using elems=pandoc.Table(table)["rows"] just use elems=table["rows"] or elems=table.rows which is equivalent. The function pandoc.Table() is used to create a new element.
Furthermore, to loop over the elements in a table that are in the form of an array, you can use the ipairs function- it will return the numerically indexed values as described here What is the difference of pairs() vs. ipairs() in Lua?.
The rows table is, as might be expected, an array of rows where each row is in turn an array of elements. So to access the elements of the table you will need to have two loops.
Finally there is the issue of the pandoc object model. Because a table can contain other things (images, links, bold text etc) the final cell value is actually a list of blocks. Now depending on what you want to do with the table you can deal with this in different ways. You can use the walk_block function that mb21 referred to, but looping over just the blocks in a single cell. If your Table only contains (unformatted) text then you can simplify things by using the stringify function, which collapses the list of blocks into a single string.
Putting all of this together gives the following modified version of your code.
local stringify=pandoc.utils.stringify
-- This function is no longer needed
function tablelength(T)
local count = 0
for e in pairs(T) do
count = count + 1
print(e) -- this shows the key not the value
end
return count
end
function Table(table)
rows=table["rows"]
print("TableLength="..#rows)
for rownum,row in ipairs(rows) do
for colnum, elem in ipairs(row) do
print(stringify(elem)) -- Prints cell text
end
end
return table
end
As to you followup question, if you want to modify things then you just need to replace the cell values, while respecting pandoc's object model. You can construct the various types used by pandoc with the constructors in module pandoc (such as the aforementioned pandoc.Table). The simplest table cell will be an array with a single Plain block, which in turn contains a single Str element (blocks usually contain a list of Inline elements).
The following code shows how you can modify a table using the existing content or the row/column number. Note that I changed the parameter to the Table function from table to tableElem because table is a common type used in lua and overriding it gives hard to track errors.
local stringify=pandoc.utils.stringify
function makeCell(s)
return {pandoc.Plain({pandoc.Str(s)})}
end
function Table(tableElem)
rows=tableElem["rows"]
for rownum,row in ipairs(rows) do
for colnum, elem in ipairs(row) do
local elemText=stringify(elem)
if elemText=="{{x}}" then
row[colnum]=makeCell(elemText:gsub("x","newVal"))
end
if rownum==1 and colnum==2 then
row[colnum]=makeCell("Single cell")
end
end
end
local newRow={ makeCell("New A"), makeCell("New B")}
table.insert(rows,newRow)
return tableElem
end
I recently started checking new Java 8 features.
I've come across this forEach iterator-which iterates over the Collection.
Let's take I've one ArrayList of type <Integer> having values= {1,2,3,4,5}
list.forEach(i -> System.out.println(i));
This statement iteates over a list and prints the values inside it.
I'd like to know How am I going to specify that I want it to iterate over some specific values only.
Like, I want it to start from 2nd value and iterate it till 2nd last value. or something like that- or on alternate elements.
How am I going to do that?
To iterate on a section of the original list, use the subList method:
list.subList(1, list.length()-1)
.stream() // This line is optional since List already has a foreach method taking a Consumer as parameter
.forEach(...);
This is the concept of streams. After one operation, the results of that operation become the input for the next.
So for your specific example, you can follow #Joni's command. But if you're asking in general, then you can create a filter to only get the values you want to loop over.
For example, if you only wanted to print the even numbers, you could create a filter on the streams before you forEached them. Like this:
List<Integer> intList = Arrays.asList(1,2,3,4,5);
intList.stream()
.filter(e -> (e & 1) == 0)
.forEach(System.out::println);
You can similarly pick out the stuff you want to loop over before reaching your terminal operation (in your case the forEach) on the stream. I suggest you read this stream tutorial to get a better idea of how they work: http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
I'm manipulating entries inside a DoubleLinkedQueue via the DoubleLinkedQueueElement.append/prepend methods. This results in the new elements being inserted into the queue, but fails to update the length, and the toList() method results in an error being thrown.
I understand queues are only supposed to have elements added at the start/end, but it looks like the interface should allow for adding in the middle via the entries. I find it hard to believe such a common/well understood data structure would have a bug at this point - so am I using DoubleLinkedQueues incorrectly? Is there another data structure that I should be using? I'm looking to merge values from another iterable into my own sorted iterable - a SplayTreeSet might get me there in n log n time, but a simple merge should get me there in linear time...
Example of code that acts unexpectedly:
main() {
var q = new DoubleLinkedQueue<int>.from([1]);
q.firstEntry().prepend(0);
print('length: ${q.length}');
int i = 0;
for (var qi in q){
print('${i++}: $qi');
}
}
Output:
length: 1
0: 0
1: 1
It looks like the length getter is only pointing to an internal counter. This is done because counting the elements everytime might take very long for long lists.
The internal counter is only updated if you use the methods that directly operate on the list instead of using the prepend method of an element. In your example you should use q.addFirst(0); which results in the length being updates. The .prepend() method just inserts a new element and changes the pointer. Which results in correct traversation of the elements, but the counter is wrong anyway.
Unfortunately it looks like you cannot insert elements in the middle of the list, nor can you make the list recount the elements. You should consider creating a bug over at www.dartbug.com.
// Update:
toList() throws an error because there are more elements than length.