dart modulo operator circular list - dart

I want to use the modulo (%) operator in order to access to list items in a circular way. But the code below doesn't work:
void main() {
List<String> myList = ['one', 'two', 'three', 'four'];
int currIdx = 0;
for (int i = 0;i < 10;i++) {
print(myList[currIdx]);
currIdx = currIdx++ % myList.length;
}
}

Here's the solution: instead of coding
currIdx++
you must code
++currIdx
Complete code:
void main() {
List<String> myList = ['one', 'two', 'three', 'four'];
int currIdx = 0;
for (int i = 0;i < 10;i++) {
print(myList[currIdx]);
currIdx = ++currIdx % myList.length; // look second comment below which is very useful !
}
}

Related

find the index of item even there is duplication in Dart

I'm really confused on how I'm gonna find the index of item in array where there's a lot of duplicated words.
List<String> _words = "the quick brown fox jumps over the lazy dog".split(" ");
now I want to get the all the index in word "the" programmatically.
I expect a result of
List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);
// [0, 6]
You can define indexOfAll as an extension method. I would implement it like this:
extension ListExtension<T> on List<T> {
List<int> indexOfAll(T item) => [
for (int i = 0; i < length; i++)
if (this[i] == item) i,
];
}
You can create an extension method. like this:
extension Occurrences on List {
List<int> indexOfAll(String pattern) {
List<int> indexes = [];
for (int i = 0; i < this.length; i++) {
if (this[i] == pattern) {
indexes.add(i);
}
}
return indexes;
}
}
then you can use it as function on your list
print(_words.indexOfAll("the")); // [0, 6]
I don't know if there is a direct solution for this job. To solve this problem I developed a function called GetIndexes() and it works successfully.
This example prints the following output to the console:
[the, quick, brown, fox, jumps, over, the, lazy, dog]
[3, 9, 15, 19, 25, 30, 34, 39]
The solution I developed is available below:
void main()
{
String text = "the quick brown fox jumps over the lazy dog";
var split = ' ';
List<int> indexes = [];
List<String> words;
words = text.split(split);
GetIndexes(text, split, indexes);
print(words);
print(indexes);
}
void GetIndexes(String text, var split, List<int> indexes)
{
int index = 0;
for(int i=0 ; i<text.length; ++i)
{
if(text[i] == split)
{
indexes.insert(index, i);
++index;
}
}
}

Dart how to get max duplicated element in a list

I have List list= [1,2,3,4,4,4,9,6,7,7,7,8,8,8,8,8,8,8];
how can i return 8 as max repeated value
Something like this?
void main() {
final list = [1, 2, 3, 4, 4, 4, 9, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8];
print(findMaxDuplicatedElementInList(list)); // 8
}
T findMaxDuplicatedElementInList<T>(Iterable<T> list) => list
.fold<Map<T, int>>(
{},
(map, element) =>
map..update(element, (value) => value + 1, ifAbsent: () => 1))
.entries
.reduce((e1, e2) => e1.value > e2.value ? e1 : e2)
.key;
I'd just write it out, as straight-forward as possible:
Assuming the equal elements are always adjacent, and list cannot be empty, return arbitrary element with maximal count if there is more than one:
T maxDuplicated<T>(List<T> elements) {
var element = elements.count;
var count = 1;
var maxElement = element;
var maxCount = count;
for (var i = 1; i < elements.length; i++) {
var nextElement = elements[i];
if (element != nextElement) {
element = nextElement;
count = 1;
} else {
count += 1;
if (count > maxCount) {
maxElement = element;
maxCount = count;
}
}
}
return maxElement;
}
Assuming elements come in random order, so we need to remember every element we have seen,
still not allowing an empty list as input:
T maxDuplicated<T>(List<T> elements) {
var maxCount = 1;
var maxElement = elements.first
var seen = <T, int>{maxElement: maxCount};
for (var i = 1; i < elements.length; i++) {
var element = elements[i];
var count = seen[element] = (seen[element] ?? 0) + 1;
if (count > maxCount) {
maxCount = count;
maxElement = element;
}
}
return maxElement;
}
(Alternatively, I'd sort the list first, if allowed, to always be in the former situation. It's not faster than using a map, if we assume hash map lookup to be a constant time operation, but it will be more memory efficient.)

In Dart, in a sequential list of integers, how do I find a number between the items?

