Loading...

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

inaivanova1990 avatar inaivanova1990 33 Точки

5. Tseam Account , Arrays - More Exercise

Някой може ли да помогне с тази задача, защото съвсем се оплетох...

https://pastebin.com/MLSLiUQc

1.Tseam Account

As a gamer, Peter has Tseam Account. He loves to buy new games. You are given Peter's account with all of his games-> strings, separated by space. Until you receive "Play!" you will be receiving commands which Peter does with his account.`

You may receive the following commands:

  • Install {game}
  • Uninstall {game}
  • Update {game}
  • Expansion {game}-{expansion}

If you receive Install command, you should add the game at last position in the account, but only if it isn't installed already.

If you receive Uninstall command, delete the game if it exists.

If you receive Update command, you should update the game if it exists and place it on last position.

If you receive Expansion command, you should check if the game exists and insert after it the expansion in the following format: "{game}:{expansion}";

Input

  • On the first input line you will receive Peter`s account - sequence of game names, separated by space.
  • Until you receive "Play!" you will be receiving commands.

Output

  • As output you must print Peter`s Tseam account.

Constraints

  • The command will always be valid.
  • The game and expansion will be strings and will contain any character, except '-'.
  • Allowed working time / memory: 100ms / 16MB.

Examples

Input

Output

Comments

['CS WoW Diablo',

'Install LoL',

'Uninstall WoW',

'Update Diablo',

'Expansion CS-Go',

'Play!']

CS CS:Go LoL Diablo

We receive the account => CS, WoW, Diablo

We Install LoL => CS, WoW, Diablo, LoL

Uninstall WoW => CS, Diablo, LoL

Update Diablo => CS, LoL, Diablo

We add expansion => CS, CS:Go, LoL, Diablo

We print the account.

['CS WoW Diablo',

'Uninstall XCOM',

'Update PeshoGame',

'Update WoW',

'Expansion Civ-V',

'Play!']

CS Diablo WoW

 

Multidimensional Arrays

We will mainly work with 2-dimensional arrays. The concept is as simple as working with a simple 1-dimensional array. It is just an array of arrays.

Тагове:
0
Fundamentals Module
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

;-)

Super-important to avoid combination of while and nested for-loops if not required, as makes the code more complicated than needed to be. Check out in the forum how other collegues are building up their solutions.

function solve(arr) {
    let account = arr.shift().split(' ');
    // let firstCurrentCommand = arr[0];
    // firstCurrentCommand = firstCurrentCommand.split(' ');
    // let currentCommand = arr.shift();
    // let newArr = [];
    // newArr.push(firstCurrentCommand);

    // while (currentCommand !== "Play!") {
    while (true) {
        // currentCommand = currentCommand.split(" ");
        let [command, game] = arr.shift().split(' ');

        if (command === 'Play!') {
            break;
        }
        // for (let i = 0; i < arr.length; i++) {
        // for (let j = 0; j < firstCurrentCommand.length; j++) {

        // if (currentCommand[i] === "Install") {
        if (command === "Install") {
            if (!account.includes(game)) {
                account.push(game);
            }
            // break;
        }

        // if (currentCommand[i] === "Uninstall") {
        else if (command === "Uninstall") {
            // if (currentCommand[i + 1] === firstCurrentCommand[j]) {
            if (account.includes(game)) {
                let gameIndex = account.indexOf(game);
                account.splice(gameIndex, 1);
                // firstCurrentCommand.splice(j, 1);
                // break;
            }
        }
        // if (currentCommand[i] === "Update") {
        else if (command === "Update") {
            // if (currentCommand[i + 1] === firstCurrentCommand[j]) {
            if (account.includes(game)) {
                let gameIndex = account.indexOf(game);
                account.splice(gameIndex, 1);
                account.push(game);
                // newArr.push(firstCurrentCommand[j]);
                // firstCurrentCommand.splice(j, 1);
                // break;
            }
        }
        // if (currentCommand[i] === "Expansion") {
        else if (command === "Expansion") {
            // firstCurrentCommand.push(currentCommand[i + 1].split('-').join(':'));
            // break;
            let originalGame = game.split('-')[0];
            if (account.includes(originalGame)) {
                let expansionGame = game.split('-')[0] + ':' + game.split('-')[1];
                let gameIndex = account.indexOf(originalGame);
                account.splice(gameIndex + 1, 0, expansionGame)
            }
        }
        // }

        // }
        // currentCommand = arr.shift();

    }
    console.log(account.join(' '));

}

Browser History (this the next step you should be going for in your solutions):

function solve(object, stringArray) {
    let newObj = {
        'Browser Name': object['Browser Name'],
        'Open Tabs': [...object['Open Tabs']],
        'Recently Closed': [...object['Recently Closed']],
        'Browser Logs': [...object['Browser Logs']],
    };

    for (let command of stringArray) {
        let data = command.split(' ');
        let currentCommand = data[0];
        let site = data[1];

        if (currentCommand === 'Open') {
            openTab(object, site);
        } else if (currentCommand === 'Close') {
            close(object, site);
        } else if (command === 'Clear History and Cache') {
            deleteObject(object);
        }
    }

    console.log(object['Browser Name']);
    console.log(`Open Tabs: ${object['Open Tabs'].join(', ')}`);
    console.log(`Recently Closed: ${object['Recently Closed'].join(', ')}`);
    console.log(`Browser Logs: ${object['Browser Logs'].join(', ')}`);

    function openTab(obj, site) {
        obj['Open Tabs'].push(site);
        browserLogs(object, 'Open ' + site);
    }

    function browserLogs(obj, command) {
        obj['Browser Logs'].push(command)
    }

    function close(obj, site, secondObj) {
        if (obj['Open Tabs'].includes(site)) {
            let index = obj['Open Tabs'].findIndex(x => x === site);
            let result = obj['Open Tabs'].splice(index, 1);
            obj['Recently Closed'].push(result[0]);
            browserLogs(object, 'Close ' + site);
        }
    }

    function deleteObject(obj) {
        obj['Open Tabs'] = [];
        obj['Recently Closed'] = [];
        obj['Browser Logs'] = [];
    }
}

solve({
    "Browser Name": "Google Chrome",
    "Open Tabs": ["Facebook", "YouTube", "Google Translate"],
    "Recently Closed": ["Yahoo", "Gmail"],
    "Browser Logs": ["Open YouTube", "Open Yahoo", "Open Google Translate", "Close Yahoo", "Open Gmail", "Close Gmail", "Open Facebook"]
},

    ["Close Facebook", "Open StackOverFlow", "Open Google"]);

solve({
    "Browser Name": "Mozilla Firefox",
    "Open Tabs": ["YouTube"],
    "Recently Closed": ["Gmail", "Dropbox"],
    "Browser Logs": ["Open Gmail", "Close Gmail", "Open Dropbox", "Open YouTube", "Close Dropbox"]
},
    ["Open Wikipedia", "Clear History and Cache", "Open Twitter"]);

 

0
21/03/2021 10:21:57
inaivanova1990 avatar inaivanova1990 33 Точки

Благодаря за помощта и за насоките, за пореден път! Знам, че колеги вече са коментирали тази задача, но ме интересуваше дали и моят вариант някак може да се дооправи, и да проработи

1
inaivanova1990 avatar inaivanova1990 33 Точки

Виждам, че задачата може да се реши много по-кратко и ми е много полезно твоето решение да разбера този тип задачи!

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