Javascript-форум (https://javascript.ru/forum/)
-   Оффтопик (https://javascript.ru/forum/offtopic/)
-   -   Обсуждений тред (https://javascript.ru/forum/offtopic/47364-obsuzhdenijj-tred.html)

nerv_ 20.11.2017 21:36

Цитата:

Сообщение от cyber
Тоже что то такое подумал, на собеседование было задание

это куда ты так зашел удачно? :) Они объяснили хотя бы принцип по которому это должно рассчитываться?)

cyber 21.11.2017 15:38

Цитата:

Сообщение от Rise
cyber,
вгуглезабанили

Нет, я видел, но для начала хотел понять сам и не уверен уже что правильно потому что меня послали :)
Цитата:

Сообщение от nerv_
это куда ты так зашел удачно?

https://freighthub.com/en/
Цитата:

Сообщение от nerv_
Они объяснили хотя бы принцип по которому это должно рассчитываться?)

Нет, первое задание еще круче
Цитата:

1) Write a function to transform array a to array b and print the elements of array b to the console.
let a = [2, 4, 6, 8, 9, 15]
let b = ['4', '16', '64']

По логике тут нужно сделать F(a) = b (или я тупой) , но судя по гуглу тут тупо нужно добавить элементы из массива а в масси б :|

cyber 21.11.2017 15:40

И раз такая пъянка пошла, как думаете что не так с решением этого задания ?
Цитата:

3) Read a text file containing a set of flat polygons represented as one polygon per line. Each line contains a comma-separated list of side lengths (for example “3,4,8,5,7”). Write a function to classify the set of polygons into four mutually exclusive subsets: triangles, rectangles, squares, and everything else. The union of all four subsets should be the original set of polygons. All the sides of the polygons are connected and the angles between them are irrelevant. Only consider the lengths.
const readline = require('readline');
const fs = require("fs");
const Stream = require('stream');

function isTriangle(sides) {
    if (sides.length !== 3) {
        return false;
    }

    const a = parseInt(sides[0]), b = parseInt(sides[1]), c = parseInt(sides[2]);
    return a + b > c && a + c > b && b + c > a;
}

function isSquare(sides) {
    const firstSide = sides[0];
    return sides.length === 4 && sides.every(side => side === firstSide);
}

function isRectangle(sides) {
    return sides.length === 4 &&
        sides[0] === sides[2] && sides[1] === sides[3]
}

function getLineStream(filePath) {
    const readFileStream = fs.createReadStream(filePath);
    const outputStream = new Stream();
    return readline.createInterface(readFileStream, outputStream);
}

function getPolygons(lineStream) {
    return new Promise((resolve, reject) => {
        const all = [];
        const triangles = [];
        const squares = [];
        const rectangles = [];
        const others = [];

        lineStream.on("line", set => {
            set = set.split(",");
            if (isTriangle(set)) {
                triangles.push(set)
            }
            else if (isRectangle(set)) {
                rectangles.push(set);
            } else if (isSquare(set)) {
                squares.push(set);
            } else {
                others.push(set);
            }

            all.push(set);
        });

        lineStream.on("error", reject);
        lineStream.on("close", () => {
            resolve({all, triangles, squares, rectangles, others})
        })
    })
}

(async function () {
    const {all, triangles, rectangles, others, squares} = await getPolygons(getLineStream("./file"));
    console.log(`Triangles ${triangles.join("")}`);
    console.log(`Squares ${squares}`);
    console.log(`Rectangles ${rectangles}`);
    console.log(`Others ${others}`);
    console.log(`All ${all}`);
}());

join 22.11.2017 13:24

Сделал бы так:
const readline = require('readline');
const fs = require("fs");
const Stream = require('stream');

function isTriangle(sides) {
    if (sides.length === 3) {
        return true;
    }
    return false;
    //const a = parseInt(sides[0]), b = parseInt(sides[1]), c = parseInt(sides[2]);
    //return a + b > c && a + c > b && b + c > a;
}

function isSquare(sides) {
    const firstSide = parseInt(sides[0]);
    return sides.length === 4 && sides.every(side => parseInt(side) === firstSide);
}

function isRectangle(sides) {
    return sides.length === 4 && parseInt(sides[0]) === parseInt(sides[2]) && parseInt(sides[1]) === parseInt(sides[3]) && parseInt(sides[0]) !== parseInt(sides[1]) 
}

function getLineStream(filePath) {
    const readFileStream = fs.createReadStream(filePath);
    const outputStream = new Stream();
    return readline.createInterface(readFileStream, outputStream);
}

function getPolygons(lineStream) {
    return new Promise((resolve, reject) => {
        const all = [];
        const triangles = [];
        const squares = [];
        const rectangles = [];
        const others = [];

        lineStream.on("line", set => {
			let sex = set.replace(/[\"|\;]/gm,'').split(",");
            if (isTriangle(sex)) {
                triangles.push(set)
            } else if (isRectangle(sex)) {
                rectangles.push(set);
            } else if (isSquare(sex)) {
                squares.push(set);
            } else {
                others.push(set);
            }

            all.push(set);
        });

        lineStream.on("error", reject);
        lineStream.on("close", () => {
            resolve({all, triangles, squares, rectangles, others});
        })
    })
}

(async function () {
    const {all, triangles, rectangles, others, squares} = await getPolygons(getLineStream("./file.js"));
    console.log(`Triangles ${triangles.join("")}`);
    console.log(`Squares ${squares}`);
    console.log(`Rectangles ${rectangles}`);
    console.log(`Others ${others}`);
    console.log(`All ${all}`);
}());


file.js:
"4,2,3,4";
"2,5,2,5";
"6,6,6,6";
"2,4,6";
"5,12,44,55,44,33";
"4,3";
"7,8,9";
"4,4,4,4";

cyber 22.11.2017 13:42

join,
Тоже так сделал сначала, а потом вспомнил что есть формула..
Цитата:

function isTriangle(sides) {
    if (sides.length === 3) {
        return true;
    }
    return false;
    
}

а есть ли смысел parseInt если нам нужно тупо сравнить
Цитата:

function isRectangle(sides) {
    return sides.length === 4 && parseInt(sides[0]) === parseInt(sides[2]) && parseInt(sides[1]) === parseInt(sides[3]) && parseInt(sides[0]) !== parseInt(sides[1]) 
}


join 22.11.2017 14:34

Цитата:

Сообщение от cyber (Сообщение 470943)
join,
а есть ли смысел parseInt если нам нужно тупо сравнить

Я экспериментировал (разные входные данные подставлял - "2,3,4,5"; 2,3,4,5; 2,3,4,5 и тд с разным расширениями .txt, .js), parseInt осталось от предыдущих вариантов.

nerv_ 24.11.2017 07:55

cyber, твоя реализация выглядит вполне себе приемлемой. Они сказали, что в ней не так?

cyber 24.11.2017 10:37

Цитата:

Сообщение от nerv_
твоя реализация выглядит вполне себе приемлемой. Они сказали, что в ней не так?

Нет, просто послали :)

cyber 10.01.2018 17:08

Кто использует redux загляньте https://toster.ru/q/489936 :)

Nexus 11.01.2018 17:27

Рассказ о том, как я ворую номера кредиток и пароли у посетителей ваших сайтов


Часовой пояс GMT +3, время: 04:20.