In a list of sequential integers, is there a simple way to locate where another integer would be placed (between two of the list members)?
main() {
var myList = new List();
myList.addAll([0, 4, 10, 20, 33, 45, 55, 64]);
int setStart;
int currentPosition;
currentPosition = 12;
// if currentPosition is greater than or equal to myList[fooPosition]
// but less than myList[barPosition]
// setStart = myList[foo]
}
So since the currentPosition is 12, the correct answer for setStart would be 10.
Try checking out package:collection's binarySearch.
Ok, figured it out myself. Pretty simple really. I just needed to add another variable (x) to indicate the list position of the upper number:
for (var i = 0; i < myList.length; i++) {
var x = i + 1;
if (currentPosition >= myList[i] && currentPosition < myList [x]) {
setStart = myList[i];
};
};

linkedList insertionsort

This is my implementation for an insertion sort method using linkedList. I have tried it and it works just fine the only problem that there is an index out of bounds exception caused by the J+1 line. Can anyone tell me how to get around that or how to fix it. Thnx
public static <T extends Comparable <? super T>> void insertionSort2(List<T> portion){
int i = 0;
int j = 0;
T value;
//List <T> sorted = new LinkedList<T>();
// goes through the list
for (i = 1; i < portion.size(); i++) {
// takes each value of the list
value = (T) portion.remove(i);
// the index j takes the value of I and checks the rest of the array
// from the point i
j = i - 1;
while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j+1 , portion.remove(j));//it was j+1
j--;
}
// put the value in the correct location.
portion.add(j + 1, value);
}
}
check this code out
just put it as a function in a class and try to call it
void InsertionSort()
{
int temp, out, in;
for(out=1 ; out<size ; out++)
{
temp = list[out];
in = out;
while (in > 0 && list[in-1] > temp)
{
list[in] = list[in-1];
--in;
}
list[in]= temp;
System.out.print("The list in this step became: ");
for (int t=0 ; t<size ; t++)
System.out.print(list[t]+" ");
System.out.println("");
}
}

Making matrices in dart

Ok guys, i've tried this:
List<num> test
for(num i = ...){
test[i]...
(...)
for(num j = ...){
test[i][j] = ...
}
}
today but didn't seem to work. My question is... Is there a way to make this in Dart? :)
Here is one way to do it:
main() {
List<List<int>> matrix = new List<List<int>>();
for (var i = 0; i < 10; i++) {
List<int> list = new List<int>();
for (var j = 0; j < 10; j++) {
list.add(j);
}
matrix.add(list);
}
print(matrix);
print(matrix[2][4]);
}
If you know the length ahead of time, and it won't change, you can pass the length to the constructor:
main() {
int size = 10;
List<List<int>> matrix = new List<List<int>>(size);
for (var i = 0; i < size; i++) {
List<int> list = new List<int>(size);
for (var j = 0; j < size; j++) {
list[j] = j;
}
matrix[i] = list;
}
print(matrix);
print(matrix[2][4]);
}
Notice the main difference. In the first example, the list is created empty, so the loops need to explicitly add elements to the list. In the second example, the list is created with a fixed size, with null elements at each index.
Changelog: The original version of the second example used the List.fixedLength(size) constructor, which existed before Dart 1.0.
One way to construct a list with a different value in each position is to use the idiom
new Iterable.generate(size, function).toList()
makeMatrix(rows, cols) =>
new Iterable<List<num>>.generate(
rows,
(i) => new List<num>.fixedLength(cols, fill: 0)
).toList();
main() {
print(makeMatrix(3, 5));
}
prints: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
It is slightly annoying that to get the fill: parameter you have to construct a fixed length list. Without a fill value, the inner lists would contain nulls. One way to get an extendable list with an initial value is to create an empty list and grow it.
(i) => <num>[]..insertRange(0, cols, 0)
This is using a method cascade to modify the list before returning it - a..b()..c() calls a.b() and a.c() before returning a. This is handy as it avoids the need for a temporary variable.
Note that, for some reason, insertRange has a positional rather than a named fill parameter.
If you want more control over the contents, you can extend the generate-to-list idea to two levels:
makeMatrix(rows, cols, function) =>
new Iterable<List<num>>.generate(
rows,
(i) => new Iterable<num>.generate(cols, (j) => function(i, j)).toList()
).toList();
main() {
print(makeMatrix(3,5, (i, j) => i == j ? 1 : 0));
}
prints: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0]]
There are some excellent libraries on pub for handling matrices (like Kevin Moore's BOT for example), but if your looking for something quick, you can just do:
List<List> test = new List<List>(n);
for (var i = 0; i < n; i++) {
test[i] = new List(n);
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
test[i][j] = myValue;
}
}

Resources