如何在Scala中使用foldLeft返回列表中的每N个偶数?
对于大学项目,我必须实现一个名为TakenTheen的函数,该函数借助foldLeft查找列表中的第n个偶数。例如:如何在Scala中使用foldLeft返回列表中的每N个偶数?,scala,list,data-structures,primes,foldleft,Scala,List,Data Structures,Primes,Foldleft,对于大学项目,我必须实现一个名为TakenTheen的函数,该函数借助foldLeft查找列表中的第n个偶数。例如: takeNthEven(单链接列表(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15,18,5,3),3) 应返回:singlelylinkedintlist(4,10,18) 我迄今为止的努力: def takeNthEven(input: IntList, n: Int): IntList = { var temp = SinglyLinked
takeNthEven(单链接列表(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15,18,5,3),3)
应返回:singlelylinkedintlist(4,10,18)
我迄今为止的努力:
def takeNthEven(input: IntList, n: Int): IntList = {
var temp = SinglyLinkedIntList()
input.foldLeft(0 -> 0) {
case(acc,n) => if (acc == 2 || !(2 to (acc-1)).exists(x => i % x == 0)) temp.append(acc)
}._n
}
但不幸的是,这甚至没有编译。我不知道如何继续使用这个算法,有人能帮我解决这个问题吗?我是函数式编程新手,不知道如何进行这项工作,类似这样的工作应该可以:
val (_, result) = input.foldLeft(0 -> List.empty[Int]) {
case ((count, acc), elem) =>
if ((elem % 2) == 0) {
val newCount = count + 1
if (newCount == n) {
0 -> (elem :: acc)
} else {
newCount -> acc
}
} else {
count -> acc
}
}
result.reverse
像这样的方法应该会奏效:
val (_, result) = input.foldLeft(0 -> List.empty[Int]) {
case ((count, acc), elem) =>
if ((elem % 2) == 0) {
val newCount = count + 1
if (newCount == n) {
0 -> (elem :: acc)
} else {
newCount -> acc
}
} else {
count -> acc
}
}
result.reverse
这是我的看法。您可能需要根据
IntList
的组成方式进行调整
type IntList = List[Int]
def takeNthEven(input: IntList, n: Int): IntList = input.foldLeft(List.empty[Int]->1){
case ((acc,cnt),elem) if elem%2 < 1 => if (cnt%n < 1) (elem::acc, cnt+1)
else (acc, cnt+1)
case (skip,_) => skip
}._1.reverse
type IntList=List[Int]
def takeNthEven(输入:IntList,n:Int):IntList=input.foldLeft(List.empty[Int]->1){
如果元素%2<1=>if(cnt%n<1)(元素::acc,cnt+1),则案例((acc,cnt),元素)
其他(acc、cnt+1)
案例(跳过,)=>跳过
}1.相反
以下是我的看法。您可能需要根据IntList
的组成方式进行调整
type IntList = List[Int]
def takeNthEven(input: IntList, n: Int): IntList = input.foldLeft(List.empty[Int]->1){
case ((acc,cnt),elem) if elem%2 < 1 => if (cnt%n < 1) (elem::acc, cnt+1)
else (acc, cnt+1)
case (skip,_) => skip
}._1.reverse
type IntList=List[Int]
def takeNthEven(输入:IntList,n:Int):IntList=input.foldLeft(List.empty[Int]->1){
如果元素%2<1=>if(cnt%n<1)(元素::acc,cnt+1),则案例((acc,cnt),元素)
其他(acc、cnt+1)
案例(跳过,)=>跳过
}1.相反
另一个折页
val n = 3
val p = List(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,18,5,3)
p.foldLeft( (List.empty[Int],1) ) {
case((x,y),z) => {
val t = if(y%n==0 && z%2==0 ) z::x else x
(t,if(z%2==0) y+1 else y)
}
}._1.reverse
// List[Int] = List(4, 10, 18)
另一个折页
val n = 3
val p = List(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,18,5,3)
p.foldLeft( (List.empty[Int],1) ) {
case((x,y),z) => {
val t = if(y%n==0 && z%2==0 ) z::x else x
(t,if(z%2==0) y+1 else y)
}
}._1.reverse
// List[Int] = List(4, 10, 18)
你能提供更多的输入和预期输出数据,并多解释一点你想要实现的目标吗?你能提供更多的输入和预期输出数据,并多解释一点你想要实现的目标吗?