Create a list from another - list

Let say I have some values in a List. I would like to return another list with a new element
fun newList():List<Int>{
val values =listOf<Int>(1,2,3,4,5,6);
return 7::values; // something like that
}

The Kotlin lists have the plus operator overloaded in kotlin-stdlib, so you can add an item to a list:
val values = listOf(1, 2, 3, 4, 5, 6)
return values + 7
There's also an overload that adds another list:
val values = listOf(1, 2, 3, 4, 5, 6)
return listOf(-1, 0) + values + listOf(7, 8)
Note that in both cases a new list is created, and the elements are copied into it.
For MutableList<T> (which has mutating functions, in contrast with List<T>), there is a plusAssign operator implementation, that can be used as follows:
fun newList(): List<Int> {
val values = mutableListOf(1, 2, 3, 4, 5, 6)
values += 7
values += listOf(8, 9)
return values
}

A different approach by using spread operator. Maybe in some case would be simpler than using + sign or mutableListOf
fun newList(): List<Int>{
val values = listOf(1,2,3,4,5,6)
return listOf(7, *values.toTypedArray(), 8, 9)
}

You can do it like this
fun newList():List<Int>{
val values =listOf(1,2,3,4,5,6) //Type can be inferred
return values.plus(7)
}

I wanted a Scala-like with for and yield. It's pretty good in - currently experimental - coroutines :
fun testYield(max:Int): List<Int> {
val values = buildSequence{
for (i in 1..max){
yield(i)
}
}
return values.toList();
}
Or in shorter way:
fun testYieldFast(max: Int) = buildSequence {
for (i in 1..max)
yield(i)
}.toList();
It allows fast immutable lazy construction, where frequent concatenation are usually slow with immutable lists.

Related

How to Initialize the List with the same element in flutter dart?

