How to create a matrix in Dart? - collections

I have a List<String> and I want to create a square matrix (2-dimensional array/list) of Set<String> with the same dimensions as the length of the List<String>.
I tried using
List.filled(entries.length, List.filled(entries.length, Set<String>()));
but the problem is that it seems that each row of my matrix refers to the same list instance, so changing a value in one row changes it in all the others as well.
So then I tried
List.filled(entries.length, List.from(List.filled(entries.length, Set<String>())));
but I still have the same problem. Eventually I surrendered and resorted to
List<List<Set<String>>> matrix = [];
for(int i=0; i<entries.length; i++) {
List<Set<String>> row = [];
for (int n = 0; n<entries.length; n++) {
row.add(Set<String>());
}
matrix.add(row);
}
It works, but it's ugly. Is there a cleaner way to do this?

List.generate(n, (_) => List.generate(n, (_) => <String>{}));

Probably, you could use Matrix2 class (or matrixes with other dimensions: Matrix3, Matrix4). Unfortunately, I have no experience in using these classes, but maybe it has a sense for you. These classes have constructors for generating matrix from lists.

Related

How add data in nested relation? I have" Must be non-negative and less than the size of the collection" error [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
I'm getting one of the following errors:
"Index was out of range. Must be non-negative and less than the size of the collection"
"Insertion index was out of range. Must be non-negative and less than or equal to size."
"Index was outside the bounds of the array."
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.
How indexing arrays works
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.
How other collections work
Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.

how to store contetnts of a several array in a matrix in C

I am trying to store contents of different vectors in a matrix.
length of vectors are different and they are all strings. lets say:
A=["MXAA', "MXBB", "MXCC"]
B=["JJJ", "LKLKLKL"]
so the new matrix should look like the following:
C= [MXAA, MXBB, MXCC;JJJ, LKLKLKL, 0]
is the a way to do that in C?
thanks
You would need to create an array of pointers to pointer to the element type (which in your case is a pointer to char).
The problem you need to consider is that every array is different size; so I suggest you store the size of the arrays, or you will quickly end up running over the bounds of an array. This sounds a bit like a custom type.
typedef {
int n;
char **strArr;
} stringArray;
stringArray *str2d;
str2d = (stringArray*) malloc(2*sizeof(stringArray));
str2d[0].n=3;
str2d[0].strArr = (char**)malloc(3*sizeof(char*));
str2d[0].strArr[0] = "MXAA";
str2d[0].strArr[1] = "MXBB";
str2d[0].strArr[2] = "MXCC";
str2d[1].n = 2;
str2d[1].strArr = (char**)malloc(2*sizeof(char*));
str2d[1].strArr[0] = "JJJ";
str2d[1].strArr[1] = "LKLKLKL";
If you want to access an element you use similar addressing - but check that you stay within bounds!
I deliberately did this in very explicit steps, hoping this makes the principle clear. There are better ways to do this but they are more obscure (or not "standard C")

Merge sorted lists into new list

So i need to write a program that merges two sorted lists into a new third sorted list and I can ONLY use operations of the ADT sorted list.
As with all my other assignments I start with pseudocode but I am in a funk tonight and can't wrap my head around some pseudocode for this.
I have written some pointers though: Create a new sorted list; while the two lists are not empty remove and compare them, to add one or the other to the new list. Stop when the lists are empty (but do think about what happens when one becomes empty before the other!).
Any and all help is very appreciated
EDIT: To let you know I am just looking for Pseudocode help NOT actual code
function merge (lista, listb) {
toReturn = your 'third list'
while lista and listb both still have elements {
if lista's smallest element < listb's smallest element {
add lista's smallest element to toReturn
remove lista's smallest element
} else {
add listb's smallest element to toReturn
remove listb's smallest element
}
}
// if lista has no elements, this loop is skipped
while lista still has elements {
add them to toReturn
}
// if listb has no elements, this loop is skipped
while listb still has elements {
add them to toReturn
}
return toReturn
}
this can be done by using merge procedure of merge sort
this is my cde where i have passed all the 3 list from main function
public static void merge(int A[],int A1[],int B1[],int n1,int n2)
{
int a[]=new int[n1+1];
int b[]=new int[n2+1];
for(int k=0;k<n1;k++){
a[k]=A1[k];
}
for(int k=0;k<n2;k++){
b[k]=B1[k];
}
int i=0,j=0;
a[n1]=Integer.MAX_VALUE;
b[n2]=Integer.MAX_VALUE;
for(int k=0;k<A.length;k++){
if(a[i]>b[j]){
A[k]=b[j];
j++;
}
else{
A[k]=a[i];
i++;
}
}
}

How can I simply check if a set of n numbers are all different?

I have n integers and I need a quick logic test to see that they are all different, and I don't want to compare every combination to find a match...any ideas on a nice and elegant approach?
I don't care what programming language your idea is in, I can convert!
Use a set data structure if your language supports it, you might also look at keeping a hash table of seen elements.
In python you might try
seen={}
n_already_seen=n in seen
seen[n]=n
n_already_seen will be a boolean indicating if n has already been seen.
You don't have to check every combination thanks to commutivity and transitivity; you can simply go down the list and check each entry against each entry that comes after it. For example:
bool areElementsUnique( int[] arr ) {
for( int i=0; i<arr.Length-1; i++ ) {
for( int j=i+1; j<arr.Length; j++ ) {
if( arr[i] == arr[j] ) return false;
}
}
return true;
}
Note that the inner loop doesn't start from the beginning, but from the next element (i+1).
You can use a Hash Table or a Set type of data structure that using hashing. Then you can insert all of the elements into the hashtable or hashset, and either as you insert, check if the element is already in the table/set. If for some reason you don't want to check as you go, you can just insert all the numbers and then check to see if the size of the structure is less than n. If it is less than n, there had to be repeated elements. Otherwise, they were all unique.
Here is a really compact Java solution. The time-complexity is amortized O(n) and the space complexity is also O(n).
public boolean areAllElementsUnique(int [] list)
{
Set<Integer> set = new HashSet<Integer>();
for (int number: list)
if (set.contains(number))
return false;
else
set.add(number);
return true;
}

Basics in for loop in actionscript 3 in flex

Good Morning stackoverflow...
I'm having a problem.... this is my sample code
var i:Number = new Number();
trace("showarray length" + showArray.length);
for(i=0;i<showArray.length;i++){
trace("equal daw" + showArray.getItemAt(i).id + "==" + num);
if(showArray.getItemAt(i).id == num){
showArray.removeItemAt(i);
}
}
trace('alerts');
myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop
this is a sample output
given that the length of showArray is 2 and num = 0
showarray length2
equal daw0==0
alerts
please help me
If you want to remove items while iterating over array, iterate in reverse order. This way element removal does not affect cycle condition:
for (var i:int = showArray.length - 1; i >= 0; i--) {
if (someCondition) {
showArray.removeItemAt(i);
}
}
Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step.
An even better way might be to use the filter method of the Array class.
array = array.filter(function (e:*, i:int, a:Array):Boolean {
return e.id != num;
});
When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.
That's because you are removing items at the time you are iterating throught them.
array = [1, 2]
^ // pointer in first iteration
eliminate 1
array = [2]
^ // the pointer remains in the same location
//ups! out of the loop. all items were visited.
You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards.
PS: Sorry for my poor English.
After showArray.removeItemAt(i);, add i--;
Because you removed the item at index i from the array, the item that was at i + 1 got moved to i. By subtracting one, you ensure that the moved item doesn't get skipped.
alxx's answer is also a good solution.

Resources