scala习题(三)

scala习题训练之yield


package com.zyc.scala.test

import scala._
import scala.collection.immutable.SortedMap
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

/**
* Created with IntelliJ IDEA.
* Author: zyc2913@163.com
* Date: 2020/9/22 16:50
* Version: 1.0
* Description: scala中for循环的yield用法
*/
object Test3 {
  def main(args: Array[String]): Unit = {
    /**
     * 1、编写一段代码,将a设置为一个n个随机整数的数组,要求随机数介于0和n之间。
     */
    /**
     * for {子句} yield {变量或表达式}
     *Scala中for循环中的 yield可以当做一个看不见的临时值存储区域,每次循环结果保存在该区域中,循环结束后将返回一个集合。
     * 返回的集合和传入的集合一样(也就是你传入Array  给你返回Array,如果被循环的是 Map,返回的就是  Map,被循环的是 List,返回的就是 List,以此类推。)
     *
     */
    def makeArr(n:Int):Array[Int]={
      //定义一个数组
      val a = new Array[Int](n)
      //定义一个随机数
      val random = new Random()
      for (i <- a) yield random.nextInt(n)
    }
    //调用函数,遍历数组并打印到控制台
    makeArr(10).foreach(println)  //随机输出0到10之间的10个数:7 3 7 5 0 0 6 2 6 7

    /**
     * 2. 编写一个循环,将整数数组中相邻的元素置换。
     * 比如Array(1, 2, 3, 4, 5)置换后为Array(2, 1, 4, 3, 5)
     */
      def revert(arr:Array[Int]) = {

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值