I have a list in dart I want to initialize the list with n number of the same element.
example:- initialize the integer list with element 5 4 times.
List<int> temp = [5,5,5,5];
what are different ways to initialize the list in dart flutter?
The easiest way I can think of is List.filled:
List.filled(int length, E fill, { bool growable: false }).
The params would be:
length - the number of elements in the list
E fill - what element should be contained in the list
growable - if you want to have a dynamic length;
So you could have:
List<int> zeros = List.filled(10, 0)
This would create a list with ten zeros in it.
One think you need to pay attention is if you're using objects to initialise the list for example:
SomeObject a = SomeObject();
List<SomeObject> objects = List.filled(10, a);
The list created above will have the same instance of object a on all positions.
If you want to have new objects on each position you could use List.generate:
List.generate(int length, E generator(int index), {bool growable:true})
Something like:
List<SomeObject> objects = List<SomeObject>.generate(10, (index) => SomeObject(index);
OR:
List<SomeObject> objects = List<SomeObject>.generate(10, (index) {
SomeOjbect obj = SomeObject(index)
obj.id= index;
return obj;
});
This will create a new instance for each position in list. The way you initialise the object is up to you.
You can try like this
List<int>.generate(4, (int index) => 5);
For more, read this
Here is a simplified version of the accepted answer. You can use a list literal, a filled list, or a generated list:
final literal = [5, 5, 5, 5];
final filled = List.filled(4, 5);
final generated = List.generate(4, (index) => 5);
print(literal); // [5, 5, 5, 5]
print(filled); // [5, 5, 5, 5]
print(generated); // [5, 5, 5, 5]
When you just want to fill the list with the same values, List.filled is good. Unless you literally want [5, 5, 5, 5]. In that case, just use the list literal. It's easy to read and understand.

kotlin: extracting from list

I have a list of Int items say
Now I want to call a function process(item1, item2, item3, item4)
How can I do this in kotlin.
I want to pass how much ever items are present in the list to the method. The method accepts variable number of arguments
I want to call this method from firbase mlk library
public FirebaseVisionBarcodeDetectorOptions.Builder
setBarcodeFormats(#BarcodeFormat int var1, #BarcodeFormat int... var2) {
}
So I need to call setBarcodeFormats(is there a way in kotlin to pass each element of list as an arg here)
Based on the description of your problem I assume you have one method that takes a variable number of integers – let's call it fun foo(vararg n: Int).
If that's the case, than the bytecode that gets generated is the following:
public final static varargs foo([I)V
This means the method takes an array of int, which is an IntArray in Kotlin world.
In order to call that method with an IntArray you need to do:
fun foo(vararg n: Int) {
n.forEach(::println) // do something with n
}
fun main() {
val numbers = intArrayOf(1, 2, 3, 4)
foo(*numbers) // prints 1; 2; 3; 4
}
In that snippet of code, * is the spread operator and is briefly described here.
Also note that the spread operator can only be applied to arrays, so if you have a list of Int you need to convert it to an IntArray first an then apply the spread operator, like this:
fun foo(vararg n: Int) {
n.forEach(::println) // do something with n
}
fun main() {
val numbers = listOf(1, 2, 3, 4)
foo(*numbers.toIntArray()) // prints 1; 2; 3; 4
}
EDIT
Following the update to your question, you can call that method from your Kotlin code like this:
val builder = ... // obtain a Builder instance
val args = intArrayOf(1, 2, 4, 10)
builder.setBarcodeFormats(1, *args) // or any other meaningful value
You have two ways. First is pass a List of Int to the method. second is using varargs. For example a function which takes n number as inputs and returns the average of all the inputs. If we want to use List it will be like so:
fun getAverage(numbersList: List<Int>): Float {
var sum = 0.0f
for (item in numbersList) {
sum += item
}
return (sum / numbersList.size)
}
val arrayList = arrayListOf(1, 2, 3, 4)
val result = getAverage(arrayList)
And if we want to pass numbers as infinite function parameters we could do it with varargs like this:
fun getAverage(vararg input: Int): Float {
var sum = 0.0f
for (item in input) {
sum += item
}
return (sum / input.size)
}
val result1 = getAverage(1, 2, 3)
val result2 = getAverage(1, 2, 3, 4, 5)

Slice view for C++20 ranges

Python's itertools has the islice(seq, start, stop, step) procedure that takes a sequence and returns an iterator of every stepth value of the sequence values between start and stop.
Does the Ranges library of C++20 provide a similar functionality, e.g. a function like slice that takes a random access iterator start, a sentinel stop, and a step value step, and that returns a random access iterator that iterates over every stepth value between start and stop?
In case it does not, can such an iterator adapter be implemented using the primitives provided by the Ranges library?
(I know how I can implement such an adapter by hand, so this is not the question.)
Not quite.
C++20 will have view::iota which gives you a sequence from a starting value to a sentinel. However, it does not have the stride functionality. It only increments (via ++).
However, you can combine it with range-v3's view::stride to add in the steps. That is:
auto evens = view::iota(0, 100) | view::stride(2); // [0, 2, 4, 6, ... ]
For existing ranges, there's view::slice, which also doesn't take a stride. But these are orthogonal and layer nicely:
auto even_teens = view::iota(0, 100)
| view::slice(10, 20)
| view::stride(2); // [10, 12, 14, 16, 18]
Unfortunaltely, slice and stride of Range-v3, as presented in Barry'sanswer, are not (yet) available in the Ranges library of C++20.
However, you can replace slice by combining std::views::drop_while and std::views::take_while. To replace stride, you can use the range adaptor std::views::filter and pass a specific lambda expression to it. To filter for every other element as in Barry's example, I would use a stateful lambda expression with an init capture. You can put everything together to represent the range [10, 12, 14, 16, 18] as follows:
auto even_teens = std::views::iota(0, 100)
| std::views::drop_while([](int i) { return i < 10; })
| std::views::take_while([](int i) { return i < 20; })
| std::views::filter([s = false](auto const&) mutable { return s = !s; });
For a more universal stride solution, you can use a counter along with the modulo operator in the lambda expression. To be able to specify the stride size n in a readable way, I would use the following lambda expression, which provides another lambda expression that keeps track of the stride operation:
auto stride = [](int n) {
return [s = -1, n](auto const&) mutable { s = (s + 1) % n; return !s; };
};
All in all, the final solution looks like this:
auto even_teens = std::views::iota(0, 100)
| std::views::drop_while([](int i) { return i < 10; })
| std::views::take_while([](int i) { return i < 20; })
| std::views::filter(stride(2));
Code on Wandbox

How to remove similar elements from a Dart list?

I'd like to remove similar elements from a dart list, where similarity is given by some boolean function.
For example in Mathematica I would achieve that as follows:
Union[{2, -2, 1, 3, 1}, SameTest -> (Abs[#1] == Abs[#2] &)]
This statement yields the following list - {-2, 1, 3}. Effectively I'd like to keep one element from each equivalence class.
I know there is a function list.retainWhere( (e) => bool test(e) ), unfortunately this test can only operate on one value at a time. Another option, of course, I could do something like this (just writing from my head)
i=0;
for(final E in list) {
i++;
for(j=i; j<list.skip(i).length; j++) {
if sameTest(e, E) then list.removeAt(i+j);
}
}
but i find this bit ugly.
Any advice?
UPDATE
I will clarify my problem in more details and then show how to solve it using advice given below.
class Pair<T> {
final T left;
final T right;
Pair(this.left, this.right);
}
Now I want to have a structure holding such pair or points, and i don't want to hold point which are sufficiently close to each other. To do so I adopt solution of Alexandre Ardhuin and his comment too, which actually makes a difference for more complicated cases: Considering 2 elements e1 and e2 you have to define hashCode to ensure that e1.hashCode == e2.hashCode if e1 == e2
so here it goes:
int N=1000;
LinkedHashSet<Pair<double>> myset =
new LinkedHashSet<Pair<double>>(
equals: (Pair<double> e1, Pair<double> e2) =>
(e1.left - e2.left)*(e1.left - e2.left) + (e1.right - e2.right)*(e1.right - e2.right) < 1/N,
hashCode: (Pair<double> e){
int ex = (e.left*N).round();
int ey = (e.right*N).round();
return (ex+ey).hashCode;
}
);
List<Pair<double>> list = [new Pair<double>(0.1,0.2), new Pair<double>(0.1,0.2001)];
myset.addAll( list );
the result will be {0.1,0.2}. If the second element of list is altered to {0.1, 0.201} I predictably get a set with two elements.
Hope this was useful.
You can use a LinkedHashSet and define the equals and hashcode to use.
import 'dart:collection';
main() {
final result = new LinkedHashSet<int>(
equals: (int e1, int e2) => e1.abs() == e2.abs(),
hashCode: (int e) => e.abs().hashCode);
result.addAll([2, -2, 1, 3, 1]);
print(result); // {2, 1, 3}
}

List in scala -getting element from the right side

I have started learning scala and I wonder is there a way I could get elements in the List from the right side
For example
val myList = List(1, 2, 3, 4, 5)
if I writemyList(-1) I would get 5.
Is there any simple way to get it done or I'll have to write my own function?
myList.last
? Remember that this operation has O(n) complexity for List. Also you can simply reverse the list and use normal indices:
myList.reverse(0)
Scala's List is a singly linked list, and therefore indexed lookup on it would be a linear time operation. Since you are interested in backward indices, you'll also have to call .length method, which is a linear time operation as well.
If you need to perform indexed access, List is probably not the right data structure to use. You should instead use Vector which is a sequence type with efficient indexed access (takes constant time effectively).
Refer this link for an overview of performance characteristics of various Scala collections.
scala> val v = Vector(3, 4, 5, 2)
v: scala.collection.immutable.Vector[Int] = Vector(3, 4, 5, 2)
scala> v(v.length - 1)
res21: Int = 2
myList(myList.length-1-index)
Note then myList.length has O(n) complexity, and querying for specific index has O(index).
To do something like:
myList(-n)
You can define an implicit conversion that lets you do:
myList.getFromRight(n)
Here is the code for the implicit conversion. It will create a new getFromRight method on all Seqs, so it will work on Lists, Vectors, etc.
implicit def getFromRightImpl[A](s: Seq[A]) = new {
def getFromRight(n: Int) = s(s.length - n)
}
And here are some examples:
scala> val v = Vector(1, 2, 3, 4)
v: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4)
scala> val l = List(1, 2, 3, 4)
l: List[Int] = List(1, 2, 3, 4)
scala> v.getFromRight(1)
res4: Int = 4
scala> l.getFromRight(3)
res5: Int = 2
Implicit conversions are a rather advanced Scala feature, but this is one of the perfect use cases for them: when an object is lacking methods you think it should have, but modifying it with inheritance is not an option, you can define an implicit conversion to another object with the methods you want.