Get list of elements that are divisible by 3 or 5 from 1 - 1000

后端 未结 6 610
北海茫月
北海茫月 2021-01-14 12:30

I\'m trying to write a functional approach in scala to get a list of all numbers between 1 & 1000 that are divisible by 3 or 5

Here is what I have so far :

6条回答
  •  不要未来只要你来
    2021-01-14 12:59

    Here's how I would do it with a for expression.

    for( i <- 1 to 1000 if i % 3 == 0 || i % 5 == 0) yield i
    

    This gives:

     scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 6, 9, 10, 12, 15, 18, 20, 21...
    

    Here's another approach filtering on a Range of numbers.

    scala> 1 to 1000
    res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10...
    
    
    scala> res0.filter(x => x % 3 == 0 || x % 5 == 0)
    res1: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 6, 9, 10, 12, 15, 18, 20, 21...
    

    If you really want a List on the return value use toList. e.g. res0.toList.

提交回复
热议问题