How efficiently to convert one dimensional array to two dimensional array in swift3 - multidimensional-array

What is the efficient way to convert an array of pixelValues [UInt8] into two dimensional array of pixelValues rows - [[UInt8]]

You can write something like this:
var pixels: [UInt8] = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15]
let bytesPerRow = 4
assert(pixels.count % bytesPerRow == 0)
let pixels2d: [[UInt8]] = stride(from: 0, to: pixels.count, by: bytesPerRow).map {
Array(pixels[$0..<$0+bytesPerRow])
}
But with the value semantics of Swift Arrays, all attempt to create new nested Array requires copying the content, so may not be "efficient" enough for your purpose.
Re-consider if you really need such nested Array.

This should work
private func convert1Dto2DArray(oneDArray:[String], stringsPerRow:Int)->[[String]]?{
var target = oneDArray
var outOfIndexArray:[String] = [String]()
let reminder = oneDArray.count % stringsPerRow
if reminder > 0 && reminder <= stringsPerRow{
let suffix = oneDArray.suffix(reminder)
let list = oneDArray.prefix(oneDArray.count - reminder)
target = Array(list)
outOfIndexArray = Array(suffix)
}
var array2D: [[String]] = stride(from: 0, to: target.count, by: stringsPerRow).map {
Array(target[$0..<$0+stringsPerRow])}
if !outOfIndexArray.isEmpty{
array2D.append(outOfIndexArray)
}
return array2D
}

Related

Creating Expression Tree Kotlin

Hi my task is to recursively create an expression tree from a List input.
ex. ("+", 2, 3)
"+"
/ \
2 3
I know my recursion is off, but I can't figure out how to make it work. I've been at it for longer than I'm proud to admit. Any insight is appreciated! This is what I have so
fun TreeBuild(input:List<Any>): Pair<Tree, List<Any>>{
var tree = Tree(input.get(0), Unit, Unit)
var list = input
System.out.println(list)
if(input.size == 1 ){
list = list.drop(1)
return Pair(Tree(input.get(0), Unit, Unit), list)
}
var flag: Boolean = (input.get(0) is Int)
if (!flag){
list = list.drop(1)
tree.left = TreeBuild(list).first
list = list.drop(1)
tree.right = TreeBuild(list).first
}
return Pair(tree, list)
}

what is the pointer to pointer equivalent in lua

