CodeWars符号化問題2021/01/29-Sums of Parts
[質問]
Let us consider this example (array written in general format):
ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []
The corresponding sums are (put together in a list):
Other Examples:
ls = [1, 2, 3, 4, 5, 6]
parts_sums(ls) -> [21, 20, 18, 15, 11, 6, 0]
ls = [744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]
parts_sums(ls) -> [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0]
Notes Some lists can be long. Please ask before translating: some translations are already written and published when/if the kata is approved. (要約)所与の配列の合計から最初の要素から最後の要素まで、車の積算値を配列に蓄積します.
[回答]
次の2つのロジックがタイムアウトし、テストケースには1万以上の要素があります.
Let us consider this example (array written in general format):
ls = [0, 1, 3, 6, 10]
Its following parts:ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []
The corresponding sums are (put together in a list):
[20, 20, 19, 16, 10, 0]
The function parts_sums (or its variants in other languages) will take as parameter a list ls and return a list of the sums of its parts as defined above.Other Examples:
ls = [1, 2, 3, 4, 5, 6]
parts_sums(ls) -> [21, 20, 18, 15, 11, 6, 0]
ls = [744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]
parts_sums(ls) -> [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0]
Notes
[回答]
function partsSums(ls) {
let sumNum = ls.reduce((acc, num) => acc += num, 0);
const answer = [sumNum];
const length = ls.length;
for(let i = 0; i < length; i++) {
sumNum -= ls[i];
answer.push(sumNum);
}
return answer;
}
配列の総和を求め,最初の要素として入れ,繰り返し文から配列中push
に前に移動する.次の2つのロジックがタイムアウトし、テストケースには1万以上の要素があります.
pop
がタイムアウトしたのは理由があると思います.function partsSums(ls) {
const answer = [0];
while(ls.length) {
const sumNum = answer[0] + ls.pop();
answer.unshift(sumNum);
}
return answer;
}
function partsSums(ls) {
const answer = [0];
const length = ls.length - 1;
for(let i = length; i >= 0; i--) {
const sumNum = answer[0] + ls.pop();
answer.unshift(sumNum);
}
return answer;
}
Reference
この問題について(CodeWars符号化問題2021/01/29-Sums of Parts), 我々は、より多くの情報をここで見つけました https://velog.io/@hemtory/CodeWars20210129テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol