scala N99(18-28)

本文提供了一系列Scala编程语言中列表操作的实用示例,包括切片提取、旋转、元素插入与移除等高级功能。通过具体代码展示了如何实现列表的随机选择、组合生成以及分组等功能。
package com.learn

/**
* Created by zhuqing on 2017/7/7.
*/
object LearnScala02 {
def main(args: Array[String]): Unit = {
println(slice(3, 7, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
println(rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
println(rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)))
println(removeAt(1, List('a, 'b, 'c, 'd)))
println(insertAt('new, 2, List('a, 'b, 'c, 'd)))
println(range(4, 9))
println("P23 (**) Extract a given number of randomly selected elements from a list.")
println(randomSelect(3, List('a, 'b, 'c, 'd, 'f, 'g, 'h)))
println(randomSelect(3, List('a, 'b, 'c, 'd, 'f, 'g, 'h)))
println(randomSelect(3, List('a, 'b, 'c, 'd, 'f, 'g, 'h)))
println("=========================================================================")


println(lotto(6, 49))

println(randomPermute(List('a, 'b, 'c, 'd, 'e, 'f)))

println(combinations(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g)))

println(group3(List("Aldo", "Beat", "Carla", "David", "Evi", "Flip", "Gary", "Hugo", "Ida")))

println(group(List(2, 3, 4), List("Aldo", "Beat", "Carla", "David", "Evi", "Flip", "Gary", "Hugo", "Ida")))
println(group(List(2, 2, 5), List("Aldo", "Beat", "Carla", "David", "Evi", "Flip", "Gary", "Hugo", "Ida")))

println(lsort(List(List('a, 'b, 'c), List('d, 'e), List('f, 'g, 'h), List('d, 'e), List('i, 'j, 'k, 'l), List('m, 'n), List('o))))

println(lsortFreq(List(List('a, 'b, 'c), List('d, 'e), List('f, 'g, 'h), List('d, 'e), List('i, 'j, 'k, 'l), List('m, 'n), List('o))))

}

/**
* P18 (**) Extract a slice from a list.
*/
def slice(start: Int, end: Int, list: List[Symbol]): List[Symbol] = {
list.take(end).drop(start)
}

/**
* P19 (**) Rotate a list N places to the left.
*
* @param nth
* @param list
*/
def rotate(nth: Int, list: List[Symbol]) = {
if (nth > 0) {
list.drop(nth) ::: list.take(nth)
} else if (nth < 0) {
list.takeRight(-nth) ::: list.dropRight(-nth)
} else {
list
}
}

/**
* P20 (*) Remove the Kth element from a list.
*
* @param nth
* @param list
* @return
*/
def removeAt(nth: Int, list: List[Symbol]): (List[Symbol], Symbol) = {
(list.take(nth) ::: list.drop(nth + 1), list(nth))
}

/**
* P21 (*) Insert an element at a given position into a list.
*
* @param nth
* @param list
* @return
*/
def insertAt(sym: Symbol, nth: Int, list: List[Symbol]): List[Symbol] = {
(list.take(nth) :+ sym) ::: list.drop(nth)
}

/**
* P22 (*) Create a list containing all integers within a given range.
*
* @param start
* @param end
* @return
*/
def range(start: Int, end: Int): List[Int] = {
(start to end).toList
}

/**
* P23 (**) Extract a given number of randomly selected elements from a list.
*
* @param size
* @param list
* @return
*/
def randomSelect(size: Int, list: List[Symbol]): List[Symbol] = {
var res = List[Symbol]()
var temp = list
for (i <- (0 until size)) {
val rindex = Math.random() * temp.length
res = res :+ temp(rindex.toInt)
temp = remove(rindex.toInt, temp)
}

res
}

def remove(nth: Int, list: List[Symbol]): List[Symbol] = {
list.take(nth) ::: list.drop(nth + 1)
}

/**
* P24 (*) Lotto: Draw N different random numbers from the set 1..M.
*
* @param size
* @param max
* @return
*/
def lotto(size: Int, max: Int): List[Int] = {
var res = List[Int]()
var i = 0;
while (i < size) {
var random = Math.random() * max
if (!res.contains(random.toInt)) {
res = res :+ random.toInt
i = i + 1
}
}

res
}

/**
* P25 (*) Generate a random permutation of the elements of a list.
*
* @param list
* @return
*/
def randomPermute(list: List[Symbol]): List[Symbol] = {
var res = List[Symbol]()
var temp = list

for (i <- (0 until list.size)) {
val index = Math.random() * temp.size
res = res :+ temp(index.toInt)
temp = remove(index.toInt, temp)

}
res

}

/**
* P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.
* In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficient). For pure mathematicians, this result may be great. But we want to really generate all the possibilities.
*
* @param size
* @param list
* @return
*/
def combinations[T](size: Int, list: List[T]): List[List[T]] = {
var temp = List[List[T]]()
var res = List[List[T]]()
for (i <- (0 until list.size - size + 1)) {
temp = temp :+ List[T](list(i))
}


for (i <- (0 until size - 1)) {
temp = combinations(temp, list)
}

temp.toStream.filter((_.size == size)).toList

}

def combinations[T](seed: List[List[T]], list: List[T]): List[List[T]] = {
var res = List[List[T]]()
for (i <- (0 until seed.size)) {
val itemOfTemp = seed(i)
val start = list.indexOf(itemOfTemp(itemOfTemp.size - 1)) + 1
for (j <- (start until list.size)) {
res = res :+ (itemOfTemp :+ list(j))
}
}
res

}

/**
* P27 (**) Group the elements of a set into disjoint subsets.
* a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities.
*
* @param list
* @return
*/
def group3(list: List[String]): List[List[List[String]]] = {
var res = List[List[List[String]]]()

var temp = this.initGroup(2, list)
for (item <- temp) {
val t = remove(list, item)
val tem = this.combinations(3, t)
for (i <- tem) {
res = res :+ (item :+ i)
}
}

temp = res;
res = List[List[List[String]]]()
for (item <- temp) {
val t = remove(list, item)
val tem = this.combinations(4, t)
for (i <- tem) {
res = res :+ (item :+ i)
}
}
res


}

def remove[T](resource: List[T], remove: List[List[T]]): List[T] = {
resource.filter(item => {
var res = true
for (re <- remove if re.contains(item)) {
res = false
}
res
}).toList
}

/**
* P27 (**) Group the elements of a set into disjoint subsets.
*
* @param sizes
* @param list
* @return
*/
def group(sizes: List[Int], list: List[String]): List[List[List[String]]] = {
var temp = initGroup(sizes.head, list)
var res = List[List[List[String]]]()


for (size <- sizes.drop(1)) {
res = List[List[List[String]]]()
for (item <- temp) {
val leftList = remove(list, item)
val tem = this.combinations(size, leftList)
for (sub <- tem) {
res = res :+ (item :+ sub)
}
temp = res
}

}

res
}


def initGroup[T](size: Int, list: List[T]): List[List[List[T]]] = {
var res = List[List[List[T]]]()
val grouped = this.combinations(size, list)
for (item <- grouped) {
res = res :+ List[List[T]](item)
}
res
}

/**
* P28 (**) Sorting a list of lists according to length of sublists.
* a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of the list according to their length. E.g. short lists first, longer lists later, or vice versa.
*
* @param list
* @return
*/
def lsort[T](list: List[List[T]]): List[List[T]] = {
list.sortWith(_.length < _.length)
}

/**
* P28 (**) Sorting a list of lists according to length of sublists.
* b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements according to their length frequency; i.e. in the default, sorting is done ascendingly, lists with rare lengths are placed, others with a more frequent length come later.
*
* @param list
* @tparam T
* @return
*/
def lsortFreq[T](list: List[List[T]]): List[List[T]] = {
var temp = list.map(item => {
(item.length, item)
})

var countMap = scala.collection.mutable.Map[Int, Int]()
for (item <- temp) {
countMap(item._1) = countMap.getOrElse(item._1, 0) + 1
}

val sortLength = countMap.toList.sortWith(_._2 < _._2)
var res = List[List[T]]()
for (item <- sortLength) {
res = res ::: list.filter(_.length == item._1)
}
res
}


}

转载于:https://my.oschina.net/u/587323/blog/1239937

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值