Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Ivelinka avatar Ivelinka 24 Точки

проблем с 02. Treasure Hunt от 06. Programming Fundamentals Mid Exam Retake

Здравейте, получавам 10/100 и не знам как да оправя грешките, някой може ли да ми помогне ?

Благодаря :)

задача: https://judge.softuni.org/Contests/Practice/Index/1773#1

код: 

function solve(input){
let state = input.shift().split("|")
let actions = {
    "Loot": loot, "Drop": drop, "Steal": steal
}
function loot(items){
items.forEach(x => {
if(!state.includes(x)) state.unshift(x)
})
}
function drop(index){
let item = state[index]
if(state[index] !== undefined)
state.splice(item, 1)
state.push(item)
}
function steal(count){
let items = state.splice(-count)
console.log(items.join(", "))
}
input.forEach(x => {
    if(x !== "Yohoho!"){
    const [a, b] = x.split(" ").map(x => (isNaN(x) ? x : Number(x)))
    try{
      actions[a](b)
    }catch(e){
      
    }
  }
})
let avg = state.reduce((a, v) => a + v.length, 0) / state.length

state.length === 0 ? console.log("Failed treasure hunt.")
: console.log(`Average treasure gain: ${avg.toFixed(2)} pirate credits.`)
}

Тагове:
0
JavaScript Fundamentals
Axiomatik avatar Axiomatik 2422 Точки

Demo code, ;-) =>

function treasureHunt(arr) {
    let initialLoot = arr.shift().split("|");
    
    for (const line of arr) {
        let [command, ...currentCommandArray] = line.split(" ");

        switch (command) {
            case "Loot":
                for (let el of currentCommandArray) {
                    if (!initialLoot.includes(el)) {
                        initialLoot.unshift(el);
                    }
                }

                break;
            case "Drop":
                let startingIndex = Number(currentCommandArray[0]);

                if (startingIndex >= 0 && startingIndex < initialLoot.length) {
                    let oldLoot = initialLoot.splice(startingIndex, 1)
                    initialLoot.push(...oldLoot);
                }

                break;
            case "Steal":
                let index = Number(currentCommandArray);
                let stolenTreasure = initialLoot.slice(-index);
                initialLoot.splice(-index);
                console.log(stolenTreasure.join(', '));

                break;
        }
    }

    let itemSum = initialLoot.reduce((sum, initialTresure) => {
        return sum + initialTresure.length;
    }, 0) / initialLoot.length;

    if (initialLoot.length > 0) {
        console.log(`Average treasure gain: ${itemSum.toFixed(2)} pirate credits.`);
    } else {
        console.log(`Failed treasure hunt.`);
    }
}

 

1
Ivelinka avatar Ivelinka 24 Точки

I saw the mistake and now I have 100/100

Thanks a lot !

0
16/05/2023 23:39:06
Axiomatik avatar Axiomatik 2422 Точки

You've got the solution in front of you, no one will help you during the exams and the exams will get more and more difficult with each further level (dito when you land a job at a software company - no senior will be around to help you out) !!!

 

JS discussions =>

https://softuni.bg/forum/41998/02-treasure-hunt

Java discussions =>

https://softuni.bg/forum/41272/treasure-hunt-ot-mid-exam-retake-6-august-2019

https://softuni.bg/forum/42616/10-treasure-hunt-java

https://softuni.bg/forum/42291/treasure-hunt-70-100

frown

 

0
13/05/2023 20:22:47
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.