How to get difference between two lists in dart? - list

I am creating an app right now and I want to get the difference between two lists such:
List x = ['one' , 'two' , 'three' , 'four'];
List y = ['one' , 'two',];
------
Output: ['three' , 'four']

This might be easier if you can use Set.difference instead.
If you're stuck with using lists this is a slightly shorter solution.
var l = [1, 2, 3, 4];
var r = [3, 4];
l.removeWhere((e) => r.contains(e));
print(l);

You can loop through one of the loop and then check if the item is present in the other list or not.
void main() {
List x = ['one' , 'two' , 'three' , 'four'];
List y = ['one' , 'two',];
List output = [];
for(final e in x){
bool found = false;
for(final f in y) {
if(e == f) {
found = true;
break;
}
}
if(!found){
output.add(e);
}
}
print(output);
}

Related

Flutter. Dart. Flutter - replacing a item in a list

List<int> myList = [1,2,3];
int i = 2;
myList[i] = 4; // myList = [1,2,4]
but what if i don't know whether myList contains data at specific index? Then it gives me range error.
i = 4;
myList[i] = 4 // range error
if(myList[i] != null) myList[i] = 4 //range error
myList.insert(i, 4) // i want to replace, not shift values.
Is the only way to replace the list value at specific index is by checking the whole list length first?
Here is the example that you can check the index before and If that condition is true then only it will update the value.
void main() {
List<int> myList1 = [1,2,3];
int i = 2;
if(myList1.length> i) myList1[i] = 4; // myList = [1,2,4]
myList1.forEach(print);
int j = 5;
if(myList1.length> j) myList1[j] = 4; // myList = [1,2,4]
myList1.forEach(print); // It will print as it is last one.
}
Thank you.
From what I understood, you want to know if there is any other way to check whether or not the index exists for your list.
If So then:
List<int> myList = [1,2,3];
int i = 2;
if(myList.asMap().containsKey(i)) myList[i] = 4
Let me know if I understood your question correctly.
try like this:
if(i<=myList.length){
myList[i]=4;
}

Dart: Check items in List of lists

Before adding a list I want to check that it does not exist so there are no repeated values. This works with a list of integers, but not with a list of other integer lists:
void main() {
var listasN = List<int>();
var n1 = 1;
var n2 = 2;
var n3 = 1;
void addN(int n) {
if (!listasN.contains(n)) {
listasN.add(n);
}
}
addN(n1);
addN(n2);
addN(n3);
print(listasN);
var listas = List<List<int>>();
var lista1 = [1, 2, 3, 4];
var lista2 = [5, 6, 7, 8];
var lista3 = [1, 2, 3, 4];
void addLista(List<int> ls) {
if (!listas.contains(ls)) {
listas.add(ls);
}
}
addLista(lista1);
addLista(lista2);
addLista(lista3);
print(listas);
}
Out:
[1, 2]
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]
The first function does not support repeated values, but the second does, why?
Dart lists do not have an inherent equality. That is, the == operator only considers lists equal if it's the same list, not if it's different lists with the same content.
That's generally how Dart handles equality of mutable types. The contains method uses equality for checking.
So, what you can do instead is to create a "list equals" method:
bool listEquals<T>(List<T> list1, List<T> list2) {
if (list1.length != list2.length) return false;
for (var i = 0; i < list1.length; i++) {
if (list1[i] != list2[i]) return false;
}
return true;
}
Then you can check if a similar list is contained in your lists:
void addLista(List<int> ls) {
if (!listas.any((ls2) => listEquals(ls, ls2))) {
listas.add(ls);
}
}

partition list into groups of size-N

what's the idiomatic way to take a list and group it into tuples of size n?
eg: group into 3's with triple
val list = listOf(1,2,3,4)
val partitioned = list.groupsOf(3)
// partitioned[0] = List<Int> 1, 2, 3
// partitioned[1] = List<Int> 4
but preferably something like this
val list = listOf(1,2,3,4)
val newList = mutableListOf()
list.forGroupsOf(3) { triple: Triple<Int?> ->
newList.add( triple )
}
// partitioned[0] = Triple<Int?> 1, 2, 3
// partitioned[1] = Triple<Int?> 4, null, null
NOTE: List.groupsOf and List.forGroupsOf I made up for this example
Kotlin provides a function called chunked(n) which produces a list of lists with n elements each:
val list = listOf(1, 2, 3, 4)
val tuples = list.chunked(2).map { Tuple(it[0], it[1]) }
Or alternatively:
val list = listOf(1, 2, 3, 4)
val tuples = list.chunked(2) { Tuple(it[0], it[1]) }
Keep in mind that this produces lists with max n elements.

How to access an element of list within a list in scala

