Doing math with elements of a 2d-array? - arrays

So I am making a 2d-array like this:
var kcalVerdier:Array = new Array(92,80,103,36,53);
var alleNumSteppers:Array = new Array(alleNumSteps.numStepMelk.value,alleNumSteps.numStepEgg.value,alleNumSteps.numStepBrød.value,alleNumSteps.numStepSmør.value,alleNumSteps.numStepOst.value);
var c:Array = new Array(kcalVerdier,alleNumSteppers);
function endreAntall(evt:Event)
{
txtTotalKcal.text = String(c[0] * [0]);
}
Is it not possible to do multiply 2 values of a 2-d Array? I get this error:
Scene 1, Layer 'script', Frame 1, Line 17, Column 38 1067: Implicit coercion of a value of type Array to an unrelated type Number.
I don't understand why, c[0][0] should both be integer values or am I misunderstanding?

Which values you actually want to multiply?
By doing:
c[0] * [0]
you're trying to multiply Array by Array.
c[0] would be 1st element of c Array which is in fact kcalVerdier Array.
[0] is making new Array with one element (that is 0);
so it's like
[92,80,103,36,53] * [0]
[EDIT]
Ok, try this piece of code:
// Check if both Arrays are what we want:
trace("kcalVerdier => " + c[0]);
trace("alleNumSteppers => " + c[0]);
trace();
// Gett Arrays lengths
var arr1Length:int = c[0].length;
var arr2Length:int = c[1].length;
// Check if both are the same length
if(arr1Length == arr2Length)
{
// Let's iterate
for(var i:int = 0; i<arr1Length; i++)
{
trace( c[0][i] * c[1][i] );
}
}

Related

How to use reduce() on multidimensional arrays in swift

I want to iterate through a multidimensional array and compare the elements with one another and increment a value if a condition is met
var arrayExample = [[4,8],[15,30],[25,50]];
var noOfSimiRect: Int = 0
arrayExample.reduce(0) {
let a = $0[0] //error: Value of type 'int' has no subscripts
let b = $0[1] //error: Value of type 'int' has no subscripts
let c = $1[0]
let d = $1[1]
if a.isMultiple(of: c) && b.isMultiple(of: d) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)
Alternatively, if I used the following syntax, I am still getting the error there
var arrayExample = [[4,8],[15,30],[25,50]];
var noOfSimiRect: Int = 0
arrayExample.reduce(0) {
let a = $0.0 //error: value of type 'int' has no member '0'
let b = $1.0 //error: value of type 'int' has no member '1'
let c = $0.0 //error: value of type '[int]' has no member 0'
let d = $1.0 //error: value of type '[int]' has no member '1'
if a.isMultiple(of: c) && b.isMultiple(of: d) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)
Thank you to David and Martin for answering my question but I found a catch in both your solutions.
var arrayExample = [[4,8],[15,30],[25,50]];
In the given array I want the following:
compare [4,8] with [15,30] and [25,50]
compare [15,30] with [4,8] and [25,50]
compare [25,50] with [4,8] and [15,30]
It seems you misunderstand the inputs to the closure of reduce. The first input argument is the accumulating result, while the 2nd is the current element of the array. $0 and $1 are not the current and next elements of the array as you assume they are.
You need to iterate over the indices of the array to access 2 subsequent nested arrays and be able to check their elements against each other.
var noOfSimiRect: Int = 0
for index in arrayExample.indices.dropLast() {
let current = arrayExample[index]
let next = arrayExample[index + 1]
if current[0].isMultiple(of: next[0]) && current[1].isMultiple(of: next[1]) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)

Add Object to Array in Matlab

I'm new to matlab and I can't add an object to an array:
%g is a transfer function
h = bodeplot(g);
% class('h') prints 'resppack.bodeplot'
a = zeros(2,1);
a(1,1) = h;
% I get the error: Conversion to double from resppack.bodeplot is not possible.
This happens because my matrix 'a' is of type double while 'h' isn't.
How can I define an array of type 'resppack.bodeplot'?
resppack.bodeplot doesn't have an 'empty' method...
The problem here, i s that you create an array of doubles, and you want to store other things.
You can not initialize the array and start adding objects like this:
my-array(1) = something
my-array(2) = something-2
...
new-array(1) = h
new-array =
resppack.bodeplot
new-array(2) = h
new-array =
resppack.bodeplot: 1-by-2
new-array
new-array =
resppack.bodeplot: 1-by-2

How to read csv file into an Array of arrays in scala

