Skip to content
Advertisement

How can I find and format visually aesthetically pleasant pattern of trees in a forest using javascript challenge question

There are examples of aesthetically pleasing trees:

enter image description here

These are examples of not aesthetically pleasing trees

enter image description here

That, given an array A consisting of N integers, where A[K] denotes the height of the K-th three, returns the number of ways of cutting out one tree, so that the remaining trees aesthetically pleasing. If it is not possible to achieve the desired result, your function should return -1. If the trees are already aesthetically pleasing without any removal your function should return 0.

Expected Result A1 = [1, 2, 3, 4, 2, 5]; This pattern can never be form visually aesthetical so, function should return -1.

Expected Result A2 = [1, 3, 1, 2]; this pattern is already in visually aesthetically pleasant so it should return 0.

I tried to solve it but it’s not working and I only got 1 result to all. Can someone help me code this in javascript?

Results Example:

Example test:   [3, 4, 5, 3, 7]
WRONG ANSWER (got 1 expected 3)

Example test:   [1, 2, 3, 4]
WRONG ANSWER (got 1 expected -1)

Example test:   [1, 3, 1, 2]
CORRECT ANSWER

My Code:

function solution(A) {
if (A.length < 3) {
            return A[0] != A[1] ? 0 : 1;
        }
        var count = 0;
        for (var i = 0; i < A.length - 2 ; i += 2) {
            var a = A[i];
            var b = A[i+1];
            var c = A[i + 2];
            if (!(a - b > 0 && b - c < 0) && !(a - b < 0 && b - c > 0)) {
                count++;
            }
        }
        return count;
}

Advertisement

Answer

You could break the problem into single tasks and check if an array is pleasant, then return zero or count pleasant subarrays.

The key function toggles the direction greater/smaller with a function and checks if the next pair is either greater, if the previous pair is smaller or vice versa.

To start, it needs to get the opposite of the actual direction, because it changes the directions first before checking.

function pleasant(array) {
    function isPleasant(array) {
        const
            toggle = { gt: 'lt', lt: 'gt' },
            fns = { gt: (a, b) => a > b, lt: (a, b) => a < b };
            
        let dir = fns.gt(array[0], array[1]) ? 'lt' : 'gt';

        return array
            .slice(1)
            .every((v, i) => fns[dir = toggle[dir]](array[i], v));
    }

    function count() {
        return array.reduce((c, _, i, a) => c + isPleasant([
            ...a.slice(0, i),
            ...a.slice(i + 1)
        ]), 0);
    }

    return isPleasant(array)
        ? 0
        : count() || -1;
}

console.log(pleasant([3, 4, 5, 3, 7])); //  3
console.log(pleasant([1, 2, 3, 4]));    // -1
console.log(pleasant([1, 3, 1, 2]));    //  0
console.log(pleasant([1, 1, 1, 1]));    // -1
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement