Exam JS Fundamentals

javascript_logo

В изпита по Основи на JavaScript има 3 задачи.
Първата е свързана с някакъв стандартен алгоритъм. Втората с работа с масиви и третата с обработка на стрингове.

Линк с условия

Задача 1:

Въпреки очакванията за лесна задача, тази за съжаление не се оказа такава за мен. Задачата беше свързана с комбинаторика. В началото смятах, че ще я направя с вече стандартни алгоритми, с които съм работил, но повече от 10 точки не ми даваше. Какви ли не решения мислих, но нямаше резултат и след около час и нещо преминах на 2ра задача.

Задача 2:

Задачата беше стандартна за обхождане на матрица и много приличаше на такава от минал изпит, така че я реших за около 30мин за 100 точки.

Задача 3:

За тази задача само отделих време да ѝ погледна условието. Така и не ми остана много, защото непрекъснато се връщах на 1ва задача. Но в крайна сметка на 3та и колегите с най-добри резултати бяха взели 30т.

Бонус задача:

Имаше и малка бонус задача тази година, която носеше 25т. Лесна като логика, но условието беше да се напише с максимум 50 символа. Не успях да измисля пълна логика за задачата, но така да се каже, излъгах системата за 6точки, което пак е нещо. :)

Като цяло не съм доволен от резултата, въпреки че взех изпита и това се дължи най-вече на първата задача, защото по-късно видях, че съм бил по прав път.

 

jsfundamentalsExam

Solution link:

Earth Download

Exam Practice

javascript_logo

От миналата година има само два варианта за изпита по Основи на JavaScript, но дадоха добра представа от какво ще се състои.
В изпитите по JavaScript решението се пише в Solve функция и най-често като параметър се подава масив за обработка.

Условията могат да бъдат намерени на следните линкове:

Ще опиша само решенията на задачите от вечерната група, тъй като типа на задачите е идентичен:

Задача 1 -Max Sum:

function Solve(params) {

            var biggestSum = Number.MIN_VALUE;

            for (var i = 1; i < params.length; i++) {
                var currentSum = 0;

                for (var j = i; j < params.length; j++) {                     
                        currentSum += parseInt(params[j]); 
                    
                        if (currentSum > biggestSum) {
                        biggestSum = currentSum;
                    }
                }
            }

            return biggestSum;
        }

Условието е да се намери максималната сума от последователни елементи.
Алгоритъмът почва от първия елемент като го събира с всеки следващ и ако сумата е по-голяма от текущата го присвоява на biggestSum, ако не сборът продължава до края на масива и след това същата процедура продължава от 2ри, 3тия елемент и т.н.

Задача 2 -Labyrinth Escape:

С няколко думи условието на задачата е да се обикаля в двумерен масив (матрица) с определена стъпка и при дадени условия функцията да върне резултат.
В нулевия елемент се задава големината на матрицата. В първия стартовата позиция на обхождане. Със следващите елементи се задава посоката на движение: r – дясно, l – ляво, d – надолу, u – нагоре. Ако, при обхождането, стъпим на клетка, в която вече сме били, алгоритъмът спира и връща броя на посетените клетки. Ако излезем от размерите на масива, като резултат се връща сбора от числата в посетените клетки.

  1. В N и M запазваме размера на матрицата;
  2. startPosition запазва стартовата позиция;
  3. field и fieldCheck, съответно запазват числата в клетките на матрицата и запълваме с false, тъй като не сме стъпили още на нито една клетка;
  4. С безкрайния цикъл проверяваме текущата посока (r,l,d,u) и прибавяме или изваждаме от row и col единица, след това проверяваме дали не сме излезнали от масива или не сме стъпили на вече посетена клетка;
function Solve(args) {
 // var args = [
 // "5 8",
 //"0 0",
 //"rrrrrrrd",
 //"rludulrd",
 //"durlddud",
 //"urrrldud",
 //"ulllllll"]
 // ;
            var N = parseInt(args[0].split(' ')[0]);
            var M = parseInt(args[0].split(' ')[1]);

            var startPosition = args[1].split(' ');
            var field = [];
            var fieldCheck = [];
            var countCells = 1;

            for (var row = 0; row < N; row++) {
                field[row] = [];
                fieldCheck[row] = [];
                for (var col = 0; col < M; col++) {
                    field[row][col] = countCells;
                    fieldCheck[row][col] = false;
                    countCells++;
                }
            }

            var SUM_OF_NUMBERS_IN_THE_PATH = 0;
            var NUMBER_OF_CELL_IN_THE_PATH = 0;

            var row = parseInt(startPosition[0]);
            var col = parseInt(startPosition[1]);

            while (true) {

                NUMBER_OF_CELL_IN_THE_PATH++;
                SUM_OF_NUMBERS_IN_THE_PATH += field[row][col];
                fieldCheck[row][col] = true;
                var currentPosition = args[row + 2][col];

                switch (currentPosition) {
                    case 'l': col -= 1;
                        break;
                    case 'r': col += 1;
                        break;
                    case 'd': row += 1;
                        break;
                    case 'u': row -= 1;
                        break;
                }

                if (row = N || col = M) {
                    return 'out ' + SUM_OF_NUMBERS_IN_THE_PATH;
                }
                if (fieldCheck[row][col] == true) {
                    return 'lost ' + NUMBER_OF_CELL_IN_THE_PATH;
                }
            }
        }

