Loading...

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

MartinBG avatar MartinBG 4803 Точки
Best Answer

Грешката е, че проверявате дали стойностите в масива, сочени от двата индекса са еднакви, преди да сте проверили дали индексите не са еднакви.

Разменете последователността им и задaчата ще мине с 100/100:

if (typeof sequence[indexOne] === "undefined" || //...
// ...
else if (sequence[indexOne] === sequence[indexTwo])
// ...
...

 

1
petarvanov123 avatar petarvanov123 8 Точки

Благодаря!

2
operator46 avatar operator46 3 Точки

Здравейте Мартин,

Имам подобен проблем, 85/100 бия си главата от доста време с тази задача. Би ли погледнал.

Благодаря предварително!

https://pastebin.com/yFq0Ukd8

 

0
26/05/2023 19:45:55
Axiomatik avatar Axiomatik 2422 Точки

Haven't tested it, but I've got a feeling that your splicing operation inside of your forEach does not consider the mutated array after the first element has been removed from the array. After eliminating the first element establish the index of the second element on the mutated array.

                const sortedIndices = [index1, index2].sort((a, b) => b - a);
                sortedIndices.forEach((index) => {
                    sequence.splice(index, 1);
                });

Plus in your checkValidIndex, should it not be =>

arr[0] >= seq.length || arr[1] >= seq.length || etc...

 

Demo code

function solve(input) {
    const numbers = input
        .shift()
        .trim()
        .split(' ');

    let moves = 0;

    while (numbers.length > 1 && input[0].toLowerCase() !== 'end') {
        let [index1, index2] = input
            .shift()
            .split(' ');
        index1 = Number(index1);
        index2 = Number(index2);

        moves++;

        if (index1 < 0
            || index1 >= numbers.length
            || index1 === index2
            || index2 < 0
            || index2 >= numbers.length) {
            const index = Math.trunc(numbers.length / 2);
            const symbol = '-' + moves + 'a';
            numbers.splice(index, 0, symbol, symbol);
            console.log('Invalid input! Adding additional elements to the board')
        }
        else {
            const num1 = numbers[index1];
            const num2 = numbers[index2];
            if (num1 === num2) {
                numbers.splice(index1, 1);
                index2 = numbers.indexOf(num2);
                numbers.splice(index2, 1);
                console.log(`Congrats! You have found matching elements - ${num1}!`);
            } else if (num1 !== num2) {
                console.log('Try again!');
            }
        }
    }

    if (numbers.length === 0 || numbers.length === 1) {
        console.log(`You have won in ${moves} turns!`);
    } else {
        console.log(`Sorry you lose :(`);
        console.log(`${numbers.join(' ')}`);
    }
}

 

1
operator46 avatar operator46 3 Точки

Hey, Thanks for your suggestions. However I have implemented what you suggested and changed the forEach() with the option you provided and i still get 85/100. Not sure if it helps but its the middle test showing wrong answer.

Here is the updated code: 

https://pastebin.com/XQ2D1XF1

Thanks again for having a look into my case!

 

 

1
Axiomatik avatar Axiomatik 2422 Точки

Refactored the code and now it gives 100%, the forEach was not the issue as it mutated the array from the end towards the beginning - nice idea by the way! It was your matchingElements function, you pass on the actual elements in your array as indeces and turn around the whole logic - surprising that it passes with 85%.

function memoryGame(input) {
    let sequence = input.shift().split(' ');
    let elements = input.shift();
    let moves = 0;

    while (elements !== 'end' && sequence.length > 1) {
        let cur = elements.split(' ');
        let index1 = Number(cur[0]);
        let index2 = Number(cur[1]);

        moves++;

        if (checkValidIndex(index1, index2, sequence)) {
            // if (checkValidIndex(cur, sequence)) {
            let index = Math.trunc(sequence.length / 2);
            sequence.splice(index, 0, `-${moves}a`, `-${moves}a`);
            console.log('Invalid input! Adding additional elements to the board');
        } else {
            // if (matchingElements(sequence[index1], sequence[index2], sequence)) {
            if (sequence[index1] == sequence[index2]) {
                let element = sequence[index1];
                const sortedIndices = [index1, index2].sort((a, b) => b - a);
                sortedIndices.forEach((index) => {
                    sequence.splice(index, 1);
                });
                console.log(`Congrats! You have found matching elements - ${element}!`);
            } else if (sequence[index1] != sequence[index2]) {
                console.log("Try again!");
            }
        }

        // function matchingElements(el1, el2, array) {
        //     if (array[el1] == array[el2]) {
        //         return true;
        //     } else {
        //         return false;
        //     }
        // }

        function checkValidIndex(index1, index2, seq) {
            if (index1 === index2 || index1 < 0 || index2 < 0 || index1 >= seq.length || index2 >= seq.length) {
                return true;
            } else {
                return false;
            }
        }
        // function checkValidIndex(arr, seq) {
        //     if (arr[0] === arr[1] || arr[0] < 0 || arr[1] < 0 || arr[0] > seq.length || arr[1] > seq.length) {
        //         return true;
        //     } else {
        //         return false;
        //     }
        // }

        elements = input.shift();

        // if (sequence.length === 0) {
        //     break;
        // }
    }

    if (sequence.length === 0 || sequence.length === 1) {
        console.log(`You have won in ${moves} turns!`);
    } else {
        console.log('Sorry you lose :(');
        console.log(sequence.join(' '));
    }
}

 

1
27/05/2023 09:13:18
operator46 avatar operator46 3 Точки

Thanks a lot @Axiomatik. It actually make sence just to check if the two indices are equal, i've complicated it a bit and I am not surpriced it was wrong. Thanks for your time on this! Have a good day ahead.

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