I want to access elements of a list within one list and check whether the elements are greater than a minimum value.
Example: List[([1,2],0.3), ([1.5,6],0.35), ([4,10],0.25), ([7,15],0.1)]
Let the minimum value: 1
The result should be: List[([1,6],0.65), ([4,10],0.25), ([7,15],0.1)]
As 1.5-1 is less than minimum value 1, it will merge the elements [1,2],0.3) and ([1.5,6],0.35) as [1, 6], 0.65, meaning it will take the 1st element of the inside list and last element of the 2nd element of the outside list and the 2nd element of the outside list will be added (0.3+0.35). This will be done for all elements of the outside list.
The code I tried is written below:
def reduce (d1:List[(Interval, Rational)]): List[(Interval, Rational)] =
{
var z = new ListBuffer[(Interval, Rational)]()
def recurse (list: List[(Interval, Rational)]): Unit = list match {
case List(x, y, _*) if ((y._1_1 - x._1_1) < min_val) =>
val i = x._1_1; y._1_2
val w = x._2 + y._2
z += (i,w)
else
z += x
recurse(list.tail)
case Nil =>
}
z.toList
}
But this is not working. Please help me to fix this.
OK, what you've written really isn't Scala code, and I had to make a few modifications just to get a compilable example, but see if this works for you.
type Interval = (Double,Double)
type Rational = Double
def reduce (lir:List[(Interval, Rational)]): List[(Interval, Rational)] = {
val minVal = 1.0
lir.foldLeft(List.empty[(Interval, Rational)]){
case (a, b) if a.isEmpty => List(b)
case (acc, ((i2a, i2b), r2)) =>
val ((i1a, _), r1) = acc.head
if (i2a - i1a < minVal) ((i1a, i2b), r1 + r2) :: acc.tail
else ((i2a, i2b), r2) :: acc
}.reverse
}
Test case:
reduce(List( ((1.0,2.0),0.3), ((1.5,6.0),0.35), ((4.0,10.0),0.25), ((7.0,15.0),0.1) ))
// result: List[(Interval, Rational)] = List(((1.0,6.0),0.6499999999999999), ((4.0,10.0),0.25), ((7.0,15.0),0.1))

Update the values of a list with their absolute values

Newbie to scala.
I am trying to make this code to work for a few hours now . It is intended to update the List[Int](list of integers) with absolute values of the integers.
Took a long time to figure out that List is immutable, so found that ListBuffer can be the saviour, but eventually in returning it back into the List form is seeing some issue i guess.
def f (arr:List[Int]) : List[Int] =
{
val list = new scala.collection.mutable.ListBuffer[Int]();
val len = arr.length;
for ( i <- 0 to len)
{
if(arr(i) < 0)
{
list.append((-1)*arr(i)) ;
}
else
{
list.append(arr(i));
}
}
return list.toList;
}
which is giving this error:
java.lang.IndexOutOfBoundsException: 12
at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:52)
at scala.collection.immutable.List.apply(List.scala:84)
at Solution$.f(Solution.scala:7)
at Solution$delayedInit$body.apply(Solution.scala:23)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:7...
Not getting what's wrong here.
The best way is to use Scala functions like #senia suggested in comments. For example:
val res = list map math.abs
But if you want to fix your code just replace to with until. You are getting off by one error:
def f (arr:List[Int]) : List[Int] =
{
val list = new scala.collection.mutable.ListBuffer[Int]();
val len = arr.length;
for ( i <- 0 until len)
{
if(arr(i) < 0)
{
list.append((-1)*arr(i)) ;
}
else
{
list.append(arr(i));
}
}
return list.toList;
}
Here is the difference between until and to:
1 to 3
// Range(1, 2, 3)
1 until 3
// Range(1, 2)
You can also remove return, ; and even braces { used with if/else.
Yet another version using a for comprehension that avoids indexing,
def f (arr:List[Int]) : List[Int] =
{
val list = new scala.collection.mutable.ListBuffer[Int]();
for {
a <- arr
sign = if (a < 0) -1 else 1
} list.append(sign * a)
return list.toList;
}
As mentioned above, the return may be omitted.
You can try using case statements for more neat syntax :
def f(arr:List[Int]):List[Int] = {
val list = scala.collection.mutable.ListBuffer[Int]()
arr.foreach{
x =>
x match {
case _ if (x <0) => list+= (x*(-1))
case _ => list +=x
}
}
list.toList
}
Looks like you were trying to solve the challenge from here. Probably you may want to use more functional approach with recursion and immutable List.
def f(arr: List[Int]): List[Int] = arr match {
case Nil => Nil
case x :: rest => java.lang.Math.abs(x) :: f(rest)
}
Beginner friendly: this is how I wrote it
def f(arr: List[Int]) : List[Int] = {
var list = new scala.collection.mutable.ArrayBuffer[Int]();
// var len = arr.length;
for(i <-0 until arr.length) {
list.append( math.abs(arr(i)));
}
return list.toList; }
I haven't done any time complexity analysis but it's the most straightforward for beginners to understand. Also, it passes all the tests on hackerrank
def f (arr: List[Int]) : List[Int] = {
arr.map {
case i if 0 > i => i * -1
case i => i
}
}