Hive 刷题——奖金瓜分问题

题目描述

在活动大促中,有玩游戏瓜分奖金环节。现有奖金池为3000元,代表奖金池中的初始额度。用户的分数信息如下:
uid,score
1001,45
1002,40
1003,35
1004,30
1005,25
表中的数据代表每一个用户和其对应的得分,user_id和score都不会有重复值。瓜分奖金的规则如下:按照score从高到低依次瓜分,每个人都能分走当前奖金池里面剩余奖金的一半,当奖金池里面剩余的奖金少于500时(不含),则停止瓜分奖金。
解题思路:这是拼多多的一个面试题,需要先进行一点数学层面的分析,把整个瓜分逻辑捋清楚之后不难。这里给出一种思考逻辑:假设奖金池的初始总奖金为n,那么第一名分到的奖金为n/2,第二名分到奖金n/4,第三名分到的奖金为n/8,依次类推第x名分到的奖金为n/2^x,然后计算即可。

数据准备

CREATE TABLE temp_score_1120
(
    uid   int,
    score int
) stored as orc tblproperties ('orc.compress' = 'snappy');
insert into temp_score_1120
select 1001, 45
union all
select 1002, 40
union all
select 1003, 35
union all
select 1004, 30
union all
select 1005, 25;

参考实现

select uid
     , score
     , 1 / power(2, rn) * 3000 as prize
from (select uid
           , score
           , row_number() over (order by score desc) as rn
      from temp_score_1120) t1
where 1 / power(2, rn) * 3000 >= 250;

 

 

posted @ 2024-03-23 22:41  晓枫的春天  阅读(25)  评论(0编辑  收藏  举报