文档章节

scala N99(18-28)

我是菜鸟我骄傲
 我是菜鸟我骄傲
发布于 2017/07/09 17:53
字数 1154
阅读 5
收藏 0
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
}


}

© 著作权归作者所有

下一篇: ScalaN99(1-17)
我是菜鸟我骄傲
粉丝 13
博文 244
码字总数 154930
作品 0
西安
架构师
私信 提问
Scala 函数和方法的定义与使用

摘要: 函数是一组一起执行一个任务的语句。 您可以把代码划分到不同的函数中。如何划分代码到不同的函数中是由您来决定的,但在逻辑上,划分通常是根据每个函数执行一个特定的任务来进行的。...

技术小牛人
2017/11/20
0
0
Scala 9*9乘法表轻松实现

打开Scala命令行 输入以下代码: 打印结果: 倒序乘法表实现

李茂冉
2016/07/25
41
0
在idea中访问spark集群报错

通过spark-submit或者idea中提交jar包报错 问题原因 服务器上版本号和本地版本号不对应,导致进行序列化的UID不一致: 解决方法 如果是通过submit提交的程序报错,则是本地编译spark程序的sca...

freeli
2018/09/29
35
0
maven项目报错,怎么解决??scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found.

target\classes at 1502177323523 [ERROR] error: error while loading , Error accessing C:\Users\Administrator\.m2\repository\org\apache\spark\spark-catalyst_2.11\2.1.0\spark-catal......

天池番薯
2017/08/08
2.5K
1
Spark DataFrame API

过滤: 注意这些API最后都转换为了 1. where filter: 这里我们推荐使用filter或者where(因为filter不能用 and 和 or) 的第一个API,因为少调了一次解析器,且代码更清晰,不容易出错. 看 where ...

xd03122049
2018/03/30
33
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周四乱弹 —— 当你简历注水但还是找到了工作

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 @花间小酌 :#今日歌曲推荐# 分享成龙的单曲《男儿当自强》。 《男儿当自强》- 成龙 手机党少年们想听歌,请使劲儿戳(这里) @hxg2016 :刚在...

小小编辑
今天
3.1K
22
靠写代码赚钱的一些门路

作者 @mezod 译者 @josephchang10 如今,通过自己的代码去赚钱变得越来越简单,不过对很多人来说依然还是很难,因为他们不知道有哪些门路。 今天给大家分享一个精彩的 GitHub 库,这个库整理...

高级农民工
昨天
7
0
用好项目管理工具,人人都可以成为项目经理

现在市面上的项目管理工具越来越多了,但是大多数都是一些协同工具或轻量项目管理工具。如果是多团队、跨部门使用或者企业级的项目管理,从管理思想到工具运用,需要适应企业的业务流程体系,...

cs平台
昨天
13
0
只需一步,在Spring Boot中统一Restful API返回值格式与统一处理异常

统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生。 比较通用的返回值格式如下:...

晓月寒丶
昨天
70
0
区块链应用到供应链上的好处和实际案例

区块链可以解决供应链中的很多问题,例如记录以及追踪产品。那么使用区块链应用到各产品供应链上到底有什么好处?猎头悬赏平台解优人才网小编给大家做个简单的分享: 使用区块链的最突出的优...

猎头悬赏平台
昨天
32
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部