I know that you can use tables in a similar way to pointers in lua. That being said, what would pointers to pointers look like? Would they look something like dp = {p = {}}? if so what would the equivalent to the c code below be in lua?
void InsertItem(node **head, node *newp){
node **dp = head;
while((*dp) && (*dp)->value > newp->value
{
dp = &(*dp)->next;
}
newp->next = *dp;
*dp = newp;
}
Yes, double pointer may be translated to Lua as nested table.
local function InsertItem(head, newitem)
while head.next and head.next.value > newitem.value do
head = head.next
end
newitem.next = head.next
head.next = newitem
end
-- Typical Usage:
local head = {}
InsertItem(head, {value = 3.14})
InsertItem(head, {value = 42})
InsertItem(head, {value = 1})
-- Now the data is the following:
-- head = {next = elem1}
-- elem1 = {next = elem2, value = 42 }
-- elem2 = {next = elem3, value = 3.14}
-- elem3 = { value = 1 }
The big difference between C pointers and Lua tables is that in C, you can take the address of a variable and pass it to a function to modify it. You can't do that in Lua, but the function could always return the modified value.
Would they look something like dp = {p = {}}?
Yes, that's about as close as close as you can get to a pointer to a pointer in Lua.
if so what would the equivalent to the c code below be in lua?
Linked lists tend to work more smoothly with recursion:
local function InsertItem(head, newp)
if not head or head.value <= newp.value then
newp.next = head
return newp
end
head.next = InsertItem(head.next, newp)
return head
end

How to optimize this loop into one linq query removing the loop call entirely?

I have this loop that builds these IEnumerables one by one, I'd like to be able to optimize this so that it can make the call and build all of these IEnumerables at once in one IEnumerable instead of a list of them as the loop has to do. The code is grouping FilteredCases (cases of different types of trees in one year) by month and calculating the percentage of trees for that month compared to the whole year. My problem is that I am doing this separately for each year and would like to do this in one LINQ call hopefully by grouping the correct data together.
Here's the code:
var seriesDataLineList = new List<IEnumerable<SeriesDataPointArray>>();
foreach (var tree in trees)
{
IEnumerable<SeriesDataPointArray> seriesDataLine = months.Select(month => new SeriesDataPointArray()
{
X = month.LookupMonthName,
Y = new object[] { Math.Round(FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId && fc.LookupMonthId == month.LookupMonthId) / (double)FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId) * 100, 0) }
});
seriesDataLineList.Add(seriesDataLine);
}
My attempt at doing this with LINQ:
var test = from fc in FilteredCases
group fc by new { fc.Tree, fc.Month }
into casesGrouped
orderby casesGrouped.Key.Tree
select new { casesGrouped.Key.Tree, casesGrouped.Key.Month, count = casesGrouped.Count() };
But I'm not sure how to get these into one IEnuerable<SeriesDataPointArray>
What you have above is a mix of loops and linq, which can get confusing because you are mixing iterative with set based logic. If you expand the code out as just loops, you may find it easier to translate to linq.
As all loops
var seriesDataLineList = new List<SeriesDataPointArray>();
foreach (var tree in trees)
{
foreach (var month in months)
{
var seriesDataLine = new SeriesDataPointArray()
{
X = month.LookupMonthName,
Y = new double[] { Math.Round(FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId && fc.LookupMonthId == month.LookupMonthId) / (double)FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId) * 100, 0) }
};
seriesDataLineList.Add(seriesDataLine);
};
}
Once you get the code in all loops, converting to linq is fairly straight forward. Nested loops are functionally equivalent a cartesian product, which syntactically in linq can be achieved by multiple uncorrelated for statements.
var results = from tree in trees
from month in months
select new SeriesDataPointArray()
{
X = month.LookupMonthName,
Y = new double[] { Math.Round(FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId && fc.LookupMonthId == month.LookupMonthId) / (double)FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId) * 100, 0) }
};
Or in lambda, multiple nested select statements. You'll need a SelectMany() in there somewhere to flatten out the nested collections.
var results = trees.Select(tree =>
months.Select(month =>
new SeriesDataPointArray()
{
X = month.LookupMonthName,
Y = new double[] { Math.Round(FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId && fc.LookupMonthId == month.LookupMonthId) / (double)FilteredCases.Count(fc => fc.LookupTreeId == tree.LookupTreeId) * 100, 0) }
}
)
).SelectMany(x => x);

converting string to vector in Unity

