Creating a 2d array in flutter / dart - arrays

I'm brand new to flutter and dart. I've searched google and all I can find is how to make 1d lists in flutter. I need a chart of values.
Specifically I need a row 12 long and a column 31 long filled with ascending numbers
1, 32, 63,
2, 33, 64,
3, 34, 65, etc....
thanks!

int row = 3;
int col = 4;
var twoDList = List.generate(row, (i) => List(col), growable: false);
//For fill;
twoDList[0][1] = "deneme";
print(twoDList);
// [[null, deneme, null, null], [null, null, null, null], [null, null, null, null]]
Your 2D list having 3 rows and 4 columns.

Declare and initialize a matrix x having m rows and n columns, containing real numbers.
var x = new List.generate(m, (_) => new List(n));

You can use smart_arrays_numerics package...
look at this..
https://pub.dev/packages/smart_arrays_numerics
else you should use nested list.
List<List<int>>
and create your list with generator

To get exactly what you want, you could use double List.generate, i.e.:
const cols = 31;
const rows = 12;
final array = List.generate(rows,
(i) => List.generate(cols + 1, (j) => i + j * cols + 1, growable: false),
growable: false);
array.forEach((row) {
print(row);
});
// [1, 32, 63, ...
// [2, 33, 64, ...
// [3, 34, 65, ...
// ...
There is also List.filled, where you can fill the array with some initial value when created. The following init the 2d array with 0s.
final array = List.generate(rows + 1, (i) => List.filled(cols + 1, 0, growable: false), growable: false);

To declare and initialize the array 2D in the dart, you can use:
List<List<int>> a =
[
[10, 2, 4, 6, -2],
[ 1, -16, 6, -2, -5],
[ 0, 3, 10, -5, 1],
[ 0, -4, 1, 18, 2],
[ 3, 1, 2, 2, -14],
];

#vahab
so would I do
final int NROWS = 12, NCOLS = 31;
List<Float64List> matrix = List(NROWS);
for (int i = 0; i < 373; i++) {
Float64List row = Float64List(NCOLS);
for (int k = 0; k < NCOLS; k++) { //I dont know what this does
row[k] = double.parse("$i.$k");
}
matrix[i] = row;
}

I would use a nested collection-for:
const maxRows = 31;
const maxColumns = 12;
var matrix = [
for (var row = 0; row < maxRows; row += 1)
[for (var column = 0; column < maxColumns; column += 1)
1 + row + column * maxRows],
];

Just use this statement i got this same problem, Got resolved
var list1 = List.generate(12,(i) => List.generate(31, (j) =>{Your equation to genearte })));

To initialize a 2d matrix filled with 0 :
List.generate(numberRows, (_) => List.filled(numberColumns, 0));

Related

Google apps script: array as property of an object is the same in all instances of the object

I have a simple object with two properties, one string and one array. When I create a few variables, each as a new instance of my object using Object.create, all my variables have their own string properties, but they all share the same array! If you run the code below step by step, you can see at each affectation of the array that all the arrays of the previous variable are also edited !!! (but the string property is ok). Indeed, we can see that the arrays in all the variables are in fact the same array thanks to the ObjectId of the debugger... Do you know how to make each array specific to each variable and not having all the variables sharing the same object?
function myFunction() {
// Object definition
var my_object = Object.create(null, {
my_object_name: {value: new String(), enumerable: true, writable: true},
my_object_array: {value: new Array(), enumerable: true, writable: true},
build: {
value: function (i) {
this.my_object_name = "name_" + i.toString();
for (var j = 0; j <= 4; j++) {
this.my_object_array[j] = i + j;
}
return this;
}
}
});
// Main
var my_variable_1 = Object.create(my_object).build(1);
var my_variable_2 = Object.create(my_object).build(5);
var my_variable_3 = Object.create(my_object).build(10);
}
At then end, we will obtain the result below, with all different strings for my_object_name property but all the same arrays for the my_object_array property
my_variable_1.name = "name_1" / my_variable_1.array = [10, 11, 12, 13, 14]
my_variable_2.name = "name_2" / my_variable_1.array = [10, 11, 12, 13, 14]
my_variable_3.name = "name_3" / my_variable_1.array = [10, 11, 12, 13, 14]
But I would like to find:
my_variable_1.name = "name_1" / my_variable_1.array = [ 1, 2, 3, 4, 5]
my_variable_2.name = "name_2" / my_variable_1.array = [ 5, 6, 7, 8, 9]
my_variable_3.name = "name_3" / my_variable_1.array = [10, 11, 12, 13, 14]
Your my_object_array sits on the prototype and every access leads to same array through prototype chain. Different properties have to sit on the objects themselves.
Try this -
// constructor
function MyObject(i) {
this.name = 'name_' + i; // own
this.array = this.build(i); // own
}
// on prototype = shared
MyObject.prototype.build = function(i) {
var arr = [];
for (var j = 0; j <= 4; j++) {
arr[j] = i + j;
}
return arr;
};
// Main
var my_variable_1 = new MyObject(1);
var my_variable_2 = new MyObject(5);
var my_variable_3 = new MyObject(10);
console.log(my_variable_1.array);
console.log(my_variable_2.array);
console.log(my_variable_3.array);
// [ 1, 2, 3, 4, 5 ]
// [ 5, 6, 7, 8, 9 ]
// [ 10, 11, 12, 13, 14 ]