I'm trying to read a csv file and return it as an array of arrays of doubles (Array[Array[Double]]). It's pretty clear how to read in a file line by line and immediately print it out, but not how to store it in a two-dimensional array.
def readCSV() : Array[Array[Double]] = {
val bufferedSource = io.Source.fromFile("/testData.csv")
var matrix :Array[Array[Double]] = null
for (line <- bufferedSource.getLines) {
val cols = line.split(",").map(_.trim)
matrix = matrix :+ cols
}
bufferedSource.close
return matrix
}
Had some type issues and then realized I'm not doing what I thought I was doing. Any help pointing me on the right track would be very appreciated.
It seems your question was already answered. So just as a side note, you could write your code in a more scalaish way like this:
def readCSV() : Array[Array[Double]] = {
io.Source.fromFile("/testData.csv")
.getLines()
.map(_.split(",").map(_.trim.toDouble))
.toArray
}
1) You should start with an empty Array unstead of null.
2) You append items to an Array with the operator :+
3) As your result type is Array[Array[Double]] you need to convert the strings of the csv to Double.
def readCSV() : Array[Array[Double]] = {
val bufferedSource = io.Source.fromFile("/testData.csv")
var matrix :Array[Array[Double]] = Array.empty
for (line <- bufferedSource.getLines) {
val cols = line.split(",").map(_.trim.toDouble)
matrix = matrix :+ cols
}
bufferedSource.close
return matrix
}

Fisher-Yates Shuffle Algorithm error

so I'm currently making a quiz game with Actionscript 3.0, and I wanna shuffle the questions with this Fisher-Yates Shuffle Algorithm:
This is my code:
var questions:Array = [1,2,3,4,5,6,7,8,9,10];
function ShuffleArray(input:Array)
{
for (var i:int=input.length-1; i>=0; i--)
{
var randomIndex:int = Math.floor(Math.random() * (i+1));
var itemAtIndex:int = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
}
function buttoncorrect(event:MouseEvent):void
{
ShuffleArray(questions);
trace (questions);
var quest:int = questions.splice(questions, 1)[0];
trace(quest);
}
btntry.addEventListener(MouseEvent.CLICK,buttoncorrect);
And here is the trace result:
9,7,5,10,4,8,6,2,1,3
9
7,1,2,6,8,10,5,4,3
7
5,2,3,10,6,1,8,4
5
4,3,10,6,2,8,1
4
2,1,8,3,6,10
2
10,8,6,1,3
10
3,8,6,1
3
1,8,6
1
6,8
6
8
0
Why do I always get the "0" value at the end? I should've get the value of "8" right?
Does someone know what's wrong with my code? Thank you.
The problem is this line:
var quest:int = questions.splice(questions, 1)[0];
The first parameter to splice() is supposed to be a start index. Since you want to remove the first element, it should be zero:
var quest:int = questions.splice(0, 1)[0];
The reason your code works for each case except the last one is because of the way automatic type conversion from Array to int works. ActionScript is automatically converting the array passed as the first parameter to a zero when it has more than one element, but converts it to the value of the only element in the array when it has a single element. So it is effectively:
var quest:int = questions.splice(0, 1)[0];
right up until the last call, when you pass in an array containing the single value 8. Then the last time it gets called, you are effectively doing this:
var quest:int = questions.splice(8, 1)[0];
Since that index is beyond the end of the array, an empty array is returned and traces out as 0.

Accessing Array Length comes back as Zero

I have an array in ActionScript 3 that is formatted as follows:
var _arrayList = new Array;
_arrayList["item1"] = true;
_arrayList["item2"] = 56;
_arrayList["item3"] = "john doe";
_arrayList["item4"] = -56.8;
and I'm attempting to pull the "_arrayList.Length" but it comes back 0... why?
Because the way you do it makes the array "associative". In Action Script, every class is a basic Object, with dynamic properties. And array does both - containing indexed elements, and having a dynamic properties.
Here's an example of a regular array:
var array:Array = new Array();
array.push(value); // equal to array[0] = value;
array.push(56); // equal to array[1] = value;
array[20] = 'test'; // will put 20th element to be 'test'
If you use this approach, the length of the array will not be 0. And so you can use a for loop:
var total:uint = array.length;
for (var i:uint = 0; i < total; i++) {
trace (array[i]);
}
But when the keys are not numeric, you are actually setting "properties" to the array and thus the length is 0. Again, you can loop through them, but with for-in:
for (var key:String in array) {
trace (array[key]);
}
Here the keys won't be 0, 1, 2, 3 and so on, but instead will be item1, item2, item3. (keep in mind that the order is not preserved!)
So the basic conclusion is that if you use non-numeric keys, then use an Object instead. Array is for numeric indexed collections.

Resources