how to declare an array of mutable lists and populate lists with starting values - kotlin

I want to create an array of mutable lists, and each mutable list should have a specified number of ints. These ints should have a starting value of 0.
Example: I know the number of mutable lists, n, in the array, and I know how many integers, m are in each list. I think I can declare the array like so:
// represents number of mutable lists in the array
val n = 2
// represents number of Ints inside each mutable list
val m = 3
val arr = Array<MutableList<Int>>(n) { ??? }
What this should do is it should create an Array arr that contains only the type MutableList. The array is of size n. The mutable lists take in only the type Int.
I am not sure how to iterate through these mutable lists and add m number of 0 valued integers.

Array (size: Int, init: (Int) -> T)
The function init is called for each array element sequentially starting from the first one. It should return the value for an array element given its index.
Same for MutableList
// represents number of mutable lists in the array
val n = 2
// represents number of Ints inside each mutable list
val m = 3
val arr = Array(n) { MutableList(m) { 0 } }

Related

How would I map a list of items to the arguments of another function?

I am trying to figure out the best way to map my sorted map to the arguments of another function. This is an example of what I have.
data class ValueDescription (val length: Int, val count: Int)
// Now I am trying to map to a variable that looks like this
// This variable cannot be changed, I have to return this variable in this format
// The output will be a list of ValueDescriptions with a length and count for each entry of the map I have
// I will add the results of myValues to a mutable list later
val myValues = ValueDescription(_length here__, __count here__)
I have a sorted map that I want to map to my values
// The map will look like this
// Where both Ints hold the lengths and counts
// For example I would have the length of 7 to count of 8
val out = Map<Int, Int>
How can I take the values in my sorted map and place them into the variable myValues?
I tried to map by looping through my map with the forEach method and doing something like
out.map{it.key to myValues.ValueDescription.length}
but this doesn't seem to work.
I'm not sure I completely understood the question. If I got it correctly, your input is the Map<Int, Int> and you want to transform it to a List<ValueDescription>.
You can definitely use the map function for this:
val inputMap: Map<Int, Int> = TODO("provide the initial map here")
val myValues = inputMap.map { (l, c) -> ValueDescription(l, c) }
The map function here iterates over the entries of the map, and transforms each of them into a value of type ValueDescription by calling our lambda (the part between braces { ... }).
Each entry of the map here contains a key (the length) and a value (the count). Instead of using it.key and it.value, you can also use parentheses like I did here with (l, c) to destructure the entry into its 2 parts and give them names like l and c. The above is equivalent to:
val myValues = inputMap.map { ValueDescription(it.key, it.value) }

How to create variables in a for-loop with Kotlin

