编写一个函数,该函数接受一个正整数列表,并返回一个整数列表,该列表近似于相同位置的相应整数的总数百分比。
返回列表中的所有整数必须精确地加到100。您可以假设传入的整数之和大于0。您希望如何舍入或截断小数取决于您,只要以百分比返回的任何单个整数在任何方向上都不超过1。
p([1,0,2]) -> [33,0,67] or [34,0,66]
p([1000,1000]) -> [50,50] or [49,51] or [51,49]
p([1,1,2,4]) -> [12,12,25,51] or [13,12,25,50] or [12,13,25,50] or [13,13,25,49] or [13,12,26,49] or [12,13,26,49] or [12,12,26,50]
p([0,0,0,5,0]) -> [0,0,0,100,0]这是密码-高尔夫,所以以字节为单位的最短代码将获胜!
发布于 2015-10-08 02:51:14
(s=Floor[100#/Tr@#];s[[;;100-Tr@s]]++;s)&发布于 2015-10-09 16:52:26
a=>(e=0,a.map(c=>((e+=(f=c/a.reduce((c,d)=>c+d)*100)%1),f+(e>.999?(e--,1):0)|0)))“必须等于100”条件(而不是舍入和加起来)使我的代码翻了一番(从44到81)。诀窍是为十进制值添加一个罐子,当它达到1时,从它本身取1并将它添加到当前的数字中。问题是浮点数,这意味着类似于1,1,1的东西留下了.9999999999999858的剩余部分。因此,我将支票改为大于.999,并决定称之为足够精确。
发布于 2018-05-18 18:04:00
((([]){[{}]({}<>)<>([])}{})[()])<>([]){{}<>([{}()]({}<([()])>)<>(((((({})({})({})){}){}){}{}){}){}(<()>))<>{(({}<({}())>)){({}[()])<>}{}}{}([])}<>{}{}从结束开始并向后工作,此代码确保在每个步骤中,到目前为止输出数字的总和等于所遇到的、四舍五入的总百分比。
(
# Compute and push sum of numbers
(([]){[{}]({}<>)<>([])}{})
# And push sum-1 above it (simulating a zero result from the mod function)
[()])
<>
# While elements remain
([]){{}
# Finish computation of modulo from previous step
<>([{}()]({}
# Push -1 below sum (initial value of quotient in divmod)
<([()])>
# Add to 100*current number, and push zero below it
)<>(((((({})({})({})){}){}){}{}){}){}(<()>))
# Compute divmod
<>{(({}<({}())>)){({}[()])<>}{}}{}
([])}
# Move to result stack and remove values left over from mod
<>{}{}https://codegolf.stackexchange.com/questions/59922
复制相似问题