I am trying to convert an array of strings in unityscript with values holding values like:
"Vector3(5, 3, 8)"
into an array of vectors, but Unity will not take these strings as is. Anyone have any ideas?
you cant convert all vector elements together in c# you can do it like bellow:
its psuedoCode:
position.x=convert.ToFloat("3");
position.y=....
i think there is no api to make this for you:
"Vector3(5, 3, 8)"
You didn't give us any sample code, so I'll assume the array is nicely organized, all elements right next to each other.
While I don't think there's any way that you can do this fully using UnityScript, there's ways you can process the literal string with other languages, that is, copying from your Unity script and into another program that will do the change for you.
Here's a small sample of what I would do.
Usage: Create a file array.txt with all the Vector3(x,x,x) strings, separated by line breaks and create another file array.php
Array.txt (sample)
Vector3(5, 1, 3)
Vector3(3, 3, 1)
Vector3(2, 2, 7)
Vector3(6, 6, 4)
Vector3(8, 8, 8)
Vector3(9, 3, 2)
Vector3(1, 2, 1)
Vector3(4, 3, 6)
Vector3(5, 3, 8)
Array.php
<?
$file = file('array.txt');
$text = array();
$text[] = "var vectors = new Array;";
foreach ( $file as $i )
{
$text[] = "vectors.Push(".trim($i).");";
}
echo implode("<br>", $text);
Then just run it under a PHP sandbox or a web server and copy and paste the new array into your script.
use this method to convert a single String value into a vector3 value
public static Vector3 StringToVector3(string sVector)
{
// Remove the parentheses
if (sVector.StartsWith ("(") && sVector.EndsWith (")")) {
sVector = sVector.Substring(1, sVector.Length-2);
}
// split the items
string[] sArray = sVector.Split(',');
// store as a Vector3
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
I figure someone else might find this useful later so:
if(PlayerPrefs.GetFloat("nodeNum") > 0) {
//Assemble axis value arrays
//X
var xString = PlayerPrefs.GetString("xVals");
var xValues = xString.Split(","[0]);
//Y
var yString = PlayerPrefs.GetString("yVals");
var yValues = yString.Split(","[0]);
//Z
var zString = PlayerPrefs.GetString("zVals");
var zValues = zString.Split(","[0]);
var countNode = 0;
var goal = PlayerPrefs.GetFloat("nodeNum");
var nodeVecs = new Array(Vector3.zero);
while (countNode != goal) {
var curVec = Vector3(float.Parse(xValues[countNode]), float.Parse(yValues[countNode]), float.Parse(zValues[countNode]));
nodeVecs.Push(curVec);
countNode += 1;
}
var convNodeVecs : Vector3[] = nodeVecs.ToBuiltin(Vector3) as Vector3[];
for(var nodeVec : Vector3 in convNodeVecs) {
Instantiate(nodeObj, nodeVec, Quaternion.identity);
}
}

Flex AS3 Arraycollection sorting based on Array of values

I have been working on sorting Arraycollection like ascending , descending the numeric list. Total length of my collection will go up to 100. Now I want to preform sort to nested data like this
Data Structure
Name : String
Categories : Array ["A","x or y or z","C"]
Categories array will have maximum 3 items , out of that three items the second item can have 3 different values either X or Y or Z. My result data looks like here
{"Mike" , ["A","x","C"]}
{"Tim" , ["A","y","C"]}
{"Bob" , ["A","x","C"]}
{"Mark" , ["A","z","C"]}
{"Peter" , ["A","z","C"]}
{"Sam" , ["A","y","C"]}
anyone please explain how to sort this type of data in a way showing all "x" first , "y" next and "z" at the last and vice a versa. Any help is really appreciated. Thanks Anandh. .
You can specify a compare function in your SortField like this:
var sortfield:SortField = new SortField("Categories");
sortfield.compareFunction = myCompare;
var sort:Sort = new Sort();
sort.fields = [sortfield];
yourCollection.sort = sort;
and your compare function:
function myCompare(a:Object, b:Object):int {
/*
return -1, if a before b
return 1, if b before a
return 0, otherwise
*/
}
or something like that.. and it's untested code :)
I have created a new property to the data structure called categoryOrder In the setter I did the following and Am using the categoryOrder for sorting - sortBy = categoryOrder;. I understand little hard coding is needed but still I believe this will reduce the number of comparisons when I use compareFunction. Anyone please valid this idea. Thanks!
public function set categories(data:ArrayCollection) :void
{
if(data != null)
{
_categories = data;
for each(var categorie:Object in data)
{
switch(categorie.categoryName)
{
case "x":{categoryOrder = 1;break;}
case "y":{categoryOrder = 2;break;}
case "z":{categoryOrder = 3;break;}
}
}
}
}
Data Structure
Name : String
Categories : Array ["A","x or y or z","C"]
categoryOrder : Number

Resources