Задача 3 -Listy:

Какво прави алгоритъмът:

  1. Всеки входящ стринг го split-вам с регулярен израз и след това в асоциативен масив functions пазя fname – името на функцията, operation – какво действие трябва да изпълни и value – стойностите в масив […].
  2. Обхождам готовия масив functions и спрямо действието, което трябва да прави минава през switch и в отделна функция, числата се обработват. Ако между тях има име на предишна функция в отделен метод addValue, то се подменя със съответната ѝ стойност.
function Solve(array) {

            var functions = [];
            var numbers = "";

            for (var i = 0; i < array.length; i++) {
                numbers = array[i].substring(array[i].indexOf('[') + 1, array[i].lastIndexOf(']'));
                array[i] = array[i].split(/[,[\]\s\r\n^ ]+/g);
                if (array[i].indexOf('sum') == -1 &&
                    array[i].indexOf('min') == -1 &&
                    array[i].indexOf('max') == -1 &&
                    array[i].indexOf('avg') == -1) {
                    functions.push({ fName: array[i][1], operation: 'none', value: numbers });
                }
                else {
                    functions.push({ fName: array[i][1], operation: array[i][2], value: numbers });
                }
            }

            for (var i = 0; i < functions.length; i++) {

                var operator = functions[i].operation;

                if (i == functions.length - 1) {
                    operator = array[i][0];
                    functions[i].operation = array[i][0];
                    functions[i].value = functions[i].value.split(/[,[\]\s\r\n^ ]+/g);
                    functions[i].fName = 'result';
                    return finalResult(operator, functions[i]);
                }

                functions[i].value = functions[i].value.split(/[,[\]\s\r\n^ ]+/g);

                switch (operator) {
                    case 'sum': sum(functions[i]);
                        break;
                    case 'avg': avg(functions[i]);
                        break;
                    case 'min': min(functions[i]);
                        break;
                    case 'max': max(functions[i]);
                        break;
                }
            }

            function max(func) {
                for (var i = 0; i < func.value.length; i++) {
                    if (!isNaN(parseInt(func.value[i]))) {
                        func.value[i] = parseInt(func.value[i]);
                    }
                    else {
                        addValue(func, func.value[i], i);
                        i -= 1;
                    }
                }

                func.value = Math.max.apply(Math, func.value);
                return func.value;
            }

            function min(func) {
                for (var i = 0; i < func.value.length; i++) {
                    if (!isNaN(parseInt(func.value[i]))) {
                        func.value[i] = parseInt(func.value[i]);
                    }
                    else {
                        addValue(func, func.value[i], i);
                        i -= 1;
                    }
                }

                func.value = Math.min.apply(Math, func.value);
                return func.value;
            }

            function sum(func) {
                var sumNums = 0;
                for (var i = 0; i < func.value.length; i++) {
                    if (!isNaN(parseInt(func.value[i]))) {
                        sumNums += parseInt(func.value[i]);
                    }
                    else {
                        addValue(func, func.value[i], i);
                        i -= 1;
                    }
                }

                func.value = sumNums;
                return sumNums;
            }
            function avg(func) {
                var len = func.value.length;
                var sumNums = sum(func);
                func.value = Math.floor(sumNums / len);
                return func.value;
            }

            function addValue(func, currentValue, index) {
                func.value.splice(index, 1);
                for (var i = 0; i < functions.length; i++) {
                    if (functions[i].fName == currentValue) {
                        if (!isNaN(functions[i].value)) {
                            func.value.push(functions[i].value);
                            break;
                        }
                        else {
                            for (var j = 0; j < functions[i].value.length; j++) {
                                if (functions[i].value[j] != "") {
                                    func.value.push(functions[i].value[j]);
                                }

                            }
                            break;
                        }
                    }
                }
            }

            function finalResult(operator, func) {

                switch (operator) {
                    case 'sum': return sum(func);
                        break;
                    case 'avg': return avg(func);
                        break;
                    case 'min': return min(func);
                        break;
                    case 'max': return max(func);
                        break;
                    default:
                        for (var i = 0; i < functions.length; i++) {
                            if (functions[i].fName == func.value) {
                                return functions[i].value;
                            }
                        }
                }
            }
        }

        var a = [
            'def maxy max[100, 5000, 4,2,1]',
            'def summary1 [0]',
            'def summary11 avg[summary1,maxy]',
            'def summary111 avg[ summary11 , maxy]',
            'def summary1111 avg[summary111 , maxy]',
            'sum[75468, summary1111]',
        ];

        document.writeln(Solve(a));