Given a maximum list size in parameter size and total amount of elements in parameter elements, I need to create a list of lists. What is the syntax for creating variables in for loops in Kotlin?
The way I'm thinking of going about this is to declare and create lists before elements are added to a list. Then, when a list has reached full capacity, it is switched out for the next list that is empty.
Here is the half-baked code:
fun listOfLists(size: Int, vararg elements: String): List<List<String>> {
var amountOfElements = elements.size
var currentSubList: List<String> = mutableListOf<String>()
val numberOfLists: Int = amountOfElements / size + 1
for (n in 0..numberOfLists) {
// Code for creating the total number of lists needed
}
for (e in elements) {
if (amountOfElements % size == 0) {
// Code for switching lists
}
amountOfElements--
}
As #dyukha correctly mentioned, what you need is chunked() function.
fun listOfLists(size: Int, vararg elements: String) =
elements.asList().chunked(size)
Or, if you want to be really efficient, you can also use asSequence():
fun listOfLists(size: Int, vararg elements: String) =
elements.asSequence().chunked(size)
chunked() doesn't work on Array, because it's defined on Iterable and Sequence, and Array doesn't implement any of them.

deal with arrays of Kotlin with Long variables

I have a question about Kotlin.
I tried two versions of Kotlin, 1.0.0 and 1.2.6.
Using Kotlin, we can initialize an array and access to its element like this.
val n: Int = 10
val arr = Array(n, { it } )
val i: Int = 0
println(arr[i])
However, I got an error with this code.
val n: Long = 10
val arr = Array(n, { it } )
val i: Long = 0
println(arr[i])
It seems that it is an only way to cast Long to Int in order to compile this code.
val n: Long = 10
val arr = Array(n.toInt(), { it } )
val i: Long = 0
println(arr[i.toInt()])
However, it seems too redundant to me, but I couldn't find any solutions. So my question is
Is there any way to initialize arrays and access elements with a Long
variable?
Does Kotlin have any reasons that Long variable should not be accepted here?
Kotlin comes with longArrayOf(1, 2, 3) which will create an array for you which contains Longs.
Note that what you are trying to do with println(arr[i]) is getting a Long value out of arr, but the indexing of arrays is done with Ints. It will never work with Longs:
/**
* Returns the array element at the given [index].
* This method can be called using the index operator.
*/
public operator fun get(index: Int): Long
If you want to initialize an array of longs of the given length, you can use the same top-level Array function:
val n = 10 // n is Int
val arrayOfLongs = Array(n) { it.toLong() } // Array of 10 longs
Here the number n is Int and the initializer function converts the integer index it of an element being initialized to Long, therefore we get an array of longs as the result.
Or you can use another similar function to create a specialized LongArray:
val longArray = LongArray(n) { it.toLong() } // LongArray of 10 longs
Both arrays store longs, but the latter does it more compactly.

Specman/e list of lists (multidimensional array)

How can I create a fixed multidimensional array in Specman/e using varibles?
And then access individual elements or whole rows?
For example in SystemVerilog I would have:
module top;
function automatic my_func();
bit [7:0] arr [4][8]; // matrix: 4 rows, 8 columns of bytes
bit [7:0] row [8]; // array : 8 elements of bytes
row = '{1, 2, 3, 4, 5, 6, 7, 8};
$display("Array:");
foreach (arr[i]) begin
arr[i] = row;
$display("row[%0d] = %p", i, row);
end
$display("\narr[2][3] = %0d", arr[2][3]);
endfunction : my_func
initial begin
my_func();
end
endmodule : top
This will produce this output:
Array:
row[0] = '{'h1, 'h2, 'h3, 'h4, 'h5, 'h6, 'h7, 'h8}
row[1] = '{'h1, 'h2, 'h3, 'h4, 'h5, 'h6, 'h7, 'h8}
row[2] = '{'h1, 'h2, 'h3, 'h4, 'h5, 'h6, 'h7, 'h8}
row[3] = '{'h1, 'h2, 'h3, 'h4, 'h5, 'h6, 'h7, 'h8}
arr[2][3] = 4
Can someone rewrite my_func() in Specman/e?
There are no fixed arrays in e. But you can define a variable of a list type, including a multi-dimensional list, such as:
var my_md_list: list of list of my_type;
It is not the same as a multi-dimensional array in other languages, in the sense that in general each inner list (being an element of the outer list) may be of a different size. But you still can achieve your purpose using it. For example, your code might be rewritten in e more or less like this:
var arr: list of list of byte;
var row: list of byte = {1;2;3;4;5;6;7;8};
for i from 0 to 3 do {
arr.add(row.copy());
print arr[i];
};
print arr[2][3];
Notice the usage of row.copy() - it ensures that each outer list element will be a copy of the original list.
If we don't use copy(), we will get a list of many pointers to the same list. This may also be legitimate, depending on the purpose of your code.
In case of a field (as opposed to a local variable), it is also possible to declare it with a given size. This size is, again, not "fixed" and can be modified at run time (by adding or removing items), but it determines the original size of the list upon creation, for example:
struct foo {
my_list[4][8]: list of list of int;
};

Create array of array in mq4

How to create a array of array in mq4?
I have a function with this pararameters:
double & v1[], double & v2[], double & v3[], double & v4[]
I want to create a array where each position has a reference to another array like:
double v[];
v[0] = v1;
v[1] = v2;
v[2] = v3;
v[3] = v4;
and then iterate like:
v[0][2] == v1[2]; // true
It's possible to do something like that? How can I do it?
You have pretty much already answered yourself already. A 2D array can be thought of/imagined as an array with each cell of the first array containing a 1D array of the specified size. Similarly, a 3D array could be imagined as a 1D array containing a 2D array in each cell. So instead of passing in v1,v2,v3,v4 you could just have the input parameter as double &v[4][6] and loop through them.
TestFunction(double &v[4][6])
{
for(int i=0;i<4;i++)
{
for(int j=0;j<6;j++)
{
v[i][j] = 0;
}
}
}
If the arrays v1,v2,v3,v4 in your example are different sizes then you could created an array of CArrayDouble objects and pass that. E.g.
CArrayDouble TestArray2[4]
void TestFunction2(CArrayDouble &v[4])
{
for(int i=0;i<4;i++)
{
for(int j=0;j<v[i].Total();j++)
{
v[i][j];
}
}
}
In answer to your comment, if you are unable to change the function signature. You could copy the arrays into an instance of CArrayDouble.
CArrayDouble ArrayOfArray[4];
ArrayOfArray[0].AssignArray(v1);
ArrayOfArray[1].AssignArray(v2);
ArrayOfArray[2].AssignArray(v3);
ArrayOfArray[3].AssignArray(v4);
If the arrays v1,v2 etc are buffers and thus change in size on every new bar, I would declare the CArrayDouble as static and after the initial copying (which is what AssignArray does), add each new element from the arrays as and when the function is called (using the member function 'Add').