某公司笔试面试题

面试题描述:
这里写图片描述

实现代码如下:

package Test

import org.apache.spark.{SparkConf, SparkContext}

import scala.collection.mutable.ArrayBuffer

/**
  * Created by TG.
  */
/** 测试数据如下:
userA locationA 8 60
userA locationA 9 60
userB locationB 8 60
userA locationA 11 60
userA locationA 10 60
userA locationA 3 60
userA locationA 4 60
userA locationA 5 60
userA locationA 13 10
userB locationB 10 30
userB locationB 11 20
userB locationB 13 20
userB locationB 15 10
userB locationB 9 30
userA locationB 3 60
userA locationB 4 60
userA locationB 5 60
userA locationB 7 60
  */
object TestData {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local").setAppName("TestData")
    val sc = new SparkContext(conf)
    val lines = sc.textFile("C:\\datas.txt")
    lines.map(x => {
      val info = x.split(" ")
      val user = info(0)
      val location = info(1)
      val times = info(2).toInt
      val seconds = info(3).toInt
      val userandlocation = user + "-" + location
      (userandlocation, (times, seconds))
    }).groupByKey()
      .map(x => {
        val userandlocation = x._1
        val infos = x._2.toArray.sortWith(_._1 > _._1)
        var temp = infos(0)
        val buffer = ArrayBuffer[Tuple2[Int, Int]]()
        var sum = temp._2
        //12  10 9 8  6  5 4 3 2
        //12  10 9 8  6 5 4 3  1
        for (i <- 1 until infos.length) {
          if (temp._1 - infos(i)._1 == 1) {
            sum = sum + infos(i)._2
            temp = infos(i)
            if (i == infos.length - 1) { //12  10 9 8  6  5 4 3 2
              buffer += Tuple2(infos(i)._1, sum)
            }
          } else {
            buffer += Tuple2(infos(i - 1)._1, sum)
            temp = infos(i)
            sum = temp._2
            if (i == infos.length - 1) { //12  10 9 8  6 5 4 3  1
              buffer += Tuple2(infos(i)._1, sum)
            }
          }
        }
        if (infos.length == 1) {
          (userandlocation, infos.toBuffer)
        } else {
          (userandlocation, buffer)
        }
      }).foreach(x => {
      val userandlocation = x._1
      println(userandlocation)
      println(x._2.toBuffer)
      println("=====================================")
    })

    sc.stop()
  }
}

运行结果:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值