Solution link (Evening + Morning):

Earth Download

Strings

javascript_logo

  1. Write a JavaScript function reverses string and returns it
    • Example: “sample” -> “elpmas”.
  2. Write a JavaScript function to check if in a given expression the brackets are put correctly.
    • Example of correct expression: ((a+b)/5-d).
    • Example of incorrect expression: )(a+b)).
  3. Write a JavaScript function that finds how many times a substring is contained in a given text (perform case insensitive search).Example: The target substring is “in”. The text is as follows: We are living in an yellow submarine. We don’t have anything else. In**side the submarine is very tight. So we are drinking all the day. We will move out of it **in 5 days.

    The result is: 9.

  4. You are given a text. Write a function that changes the text in all regions:
    • <upcase>text</upcase> to uppercase.
    • <lowcase>text</lowcase> to lowercase
    • <mixcase>text</mixcase> to mix casing (random)

    Example: We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>. We <mixcase>don't</mixcase> have <lowcase>anything</lowcase> else.

    The expected result: We are LiVinG in a YELLOW SUBMARINE. We dOn'T have anything else.

    Regions can be nested.

  5. Write a function that replaces non breaking white-spaces in a text with &nbsp;
  6. Write a function that extracts the content of a html page given as text. The function should return anything that is in a tag, without the tags:
    <html>
        <head>
            <title>Sample site</title>
        </head>
        <body>
            <div>text<div>more text</div>and more...</div>in body
        </body>
    </html>
    

    Result: Sample sitetextmore textand more...in body

  7. Write a script that parses an URL address given in the format: [protocol]://[server]/[resource] and extracts from it the [protocol], [server] and [resource] elements. Return the elements in a JSON object.For example from the URL http://www.devbg.org/forum/index.php the following information should be extracted:
    {
        protocol: "http",
        server: "www.devbg.org",
        resource: "/forum/index.php"
    }
    
  8. Write a JavaScript function that replaces in a HTML document given as string all the tags <a href="...">...</a> with corresponding tags [URL=...]...[/URL]. Sample HTML fragment:
    <p>Please visit <a href="http://academy.telerik. com">our site</a> to choose a training course. Also visit <a href="www.devbg.org">our forum</a> to discuss the courses.</p>
    
    <p>Please visit [URL=http://academy.telerik. com]our site[/URL] to choose a training course. Also visit [URL=www.devbg.org]our forum[/URL] to discuss the courses.</p>
    
  9. Write a function for extracting all email addresses from given text. All substrings that match the format <identifier>@<host>...<domain> should be recognized as emails. Return the emails as array of strings.
  10. Write a program that extracts from a given text all palindromes, e.g. “ABBA“, “lamal” “exe“.
  11. Write a function that formats a string using placeholders:
    var str = stringFormat("Hello {0}!", "Peter");
    // str = "Hello Peter!";
    

    The function should work with up to 30 placeholders and all types

    var format = "{0}, {1}, {0} text {2}";
    var str = stringFormat(format, 1, "Pesho", "Gosho");
    // str = "1, Pesho, 1 text Gosho"
    
  12. Write a function that creates a HTML UL using a template for every HTML LI. The source of the list should an array of elements. Replace all placeholders marked with -{...}- with the value of the corresponding property of the object. Example:
    <div data-type="template" id="list-item">
        <strong>-{name}-</strong> <span>-{age}-</span>
    </div>
    
    var people = [{name: "Peter", age: 14}, ...];
    var tmpl = document.getElementById("list-item").innerHTML;
    var peopleList = generateList(people, template);
    // peopleList = "<ul><li><strong>Peter</strong> <span>14</span></li><li>...</li>...</ul>"
    
    

Solution link:

Earth Download

Objects

javascript_logo

  1. Write functions for working with shapes in standard Planar coordinate system
    • Points are represented by coordinates P(X, Y)
    • Lines are represented by two points, marking their beginning and ending: L(P1(X1,Y1), P2(X2,Y2))
    • Calculate the distance between two points
    • Check if three segment lines can form a triangle
  2. Write a function that removes all elements with a given value
    var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, "1"];
    arr.remove(1); // arr = [2, 4, 3, 4, 111, 3, 2, "1"];
    
    • Attach it to the array object
    • Read about prototype and how to attach methods
  3. Write a function that makes a deep copy of an object. The function should work for both primitive and reference types.
  4. Write a function that checks if a given object contains a given property
    var obj  = ...;
    var hasProp = hasProperty(obj, "length");
    
  5. Write a function that finds the youngest person in a given array of persons and prints his/hers full name
    • Each person has properties firstName, lastName and age, as shown:
    var persons = [
     { firstName : "Gosho", lastName: "Petrov", age: 32 },
     { firstName : "Bay", lastName: "Ivan", age: 81 }
     ...
    ];
    
  6. Write a function that groups an array of persons by age, first or last name. The function must return an associative array, with keys – the groups, and values -arrays with persons in this groups. Use function overloading (i.e. just one function).
    var persons = { ... };
    var groupedByFirstName = group(persons, "firstname");
    var groupedByAge = group(persons, "age");
    

