Your program should be able to achieve the following functions,
1- To add a new node to the bingeing, specific position, or the 2-
3-
4-
5- 6- 7- 8- 9- 10- 11-
To display List items.
To display List items in reverse order
To count the number of items
To insert a new item at the beginning
To insert a new item at the end
To insert a new item at the middle
To delete the first item
To delete an item from the middle
To delete the last item
To search an existing item and return node position
In Swift, the syntax is pretty much straight forward when you need to do some sort of action with arrays.
Here are the examples that you were looking for.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Insert a number to the beginning of the array
numbers.insert(0, at: 0)
// Append a number to the end of the array
numbers.append(11)
// Display the array of numbers in reverse order
print(numbers.reverse())
// Count the number of items in the array
numbers.count
// Remove the first item from the array
numbers.removeFirst()
// Remove the last item from the array
numbers.removeLast()
// Remove the item in the middle of the array (Only if the array count is not an even number so it has a middle value)
numbers.remove(at: (numbers.count / 2))
// Find the index of the number 3
numbers.firstIndex(of: 3)
Related
I'm extremely new to Apps Script and trying to make my first thing. It's a shopping list.
I want to create a function that will activate and then sort (by Column 1, 'Aisle #') all rows where there are values in a given other column (Column 3, 'Qty'). The idea is to sort the items on the list for that week (i.e., with a value filled in for Qty) by aisle to give me the order I should be looking for things. I do not want to sort items which are in the spreadsheet but without
a value for Qty.
Here is what I've got so far:
var sheet = ss.getActiveSheet()
var range = sheet.getDataRange();
var rangeVals = range.getValues()
function orderList2(){
if(rangeVals[3] != ""){
sheet.activate().sort(1, ascending=true);
};
};
I'm trying to use "if" to define which rows to activate before doing the sort (as I don't want to sort the entire sheet—I only want to sort the items I will be buying that week, i.e., the items with a value in Column 3). The script runs but ends up sorting the entire sheet.
The closest thing I could find was an iteration, but when I did it, it ended up only activating the top-left cell.
Any help you can provide would be greatly appreciated!
Cheers,
Nick
Answer:
Use Range.sort() instead of Sheet.sort() if you don't want to sort the entire sheet.
Explanation:
You want to sort the data according to the value in column A (Aisle #), if the corresponding value in C (Qty) is not empty.
If my assumption is correct, the rows where Qty is empty should go below the rest of data, and they should not be sorted according to their Aisle #.
In this case, I'd suggest the following:
Sort the full range of data (headers excluded) according to Qty, so that the rows without a Qty are placed at the bottom, using Range.sort() (if you don't need to exclude the headers, you can use Sheet.sort() instead).
Use SpreadsheetApp.flush() to apply the sort to the spreadsheet.
Use getValues(), filter() and length to know how many rows in the initial range have their column C populated (variable QtyElements in the sample below).
Using QtyElements, retrieve the range of rows with a non-empty column C, and sort it according to column 1, using Range.sort().
Code sample:
function orderList2() {
var sheet = SpreadsheetApp.getActiveSheet();
var firstRow = 2; // Range starts at row 2, header row excluded
var fullRange = sheet.getRange(firstRow, 1, sheet.getLastRow() - firstRow + 1, sheet.getLastColumn());
fullRange.sort(3); // Sort full range according to Qty
SpreadsheetApp.flush(); // Refresh spreadsheet
var QtyElements = fullRange.getValues().filter(row => row[2] !== "").length;
sheet.getRange(firstRow, 1, QtyElements, sheet.getLastColumn())
.sort(1); // If not specified, default ascending: true
//.sort({column: 1, ascending: false}); // Uncomment if you want descending sort
}
Reference:
Range.sort(sortSpecObj)
I am attempting to create a pug mixin that can handle different formatting depending on the length of the generated list. I have it able to accept unlimited values, and can generate a single list no problem.
When I try to sort the items by index in order to create multiple lists, the code either generates a new <ul> for each <li> or nothing at all for the longer list formatting.
How can I make it so if the length of the items array is greater than 5, it puts the first 5 items in list 1 and the rest in the second list?
Code:
mixin panelList(...items)
if items.length < 6
ul.list-unstyled.col.col-12.col-lg-12.d-none.d-lg-inline
each item in items
li.list-item.my-lg-1= item
else
each item in items
.row.row-12
while index < 6
ul.list-unstyled.col.col-12.col-lg-6.offset-sm-4.offset-md-0.offset-lg-0.d-none.d-lg-inline
li.list-item.my-lg-1= item
while index > 5
ul.list-unstyled.col.col-12.col-lg-12.d-none.d-lg-inline
li.list-item.my-lg-1= item
mixin panelList(...items)
if items.length < 6
ul.list-unstyled.col.col-12.col-lg-12.d-none.d-lg-inline
each item in items
li.list-item.my-lg-1= item
else
each item in items
.row.row-12
while index < 6
ul.list-unstyled.col.col-12.col-lg-6.offset-sm-4.offset-md-0.offset-lg-0.d-none.d-lg-inline
li.list-item.my-lg-1= item
while index > 5
ul.list-unstyled.col.col-12.col-lg-12.d-none.d-lg-inline
li.list-item.my-lg-1= item
implemented via:
+panelList("this", "is", "working", "great") works fine
problem is with a list like:
+panelList("this", "is", "not", "working", "quite", "as", "intended", "yet")
I have tried sorting by % but it generates a new <ul> for each item. I have tried using item.index and index. I have tried using for and if instead of while before index < 6 also.
I'm a bit new to LUA. So I have a game that I need to capture the Entity and insert into the table. The maximum possible Entity table that could happen at the same time is 14. So I read that an array based solution is good.
But I saw that the table size increment even if we delete some value, for example from 10 table value and delete value at index 9 its not automatically shift the size when I want to insert table number 11.
Example:
local Table = {"hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello"}
-- Current Table size = 10
-- Perform delete at index 9
Table[9] = nil
-- Have new Entity to insert
Table[#Table + 1] = "New Value"
-- The table size will grow by the time the game extend.
So for this type of situation did array based table with nil value inside that grow by the time of new table value inserted will have better perfomance or should I move into table with key?
Or I should just stick with array based table and perform full cleanup when the table isnt used?
If you set an element in a table to nil, then that just stays there as a "hole" in your array.
tab = {1, 2, 3, 4}
tab[2] = nil
-- tab == {1, nil, 3, 4}
-- #tab is actually undefined and could be both 1 or 4 (or something completely unexpected)!
What you need to do is set the field to nil, then shift all the following fields to fill that hole. Luckily, Lua has a function for that, which is table.remove(table, index).
tab = {1, 2, 3, 4}
table.remove(tab, 2)
-- tab == {1, 3, 4}
-- #tab == 3
Keep in mind that this can get very slow as there's lots of memory access involved, so don't go applying this solution when you have a few million elements some day :)
While table.remove(Table, 9) will do the job in your case (removing field from "array" table and shifting remaining fields to fill the hole), you should first consider using "set" table instead.
If you:
- often remove/add elements
- don't care about their order
- often check if table contains a certain element
then the "set" table is your choice. Use it like so
local tab = {
["John"] = true,
["Jane"] = true,
["Bob"] = true,
}
Your elements will be stored as indices in a table.
Remove an element with
tab["Jane"] = nil
Test if table contains an element with
if tab["John"] then
-- tab contains "John"
Advantages compared to array table:
- this will eliminate performance overhead when removing an element because other elements will remain intact and no shifting is required
- checking if element exists in this table (which I assume is the main puspose of this table) is also faster than using array table because it no longer requires iterating over all the elements to find a match, the hash lookup is used instead
Note however that this approach doesn't let you have duplicate values as your elements, because tables can't contain duplicate keys. In that case you can use numbers as values to store the amount of times the element is duplicated in your set, e.g.
local tab = {
["John"] = 1,
["Jane"] = 2,
["Bob"] = 35,
}
Now you have 1 John, 2 Janes and 35 Bobs
https://www.lua.org/pil/11.5.html
Say there's a list. Each item in the list has a unique id.
List [5, 2, 4, 3, 1]
When I remove an item from this list, the unique id from the item goes with it.
List [5, 2, 3, 1]
Now say I want to add another item to the list, and give it the least lowest unique id.
What's the easiest way to get the lowest unique id when adding a new item to the list?
Here's the restriction though: I'd prefer it if I didn't reassign the unique id of another item when deleting an item.
I realise it would be easy to find the unique id if I reassigned unique id 5 to unique id 4 when I deleted 4. Then I could get the length of the list (5) and creating the new item with the unique id with that number.
So is there another way, that doesn't involve iterating through the entire list?
EDIT:
Language is java, but I suppose I'm looking for a generic algorithm.
An easy fast way is to just put your deleted ids in a priority queue, and just pick the next id from there when you insert new ones (or use size() + 1 of the first list as id when the queue is empty). This would however require another list.
You could maintain a list of available ID's.
Declare a boolean array (pseudo code):
boolean register[3];
register[0] = false;
register[1] = false;
register[2] = false;
When you add an element, loop from the bottom of the register until a false value is found. Set the false value to true, assign that index as the unique identifier.
removeObject(index)
{
register[index] = false;
}
getsetLowestIndex()
{
for(i=0; i<register.size;i++)
{
if(register[i]==false)
{
register[i] = true;
return i;
}
}
// Array is full, increment register size
register.size = register.size + 1;
register[register.size] = true;
return register.size;
}
When you remove an element, simply set the index to false.
You can optimise this for larger lists by having continuality markers so you don't need to loop the entire thing.
This would work best for your example where the indexes are in no particular order, so you skip the need to sort them first.
Its equivalent to a search, just this time you search for a missing number. If your ID's are sorted integers, you can start going from bottom to top checking if the space between two ID's is 1.
If you know how many items in the list and its sorted you can implement a binary search.
I don't think you can do this without iterating through the list.
When you say
'Now say I want to add another item to
the list, and give it the least
highest unique id. '
I assume you mean you want to assign the lowest available ID that has not been used elsewhere.
You can do this:
private int GetLowestFreeID(List list){
for (int idx = 0; idx < list.Length; ++i){
if ( list[idx] == idx ) continue;
else return idx;
}
}
this returns the lowest free index.
This assumes your list is sorted, and is in C# but you get the idea.
The data structure that would be used to do this is a Priority Binary Heap that only allow unique values.
How about keeping the list sorted. and than you can remove it from one end easily.
I have a datagrid. I add a row to the datagrid using an ADD button. Once I add, I sort the datagrid based on a column. I also provide the serial numbers i.e. row numbers as first column to the datagrid. But, the serial number function does not apply after sorting. Hence, a new row added for e.g. row 5, based on sorting should be row 1, the serial number displayed is still row 5. The UI looks bad as numbers are not in correct order. the code is :
// Sorting Function :
private function sortGrid():void
{
sortGridColl = new ArrayCollection(sortGridArray);
sortA = new Sort();
sortByLevel = new SortField("Type", true, false);
sortA.fields=[sortByLevel];
sortGridColl.sort=sortA;
sortGridColl.refresh();
sortGrid.dataProvider=sortGridColl;
sortGrid.rowCount=myDPColl.length +1;
}
// Serial Number function :
private function sortGridSerialNumbers(oItem:Object,iCol:int):String
{
myDPColl = new ArrayCollection(sortGridArray);
var iIndex:int = myDPColl.getItemIndex(oItem) + 1;
return String(iIndex);
}
// Adding new row to datagrid :
sortGrid.dataProvider.addItem
(
{
Type : typeName.text
}
);
Is sortGridSerialNumbers supposed to return the current serial numbers after sorting? Because it seems to only display the serial numbers for your original state. It won't give the correct value for any item that was added since you added the item to the dataProvider, not the original array.
I like arrays better than array collections, so my choice would be to maintain the list as a raw array. Then on each add, push the new element, do a sortOn (myArray.sortOn("Type")), then iterate over all items to adjust the serial number. Then apply the array to the datagrid as a new dataprovider.