Looping through Array, return largest number

For the Life of me i can not understand why this doesn't work.
I'm trying to find the Largest number in the array. Plz explain what I did wrong here.
function largestOfFour(arr) {
var maxArry = [];
for (let i = 0; i < arr.length; i++) {
var Max = 0;
for (let y = 0; y < arr.length; y++) {
var currentElement = arr[i][y];
if (currentElement >= Max) {
Max = currentElement;
}
}
console.log(Max);
}
}
largestOfFour([
[4, 5, 6, 7, 9],
[9, 4, 5, 64, 3],
[4, 4, 6, 8, 35],
[3, 5, 76, 54, 3]
]);
Try this:
function largestOfFour(arr) {
var largestNr = 0;
arr.map(child => {
var largestChild = Math.max(...child)
if (largestChild > largestNr) largestNr = largestChild
})
return largestNr;
}
or if you care about IE browser support of Spread opearator, use:
var largestChild = Math.max.apply(null, child)
Array.Map() is more reliable these days because it's easier to use and less bug-prone :)
You can read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Try this for sort array:
var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];
for (var i = 1; i < Arr.length; i++)
for (var j = 0; j < i; j++)
if (Arr[i] > Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
console.log(Arr);
then get four first item in array.
Your variable assignment of Max needs to go outside your for loop as every time you finish your inner loop, Max will reset to 0 as you iterate through the outer loop.

How to find the lowest number in an array? [duplicate]

This question already has answers here:
Find min / max value in Swift Array
(16 answers)
Closed 1 year ago.
I am writing an algorithm to find the lowest number in an array however my print statement keeps saying that the lowest number is 0. I have the following:
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
func findMin(numbers: NSArray) {
var minValue = numbers[0]
var isSmallest: Bool
for i in 0...numbers.count {
isSmallest = true
for j in 0...numbers.count {
if i > j {
isSmallest = false
}
}
if isSmallest {
minValue = i
}
}
print("Smallest value in the list is \(minValue)")
}
findMin(numbers: list as NSArray)
My print statement returns as:
"Smallest value in the list is 0\n"
I feel like the algorithm is correct. Any ideas?
EDIT: Answered my own question
I was iterating over indices and not actual values. Thanks to one of the users in the comments. The correct code should be:
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
func findMin(numbers: NSArray) {
var minValue = numbers[0]
var isSmallest: Bool
for i in list {
isSmallest = true
for j in list {
if i > j {
isSmallest = false
}
}
if isSmallest {
minValue = i
}
}
print("Smallest value in the list is \(minValue)")
}
findMin(numbers: list as NSArray)
Simply
let list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
let minValue = list.min()
For logic use try this
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
var minValue = list[0]
for num in list {
minValue = (num < minValue) ? num : minValue
}
print("Smallest value in the list is \(minValue)")
For direct get min value by property
let list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
let minValue = list.min()
Or you could just use
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
list.min() // returns 2
If you'd like to find the min value without an extra loop, try this:
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
func findMin(numbers: NSArray) {
var minValIdx = 0
var minValue = numbers[0] as! Int
for i in 1..<numbers.count {
if (numbers[i] as! Int) < minValue {
minValue = numbers[i] as! Int
minValIdx = i
}
}
print("Smallest value in the list is \(minValue)")
}
findMin(numbers: list as NSArray)
You can use this code in Swift for manual algorithm:
let list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
var smallest = list[0]
for item in list {
if (item < smallest) {
smallest = item
}
}
print("smallest number is: \(smallest)")
And if you want Swift to do the hard work then use this:
let smallest = list.min()
print("smallest number is: \(smallest)")
here it is your solution
let numbers = [1, 6, 3, 9, 4, 6]
let min = minElement(numbers) // 1
let position = find(array, min)// it will return index
Just to throw a few more options out there, assuming you have to actually show some logic:
func min<T:Comparable>(_ elements:[T]) -> T? {
guard let first = elements[0] else {
return nil
}
return elements.reduce(first, min)
}
print(min(list))
or put it in an extension, this is essentially the definition of Array.min
extension Array where Element : Comparable {
func smallest() -> Element? {
guard let first = self.first else {
return nil
}
// Use 'Swift.min' to get to the global function since Array
// already has a min function
return reduce(first, Swift.min)
}
}
print(list.smallest())
You can use this code:
it is in C#
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
int minVal = list[0];
for (int i = 1; i < list.Length; i++)
{
if (list[i] < minVal)
{
minVal = intArray[i];
}
}
To find the minimum element in the sequence, Swift 3 have an istance method called min():
var list = [5, 4, 3, 5, 2, 50, 8, 10, 300]
let minElem = list.min()
If the sequence has no elements, returns nil.
This method can be used also for a list of floats:
let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let minHeight = heights.min()
You can find the official document referece here

Sort array with goal to minimize sequence repeat

Ok so I have an array of websocket client connections. Imagine that this array contains connections to several different machines. Imagine that each different letter (1,2,3, etc) represents a different host. It might look like this:
const conns = [1,1,1,3,3,1,3,2,2,2,2,3,2,1,1,2,2];
what I would like to do, is sort the array like so:
const conns = [1,2,3,1,2,3,1,2,3, ... etc];
the rationale is if a client does not respond, I don't want to retry to the same host, I would like to try sending a message to a client on a different host, and only come back to the original host later. This is basically like a round-robin type thing.
I assume the best way to sort the array like this is:
find all the different hosts (unique letters) in the array
Iterate over this unique list, and splice off items from the original array as I go.
Here is the JS code I have for the above algorithm:
const list = [1,2,3,4,5,1,1,1,1,1,2,3,4,5,1,2,11,3,3,3,3,3,4,4,4,1,1,1];
const _ = require('lodash');
function findAndRemoveFirstMatch(m, list){
for(var i = 0; i < list.length; i++){
if(m === list[i]){
return list.splice(i,1)[0];
}
}
}
function getSorted(list){
const ret = [];
const set = _.uniqBy(list, function(x){
return x;
});
while(list.length > 0){
var i = 0;
while(i < set.length && list.length > 0){
var item;
if(item = findAndRemoveFirstMatch(set[i],list)){
ret.push(item);
}
i++;
}
}
return ret;
}
console.log(getSorted(list));
//given the above input, we get:
[ 1, 2, 3, 4, 5, 11, 1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 3, 4, 1, 3, 4, 1, 3, 1, 3, 1, 1, 1 ]
I am not proud of this code, and am wondering if there is a better way to do it. The above works for this input, but looking for a good way to clean it up and make it more generic.
Is there a better/faster way to do this?
You can do it differently:
sort input - it will help later
find maximum count of equal elements (10 in your example, for element=1), cnt
create cnt buckets to distribute elements over them
put elements in sorted order one by one into next bucket with round-robin principle
merge buckets
This way you get longer series in the end, 1 less than at the beginning.
[1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 3, 4, 1, 3, 4, 1, 3, 5, 1, 3, 5, 1, 3, 11, 1, 3, 1, 3]
Bad case is when one element appears more than n/2 times, but that's unavoidable.
var list = [1,2,3,4,5,1,1,1,1,1,2,3,4,5,1,2,11,3,3,3,3,3,4,4,4,1,1,1];
var a = list.sort(function(a, b) { return a - b; });
var cnt = a.reduce(function(res, cur) {
if (cur == res[0])
return [cur, res[1]+1, Math.max(res[1]+1, res[2])]
else
return [cur, 1, Math.max(1, res[2])];
}, [null, 0, 0])[2];
var buckets = [];
for (var i = 0; i < cnt; i++)
buckets[i] = [];
var j = 0;
for (var i = 0; i < a.length; i++) {
buckets[j].push(a[i]);
j = (j+1)%cnt;
}
var res = buckets.reduce(function(r, cur) {
return r.concat(cur);
});
If you insist on full list of key from beginning, it's also possible:
var list = [1,2,3,4,5,1,1,1,1,1,2,3,4,5,1,2,11,3,3,3,3,3,4,4,4,1,1,1];
var a = list.sort(function(a, b) { return a - b; });
var cnt = a.reduce(function(res, cur) {
if (cur == res[0])
return [cur, res[1]+1, Math.max(res[1]+1, res[2])]
else
return [cur, 1, Math.max(1, res[2])];
}, [null, 0, 0])[2];
var buckets = [];
for (var i = 0; i < cnt; i++)
buckets[i] = [];
var j = 0;
var cur = null;
for (var i = 0; i < a.length; i++) {
if (cur != a[i])
j = 0;
buckets[j].push(a[i]);
j = j+1;
}
var res = buckets.reduce(function(r, cur) {
return r.concat(cur);
});

Writing an iterator for a 2D array

I am trying to write an iterator for a 2D array. The following is what I have come up with.
def rowsTest() {
val array = Array(
Array(9, 11, 4, 89),
Array(7, 62, 34, 2),
Array(3, 4, 5, 12),
Array(13, 4, 5, 12),
Array(3, 24, 5, 12),
Array(3, 4, 35, 12)
)
def rows: Iterator[Iterator[Int]] = {
new Iterator[Iterator[Int]] {
private var rowIndex = 0
def hasNext: Boolean = rowIndex < 6
def next: Iterator[Int] = {
val rowIterator = new Iterator[Int] {
private var columnIndex = 0
def next: Int = {
val p = array(columnIndex)(rowIndex)
columnIndex += 1
println("ColIndex = "+ columnIndex.toString)
p
}
def hasNext: Boolean = columnIndex < 4
}
rowIndex += 1
println("RowIndex = "+ rowIndex.toString)
rowIterator
}
}
}
for(row <- rows; elem <- row)
println(elem)
}
The above code when run skips the first row, and also gives an ArrayIndexOutOfBoundsException when all elements have been printed. Can you help me figure out where I've gone wrong?
Thank you,
Siddharth Raina.
How about the following code?
val array = Array(Array(1,2,3),Array(4,5,6),Array(7,8,9))
array.view.flatten.iterator
It works, as tested in REPL. Though I don't know if I achieve what I intended with "view". Any comments are welcome.
Edit
I forgot the author wanted a nested iterator.
array.iterator.map(_.iterator)
This certainly works without the "view" and without overhead.
I can't tell from your code what you actually want to do.
If you want traverse your array with iterators of iterators, there's already an easy way to do it:
val a2d = Array.tabulate(4,4)((i,j)=>4*i+j)
a2d.iterator.map(_.iterator)
And if you decide you want a single iterator, you can do that too:
a2d.iterator.flatMap(_.iterator)
If you want to traverse columns even though the array is in row-major order, then you have a little more work to do (which I think is what you were trying to do, but you mixed up your array indices, and maybe some other things):
def iterateColumns(aai: Array[Array[Int]]) = new Iterator[Iterator[Int]] {
private[this] var j = -1
private[this] val shortest = if (aai.length==0) 0 else aai.map(_.length).min
def hasNext = j+1 < shortest
def next = {
j += 1
new Iterator[Int] {
private[this] var i = -1
def hasNext = i+1 < aai.length
def next = {
i += 1
aai(i)(j)
}
}
}
}
Now you can
scala> for (row <- a2d.iterator.map(_.iterator)) println(row.mkString(" "))
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
scala> for (col <- iterateColumns(a2d)) println(col.mkString(" "))
0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15
(You also ought to be able to do a2d.view.transpose.iterator.map(_.iterator) to avoid making a copy, but unfortunately it doesn't look like this works the way you'd hope in 2.8.1.)
If you want to do it handmade in an imperative style:
def rowsTest() {
val array = Array(
Array(9, 11, 4, 89),
Array(7, 62, 34, 2),
Array(3, 4, 5, 12),
Array(13, 4, 5, 12),
Array(3, 24, 5, 12),
Array(3, 4, 35, 12)
)
def rows: Iterator[Iterator[Int]] = {
new Iterator[Iterator[Int]] {
private var rowIndex = 0
def hasNext: Boolean = rowIndex < 6
def next: Iterator[Int] = {
// fix row index for inner iterator
val rowIdx = rowIndex
val rowIterator = new Iterator[Int] {
private var columnIndex = 0
def next: Int = {
// swap indices!!!
val p = array(rowIdx)(columnIndex)
columnIndex += 1
println("ColIndex = " + columnIndex.toString)
p
}
def hasNext: Boolean = columnIndex < 4
}
rowIndex += 1
println("RowIndex = " + rowIndex.toString)
rowIterator
}
}
}
for (row <- rows; elem <- row)
println(elem)
}
but the
val rows: Iterator[Iterator[Int]] = array.iterator.map(_.iterator)
of ziggystar is still better because its work with non rectangular 2D-arrays too and is more consice and "scalaish".

Resources