Solution link:

Earth Download

Functions

javascript_logo

  1. Write a function that returns the last digit of given integer as an English word. Examples: 512 -> “two”, 1024 -> “four”, 12309 -> “nine”
  2. Write a function that reverses the digits of given decimal number. Example: 256 -> 652
  3. Write a function that finds all the occurrences of word in a text
    • The search can case sensitive or case insensitive
    • Use function overloading
  4. Write a function to count the number of divs on the web page
  5. Write a function that counts how many times given number appears in given array. Write a test function to check if the function is working correctly.
  6. Write a function that checks if the element at given position in given array of integers is bigger than its two neighbors (when such exist).
  7. Write a Function that returns the index of the first element in array that is bigger than its neighbors, or -1, if there’s no such element. Use the function from the previous exercise.

Solution link:

Earth Download

Arrays

javascript_logo

  1. Write a script that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console.
  2. Write a script that compares two char arrays lexicographically (letter by letter).
  3. Write a script that finds the maximal sequence of equal elements in an array.

    Example: [2, 1, 1, 2, 3, 3, 2, 2, 2, 1] -> [2, 2, 2].

  4. Write a script that finds the maximal increasing sequence in an array.

    Example: [3, 2, 3, 4, 2, 2, 4] -> [2, 3, 4].

  5. Sorting an array means to arrange its elements in increasing order. Write a script to sort an array. Use the “selection sort” algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc. Hint: Use a second array
  6. Write a program that finds the most frequent number in an array.

    Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)

  7. * Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm.

Solution link:

Earth Download

Loops

javascript_logo

  1. Write a script that prints all the numbers from 1 to N.
  2. Write a script that prints all the numbers from 1 to N, that are not divisible by 3 and 7 at the same time.
  3. Write a script that finds the max and min number from a sequence of numbers
  4. Write a script that finds the lexicographically smallest and largest property in document, window and navigator objects

Solution link:

Earth Download

Conditional Statements

javascript_logo

  1. Write an if statement that examines two integer variables and exchanges their values if the first one is greater than the second one.
  2. Write a program that shows the sign (+ or -) of the product of three real numbers without calculating it. Use a sequence of if statements.
  3. Write a program that finds the biggest of three integers using nested if statements.
  4. Sort 3 real values in descending order using nested if statements.
  5. Write a program that asks for a digit and depending on the input shows the name of that digit (in English) using a switch statement.
  6. Write a program that enters the coefficients a, b and c of a quadratic equation ax2+bx+c=0 and calculates and prints its real roots. Note that quadratic equations may have 0, 1 or 2 real roots.
  7. Write a program that finds the greatest of given 5 variables.
  8. Write a program that converts a number in the range [0…999] to a text corresponding to its English pronunciation. Examples:
    • 0 -> “Zero”
    • 273 -> “Two hundred and seventy-three”
    • 400 -> “Four hundred”
    • 501 -> “Five hundred and one”
    • 711 -> “Seven hundred and eleven”

Solution link:

Earth Download

Operators And Expressions

javascript_logo

  1. Write an expression that checks if given integer is odd or even.
  2. Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time.
  3. Write an expression that calculates rectangle’s area by given width and height.
  4. Write an expression that checks for given integer if its third digit (right-to-left) is 7.Example: 1732 -> true.
  5. Write a boolean expression for finding if the bit 3 (counting from 0) of a given integer is 1 or 0.
  6. Write an expression that checks if given point (x, y) is within a circle K((0, 0), 5).
  7. Write an expression that checks if given positive integer n (n ≤ 100) is prime.Example: 37 is prime.
  8. Write an expression that calculates trapezoid’s area by given sides a and b and height h.
  9. Write an expression that checks for given point (x, y) if it is within the circle K((1,1), 3) and out of the rectangle R(top=1, left=-1, width=6, height=2).

Solution link:

Earth Download

Data Types And Variables

javascript_logo

  1. Assign all the possible JavaScript literals to different variables.
  2. Create a string variable with quoted text in it. For example: “How you doin’?”, Joey said.
  3. Try typeof on all variables you created.
  4. Create null, undefined variables and try typeof on them.

Solution link:

Earth Download