Ilia
Natalina27 🍀
оказывается чатгпт есть в телеграмме… написал мне этого Демукрона… обалдеть
Dan
Natalina27 🍀
https://t.me/GPT4Telegrambot
Null
Всем привет! 👋
LeetCode выкатили новую категорию вопросов -- JavaScript. Правда, пока их всего 21, но похоже на реальные задачи с фронтенд-собеседований.
P.S. bigfrontend.dev, по-моему, лучший сборников задач для фронтенда.
Alexander
Viktor
По Golang есть?
по golang это кажись обычные задачи на литкоде, все остальные
Sergei
Интересно будет специфичные для js задачи порешать
Ilia
Uladzimir
Ilia
Хана Миру (MSK+4)
Ой, а откуда столько людей пришло?
Viktar
Viktor
Irene
#whois какой забавный бот, до меня не сразу дошло, что он от меня хочет, если честно - может лучше поправить на - "пожалуйста, сообщение с тегом #whois длиной не менее 60 символов, чтобы представиться в чате и получить полный доступ"?
Вахтёр
Viktor
Alex
#whois Всем привет, меня зовут Саша! Мне этот чат порекоммендовали с другого чата, говорят что тут можно найти много полезного :)
Вахтёр
Viktor
Alex
Alex
По упаковке опыта и поиска работы
Natalina27 🍀
я кстати сюда пришла из чата Лены . у нее тоже интересно и на ее канале много интересных видео
https://t.me/webelart_chat
Viktor
Viktor
Реально классная задачка, кстати, которую мы с Леной решали
Viktor
На собесах встречается
Sergei
#whois Привет! Зовут Сергей, готовлюсь к собесам на западным рынке. решил 600+ на литкоде.
Вахтёр
Viktor
Sergei
Сегодня получил доступ на https://foobar.withgoogle.com/ . кто-нибудь проходил?
Viktor
johaone
#whois Привет всем! Вступил в чат чтобы быть в теме алгоритмов, узнать для себя что-то новое, научиться решать задачи
Вахтёр
Natalina27 🍀
Natalina27 🍀
Sergei
как получить туда доступ?
Пишут что гугл сам дает доступ по истории поиска (я искал inverse Ackermann function) или кто уже решил все задачи могут дать инвайты друзьям
Natalina27 🍀
спасибо
Sergei
разбор задач https://github.com/n3a9/google-foobar
Natalina27 🍀
ты на java пишешь?
Sergei
python+golang (разбор по ссылке не мой)
Natalina27 🍀
ааа ок
Ilia
#whois Всем привет, я java middle developer, сейчас проживаю в Ереване и ищу работу там же или удаленку/релокацию. Пришёл в поиске материалов для подготовки к алгоритмическим собеседования, посижу почитаю ваши сообщения)
Вахтёр
Вахтёр
@Kamila\_Malikova молчит и покидает чат
Вахтёр
@kolysvit молчит и покидает чат
Вахтёр
@akushev молчит и покидает чат
Вахтёр
@AnrMGZV молчит и покидает чат
Вахтёр
Leah Reader молчит и покидает чат
Ainur
#whois Всем привет, я python developer, сейчас активно учу алгоритмы для дальнейшей смены работы. Пришёл в поиске материалов для подготовки к алгоритмическим собеседования, посижу почитаю ваши сообщения)
Вахтёр
Viktor
Viktor
August
Ainur
Natalina27 🍀
Всем привет я опять со своим алгоритмом Демукрона Что то чатгпт меня вообще запутал выдает всегда разное и я еще больше запуталась Граф я так понимаю надо отсортировать то есть он обязательно должен быть взвешанным? направленным? если кто то сможет вообще обьяснить задачу буду благодарна
Natalina27 🍀
сначала он выдал мне такое
Natalina27 🍀
Sure, here is the implementation of Demukron algorithm in JavaScript:
function demukronAlgorithm(graph, startNode) {
const distances = {};
const parents = {};
const visitedNodes = [];
let negativeCycle = false;
// Initialize distances to infinity except for startNode
for (let node in graph) {
distances[node] = Infinity;
}
distances[startNode] = 0;
// Find shortest path from startNode to all other nodes
for (let i = 0; i < Object.keys(graph).length - 1; i++) {
for (let node in graph) {
for (let neighbor in graph[node]) {
const weight = graph[node][neighbor];
const distanceFromStartToNeighbor = distances[node] + weight;
if (distanceFromStartToNeighbor < distances[neighbor]) {
distances[neighbor] = distanceFromStartToNeighbor;
parents[neighbor] = node;
}
}
}
}
// Check for negative cycle
for (let node in graph) {
for (let neighbor in graph[node]) {
const weight = graph[node][neighbor];
const distanceFromStartToNeighbor = distances[node] + weight;
if (distanceFromStartToNeighbor < distances[neighbor]) {
negativeCycle = true;
break;
}
}
if (negativeCycle) break;
}
// Build path from startNode to endNode
let path = [];
let currentNode = Object.keys(graph)[Object.keys(graph).length - 1];
while (currentNode !== startNode) {
path.unshift(currentNode);
currentNode = parents[currentNode];
}
path.unshift(startNode);
return { distances, path, negativeCycle };
}
This implementation takes in a graph object, where each key represents a node and its value is an object containing its neighbors and their corresponding edge weights. For example:
const graph = {
A: { B: -1, C: 4 },
B: { D: 2 },
C: { B: 3, D: 2 },
D: {},
};
This graph represents the following:
-1 2
A -----> B -----> D
\ ^
\4 |3
\ |
v v
C --->
2
The startNode parameter specifies the starting node for the algorithm.
The function returns an object containing the shortest distances from the startNode to all other nodes, the path from the startNode to the last node in the graph (which can be used to reconstruct the shortest path), and a boolean indicating whether there is a negative cycle in the graph (negativeCycle).
Note that this implementation assumes that the graph does not contain any self-loops or parallel edges. If your graph does contain these, you may need to modify the implementation accordingly.
Natalina27 🍀
я сам граф реализовала так
Natalina27 🍀
Natalina27 🍀
а что дальше? пыталась использовать его функцию но не работает видимо я не те параметры передаю
Natalina27 🍀
попросила его с примером и он прислал вообще другое
Natalina27 🍀
Certainly! Here is an implementation of the Demukron algorithm in JavaScript for sorting a graph:
class Graph {
constructor(vertices) {
this.vertices = vertices;
this.adjacencyList = new Map();
for (let i = 0; i < vertices.length; i++) {
this.adjacencyList.set(vertices[i], []);
}
}
addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
}
demukronSort() {
const sortedVertices = [];
const visitedVertices = new Map();
for (let i = 0; i < this.vertices.length; i++) {
visitedVertices.set(this.vertices[i], false);
}
for (let i = 0; i < this.vertices.length; i++) {
if (!visitedVertices.get(this.vertices[i])) {
this.dfs(this.vertices[i], visitedVertices, sortedVertices);
}
}
return sortedVertices;
}
dfs(vertex, visitedVertices, sortedVertices) {
visitedVertices.set(vertex, true);
const adjacencyList = this.adjacencyList.get(vertex);
for (let i = 0; i < adjacencyList.length; i++) {
const adjacentVertex = adjacencyList[i];
if (!visitedVertices.get(adjacentVertex)) {
this.dfs(adjacentVertex, visitedVertices, sortedVertices);
}
}
sortedVertices.unshift(vertex);
}
}
const graph = new Graph(["A", "B", "C", "D", "E"]);
graph.addEdge("A", "C");
graph.addEdge("C", "D");
graph.addEdge("D", "E");
graph.addEdge("E", "B");
graph.addEdge("B", "C");
const sortedVertices = graph.demukronSort();
console.log(sortedVertices); // Output: ["A", "B", "E", "D", "C"]
In this example, we create a graph with five vertices and add edges between them. We then call the demukronSort method on the graph to sort its vertices using the Demukron algorithm.
The dfs method is used to perform a depth-first search on the graph, starting from a given vertex. It marks each visited vertex as true in the visitedVertices map and recursively calls itself on each adjacent vertex that has not been visited yet. Once all adjacent vertices have been visited, the current vertex is added to the beginning of the sortedVertices array using the unshift method.
The demukronSort method initializes a visitedVertices map with all vertices set to false, and then loops through each vertex in the graph. If a vertex has not been visited yet, it calls the dfs method on it. Once all vertices have been visited, the sortedVertices array is returned.
In this example, the output of the demukronSort method is an array of sorted vertices: ["A", "B", "E", "D", "C"].
Natalina27 🍀
хочется добить все таки его
Ilia
Описание, которое он дал, это чистый тарьян
Ilia
Инфы по демукрону и в Гугле то мало, я не могу толком ничего найти даже
Natalina27 🍀
я тоже ничего не нашла
Natalina27 🍀
написала в чате отуса чтоб они обьяснили для ту...х... таких как я пока молчат
Lynn «Кофеман»
Я нашёл pdf, но что-то по диагонали с ходу не разобрался…
Lynn «Кофеман»
Насколько я понял это алгоритм рисования планарного графа (или доказывания по пути что он не планарный).
Так что при чём тут веса и направленность я не очень понимаю.
В чём состоит изначальная задача?
Natalina27 🍀
задача реализовать алгоритм Демукрона )))
Natalina27 🍀
в том то и проблема что я не понимаю задачу )))
Natalina27 🍀
а что такое планарный граф?
Lynn «Кофеман»
Вот ещё что нашлось на португальском питоне =)
https://github.com/matheper/demoucron