mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
Merge branch 'master' into master
This commit is contained in:
84
CONTRIBUTING.md
Normal file
84
CONTRIBUTING.md
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
# Contributing guidelines
|
||||||
|
|
||||||
|
## Before contributing
|
||||||
|
|
||||||
|
Welcome to [TheAlgorithms/Javascript](https://github.com/TheAlgorithms/Javascript)! Before sending your pull requests, make sure that you **read the whole guidelines**. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Javascript/issues/new)
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
### Contributor
|
||||||
|
|
||||||
|
We are very happy that you consider implementing algorithms and data structure for others! This repository is referenced and used by learners from around the globe. Being one of our contributors, you agree and confirm that:
|
||||||
|
|
||||||
|
- You did your work - plagiarism is not allowed.
|
||||||
|
- Any plagiarized work will not be merged.
|
||||||
|
- Your work will be distributed under [GNU License](License) once your pull request is merged
|
||||||
|
- You submitted work fulfils or mostly fulfils our styles and standards
|
||||||
|
|
||||||
|
**New implementation** is welcome! For example, new solutions to a problem, different representations of a graph data structure or algorithm designs with different complexity.
|
||||||
|
|
||||||
|
**Improving comments** and **writing proper tests** are also highly welcome.
|
||||||
|
|
||||||
|
### Contribution
|
||||||
|
|
||||||
|
We appreciate any contribution, from fixing grammar mistakes to implementing complex algorithms. Please read this section if you are contributing your work.
|
||||||
|
|
||||||
|
|
||||||
|
If you submit a pull request that resolves an open issue, please help us to keep our issue list small by adding `fixes: #{$ISSUE_NO}` to your commit message. GitHub will use this tag to auto close the issue if your PR is merged.
|
||||||
|
|
||||||
|
#### What is an Algorithm?
|
||||||
|
|
||||||
|
An Algorithm is one or more functions (or classes) that:
|
||||||
|
* take one or more inputs,
|
||||||
|
* perform some internal calculations or data manipulations,
|
||||||
|
* return one or more outputs,
|
||||||
|
* have minimal side effects.
|
||||||
|
|
||||||
|
Algorithms should be packaged in a way that would make it easy for readers to put them into larger programs.
|
||||||
|
|
||||||
|
Algorithms should:
|
||||||
|
* have intuitive class and function names that make their purpose clear to readers
|
||||||
|
* use JavaScript naming conventions and intuitive variable names to ease comprehension
|
||||||
|
* be flexible to take different input values
|
||||||
|
* raise JavaScript exceptions (RangeError, etc.) on erroneous input values
|
||||||
|
|
||||||
|
Algorithms in this repo should not be how-to examples for existing JavaScript packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing JavaScript packages but each algorithm in this repo should add unique value.
|
||||||
|
|
||||||
|
#### Coding Style
|
||||||
|
|
||||||
|
To maximize the readability and correctness of our code, we require that new submissions follow [JavaScript Standard Style](https://standardjs.com/)
|
||||||
|
- Command to install JavaScript Standard Style
|
||||||
|
```
|
||||||
|
$ npm install standard --save-dev
|
||||||
|
```
|
||||||
|
- Usage
|
||||||
|
```
|
||||||
|
$ standard MyFile.js // if that fails, try: npx standard MyFile.js
|
||||||
|
```
|
||||||
|
|
||||||
|
- Use camelCase for with leading character lowercase for identifier names (variables and functions)
|
||||||
|
- Names start with a letter
|
||||||
|
- follow code indentation
|
||||||
|
- Always use 2 spaces for indentation of code blocks
|
||||||
|
```
|
||||||
|
function sumOfArray (arrayOfNumbers) {
|
||||||
|
let sum = 0
|
||||||
|
for (let i = 0; i < arrayOfNumbers.length; i++) {
|
||||||
|
sum += arrayOfNumbers[i]
|
||||||
|
}
|
||||||
|
return (sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
- Avoid using global variables and avoid '=='
|
||||||
|
- Please use 'let' over 'var'
|
||||||
|
- We strongly recommend the use of ECMAScript 6
|
||||||
|
- Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- Most importantly,
|
||||||
|
- **Be consistent in the use of these guidelines when submitting.**
|
||||||
|
- Happy coding!
|
||||||
|
|
||||||
|
Writer [@itsvinayak](https://github.com/itsvinayak), May 2020.
|
@ -1,195 +1,198 @@
|
|||||||
// Hamza chabchoub contribution for a university project
|
//Hamza chabchoub contribution for a university project
|
||||||
function doubleLinkedList () {
|
function doubleLinkedList() {
|
||||||
const Node = function (element) {
|
let Node = function(element) {
|
||||||
this.element = element
|
this.element = element;
|
||||||
this.next = null
|
this.next = null;
|
||||||
this.prev = null
|
this.prev = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
let length = 0
|
let length = 0;
|
||||||
let head = null
|
let head = null;
|
||||||
let tail = null
|
let tail = null;
|
||||||
|
|
||||||
// Add new element
|
//Add new element
|
||||||
this.append = function (element) {
|
this.append = function(element) {
|
||||||
const node = new Node(element)
|
let node = new Node(element);
|
||||||
|
|
||||||
if (!head) {
|
if(!head){
|
||||||
head = node
|
head = node;
|
||||||
tail = node
|
tail = node;
|
||||||
} else {
|
}else{
|
||||||
node.prev = tail
|
node.prev = tail;
|
||||||
tail.next = node
|
tail.next = node;
|
||||||
tail = node
|
tail = node;
|
||||||
}
|
}
|
||||||
|
|
||||||
length++
|
length++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add element
|
|
||||||
this.insert = function (position, element) {
|
|
||||||
// Check of out-of-bound values
|
|
||||||
if (position >= 0 && position <= length) {
|
|
||||||
const node = new Node(element)
|
|
||||||
let current = head
|
|
||||||
let previous
|
|
||||||
let index = 0
|
|
||||||
|
|
||||||
if (position === 0) {
|
//Add element
|
||||||
if (!head) {
|
this.insert = function(position, element) {
|
||||||
head = node
|
|
||||||
tail = node
|
//Check of out-of-bound values
|
||||||
} else {
|
if(position >= 0 && position <= length){
|
||||||
node.next = current
|
let node = new Node(element),
|
||||||
current.prev = node
|
current = head,
|
||||||
head = node
|
previous,
|
||||||
|
index = 0;
|
||||||
|
|
||||||
|
if(position === 0){
|
||||||
|
if(!head){
|
||||||
|
head = node;
|
||||||
|
tail = node;
|
||||||
|
}else{
|
||||||
|
node.next = current;
|
||||||
|
current.prev = node;
|
||||||
|
head = node;
|
||||||
}
|
}
|
||||||
} else if (position === length) {
|
}else if(position === length){
|
||||||
current = tail
|
current = tail;
|
||||||
current.next = node
|
current.next = node;
|
||||||
node.prev = current
|
node.prev = current;
|
||||||
tail = node
|
tail = node;
|
||||||
} else {
|
}else{
|
||||||
while (index++ < position) {
|
while(index++ < position){
|
||||||
previous = current
|
previous = current;
|
||||||
current = current.next
|
current = current.next;
|
||||||
}
|
}
|
||||||
|
|
||||||
node.next = current
|
node.next = current;
|
||||||
previous.next = node
|
previous.next = node;
|
||||||
|
|
||||||
// New
|
//New
|
||||||
current.prev = node
|
current.prev = node;
|
||||||
node.prev = previous
|
node.prev = previous;
|
||||||
}
|
}
|
||||||
|
|
||||||
length++
|
length++;
|
||||||
return true
|
return true;
|
||||||
} else {
|
}else{
|
||||||
return false
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove element at any position
|
//Remove element at any position
|
||||||
this.removeAt = function (position) {
|
this.removeAt = function(position){
|
||||||
// look for out-of-bounds value
|
//look for out-of-bounds value
|
||||||
if (position > -1 && position < length) {
|
if(position > -1 && position < length){
|
||||||
let current = head; let previous; let index = 0
|
let current = head, previous, index = 0;
|
||||||
|
|
||||||
// Removing first item
|
//Removing first item
|
||||||
if (position === 0) {
|
if(position === 0){
|
||||||
head = current.next
|
head = current.next;
|
||||||
|
|
||||||
// if there is only one item, update tail //NEW
|
//if there is only one item, update tail //NEW
|
||||||
if (length === 1) {
|
if(length === 1){
|
||||||
tail = null
|
tail = null;
|
||||||
} else {
|
}else{
|
||||||
head.prev = null
|
head.prev = null;
|
||||||
}
|
}
|
||||||
} else if (position === length - 1) {
|
}else if(position === length - 1){
|
||||||
current = tail
|
current = tail;
|
||||||
tail = current.prev
|
tail = current.prev;
|
||||||
tail.next = null
|
tail.next = null;
|
||||||
} else {
|
}else{
|
||||||
while (index++ < position) {
|
while(index++ < position){
|
||||||
previous = current
|
previous = current;
|
||||||
current = current.next
|
current = current.next;
|
||||||
}
|
}
|
||||||
|
|
||||||
// link previous with current's next - skip it
|
//link previous with current's next - skip it
|
||||||
previous.next = current.next
|
previous.next = current.next;
|
||||||
current.next.prev = previous
|
current.next.prev = previous;
|
||||||
}
|
}
|
||||||
|
|
||||||
length--
|
length--;
|
||||||
return current.element
|
return current.element;
|
||||||
} else {
|
}else{
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the indexOf item
|
//Get the indexOf item
|
||||||
this.indexOf = function (elm) {
|
this.indexOf = function(elm){
|
||||||
let current = head
|
let current = head,
|
||||||
let index = -1
|
index = -1;
|
||||||
|
|
||||||
// If element found then return its position
|
//If element found then return its position
|
||||||
while (current) {
|
while(current){
|
||||||
if (elm === current.element) {
|
if(elm === current.element){
|
||||||
return ++index
|
return ++index;
|
||||||
}
|
}
|
||||||
|
|
||||||
index++
|
index++;
|
||||||
current = current.next
|
current = current.next;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Else return -1
|
//Else return -1
|
||||||
return -1
|
return -1;
|
||||||
}
|
};
|
||||||
|
|
||||||
// Find the item in the list
|
//Find the item in the list
|
||||||
this.isPresent = (elm) => {
|
this.isPresent = (elm) => {
|
||||||
return this.indexOf(elm) !== -1
|
return this.indexOf(elm) !== -1;
|
||||||
}
|
};
|
||||||
|
|
||||||
// Delete an item from the list
|
//Delete an item from the list
|
||||||
this.delete = (elm) => {
|
this.delete = (elm) => {
|
||||||
return this.removeAt(this.indexOf(elm))
|
return this.removeAt(this.indexOf(elm));
|
||||||
|
};
|
||||||
|
|
||||||
|
//Delete first item from the list
|
||||||
|
this.deleteHead = function(){
|
||||||
|
this.removeAt(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete first item from the list
|
//Delete last item from the list
|
||||||
this.deleteHead = function () {
|
this.deleteTail = function(){
|
||||||
this.removeAt(0)
|
this.removeAt(length-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete last item from the list
|
//Print item of the string
|
||||||
this.deleteTail = function () {
|
this.toString = function(){
|
||||||
this.removeAt(length - 1)
|
let current = head,
|
||||||
|
string = '';
|
||||||
|
|
||||||
|
while(current){
|
||||||
|
string += current.element + (current.next ? '\n' : '');
|
||||||
|
current = current.next;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print item of the string
|
return string;
|
||||||
this.toString = function () {
|
};
|
||||||
let current = head
|
|
||||||
let string = ''
|
|
||||||
|
|
||||||
while (current) {
|
//Convert list to array
|
||||||
string += current.element + (current.next ? '\n' : '')
|
this.toArray = function(){
|
||||||
current = current.next
|
let arr = [],
|
||||||
|
current = head;
|
||||||
|
|
||||||
|
while(current){
|
||||||
|
arr.push(current.element);
|
||||||
|
current = current.next;
|
||||||
}
|
}
|
||||||
|
|
||||||
return string
|
return arr;
|
||||||
|
};
|
||||||
|
|
||||||
|
//Check if list is empty
|
||||||
|
this.isEmpty = function(){
|
||||||
|
return length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
//Get the size of the list
|
||||||
|
this.size = function(){
|
||||||
|
return length;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert list to array
|
//Get the head
|
||||||
this.toArray = function () {
|
this.getHead = function() {
|
||||||
const arr = []
|
return head;
|
||||||
let current = head
|
|
||||||
|
|
||||||
while (current) {
|
|
||||||
arr.push(current.element)
|
|
||||||
current = current.next
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return arr
|
//Get the tail
|
||||||
|
this.getTail = function() {
|
||||||
|
return tail;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if list is empty
|
|
||||||
this.isEmpty = function () {
|
|
||||||
return length === 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the size of the list
|
|
||||||
this.size = function () {
|
|
||||||
return length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the head
|
|
||||||
this.getHead = function () {
|
|
||||||
return head
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the tail
|
|
||||||
this.getTail = function () {
|
|
||||||
return tail
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,58 +1,60 @@
|
|||||||
function TopologicalSorter () {
|
|
||||||
var graph = {}
|
function TopologicalSorter() {
|
||||||
var isVisitedNode
|
var graph = {},
|
||||||
var finishTimeCount
|
isVisitedNode,
|
||||||
var finishingTimeList
|
finishTimeCount,
|
||||||
var nextNode
|
finishingTimeList,
|
||||||
|
nextNode;
|
||||||
|
|
||||||
this.addOrder = function (nodeA, nodeB) {
|
this.addOrder = function (nodeA, nodeB) {
|
||||||
nodeA = String(nodeA)
|
nodeA = String(nodeA);
|
||||||
nodeB = String(nodeB)
|
nodeB = String(nodeB);
|
||||||
graph[nodeA] = graph[nodeA] || []
|
graph[nodeA] = graph[nodeA] || [];
|
||||||
graph[nodeA].push(nodeB)
|
graph[nodeA].push(nodeB);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sortAndGetOrderedItems = function () {
|
this.sortAndGetOrderedItems = function () {
|
||||||
isVisitedNode = Object.create(null)
|
isVisitedNode = Object.create(null);
|
||||||
finishTimeCount = 0
|
finishTimeCount = 0;
|
||||||
finishingTimeList = []
|
finishingTimeList = [];
|
||||||
|
|
||||||
for (var node in graph) {
|
for (var node in graph) {
|
||||||
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
|
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
|
||||||
dfsTraverse(node)
|
dfsTraverse(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
finishingTimeList.sort(function (item1, item2) {
|
finishingTimeList.sort(function (item1, item2) {
|
||||||
return item1.finishTime > item2.finishTime ? -1 : 1
|
return item1.finishTime > item2.finishTime ? -1 : 1;
|
||||||
})
|
});
|
||||||
|
|
||||||
return finishingTimeList.map(function (value) { return value.node })
|
return finishingTimeList.map(function (value) { return value.node })
|
||||||
}
|
}
|
||||||
|
|
||||||
function dfsTraverse (node) {
|
function dfsTraverse(node) {
|
||||||
isVisitedNode[node] = true
|
isVisitedNode[node] = true;
|
||||||
if (graph[node]) {
|
if (graph[node]) {
|
||||||
for (var i = 0; i < graph[node].length; i++) {
|
for (var i = 0; i < graph[node].length; i++) {
|
||||||
nextNode = graph[node][i]
|
nextNode = graph[node][i];
|
||||||
if (isVisitedNode[nextNode]) continue
|
if (isVisitedNode[nextNode]) continue;
|
||||||
dfsTraverse(nextNode)
|
dfsTraverse(nextNode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
finishingTimeList.push({
|
finishingTimeList.push({
|
||||||
node: node,
|
node: node,
|
||||||
finishTime: ++finishTimeCount
|
finishTime: ++finishTimeCount
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* TEST */
|
/* TEST */
|
||||||
var topoSorter = new TopologicalSorter()
|
var topoSorter = new TopologicalSorter();
|
||||||
topoSorter.addOrder(5, 2)
|
topoSorter.addOrder(5, 2);
|
||||||
topoSorter.addOrder(5, 0)
|
topoSorter.addOrder(5, 0);
|
||||||
topoSorter.addOrder(4, 0)
|
topoSorter.addOrder(4, 0);
|
||||||
topoSorter.addOrder(4, 1)
|
topoSorter.addOrder(4, 1);
|
||||||
topoSorter.addOrder(2, 3)
|
topoSorter.addOrder(2, 3);
|
||||||
topoSorter.addOrder(3, 1)
|
topoSorter.addOrder(3, 1);
|
||||||
console.log(topoSorter.sortAndGetOrderedItems())
|
console.log(topoSorter.sortAndGetOrderedItems());
|
||||||
|
@ -1,66 +1,71 @@
|
|||||||
// starting at s
|
// starting at s
|
||||||
function solve (graph, s) {
|
function solve(graph, s) {
|
||||||
var solutions = {}
|
var solutions = {};
|
||||||
solutions[s] = []
|
solutions[s] = [];
|
||||||
solutions[s].dist = 0
|
solutions[s].dist = 0;
|
||||||
|
|
||||||
while (true) {
|
while(true) {
|
||||||
var p = null
|
var p = null;
|
||||||
var neighbor = null
|
var neighbor = null;
|
||||||
var dist = Infinity
|
var dist = Infinity;
|
||||||
|
|
||||||
for (var n in solutions) {
|
|
||||||
if (!solutions[n]) { continue }
|
|
||||||
var ndist = solutions[n].dist
|
|
||||||
var adj = graph[n]
|
|
||||||
|
|
||||||
for (var a in adj) {
|
for(var n in solutions) {
|
||||||
if (solutions[a]) { continue }
|
if(!solutions[n])
|
||||||
|
continue
|
||||||
|
var ndist = solutions[n].dist;
|
||||||
|
var adj = graph[n];
|
||||||
|
|
||||||
var d = adj[a] + ndist
|
for(var a in adj) {
|
||||||
if (d < dist) {
|
|
||||||
p = solutions[n]
|
if(solutions[a])
|
||||||
neighbor = a
|
continue;
|
||||||
dist = d
|
|
||||||
|
var d = adj[a] + ndist;
|
||||||
|
if(d < dist) {
|
||||||
|
|
||||||
|
p = solutions[n];
|
||||||
|
neighbor = a;
|
||||||
|
dist = d;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// no more solutions
|
//no more solutions
|
||||||
if (dist === Infinity) {
|
if(dist === Infinity) {
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// extend parent's solution path
|
//extend parent's solution path
|
||||||
solutions[neighbor] = p.concat(neighbor)
|
solutions[neighbor] = p.concat(neighbor);
|
||||||
// extend parent's cost
|
//extend parent's cost
|
||||||
solutions[neighbor].dist = dist
|
solutions[neighbor].dist = dist;
|
||||||
}
|
}
|
||||||
|
|
||||||
return solutions
|
return solutions;
|
||||||
}
|
}
|
||||||
// create graph
|
//create graph
|
||||||
var graph = {}
|
var graph = {};
|
||||||
|
|
||||||
var layout = {
|
var layout = {
|
||||||
R: ['2'],
|
'R': ['2'],
|
||||||
2: ['3', '4'],
|
'2': ['3','4'],
|
||||||
3: ['4', '6', '13'],
|
'3': ['4','6','13'],
|
||||||
4: ['5', '8'],
|
'4': ['5','8'],
|
||||||
5: ['7', '11'],
|
'5': ['7','11'],
|
||||||
6: ['13', '15'],
|
'6': ['13','15'],
|
||||||
7: ['10'],
|
'7': ['10'],
|
||||||
8: ['11', '13'],
|
'8': ['11','13'],
|
||||||
9: ['14'],
|
'9': ['14'],
|
||||||
10: [],
|
'10': [],
|
||||||
11: ['12'],
|
'11': ['12'],
|
||||||
12: [],
|
'12': [],
|
||||||
13: ['14'],
|
'13': ['14'],
|
||||||
14: [],
|
'14': [],
|
||||||
15: []
|
'15': []
|
||||||
}
|
}
|
||||||
|
|
||||||
// convert uni-directional to bi-directional graph
|
//convert uni-directional to bi-directional graph
|
||||||
// var graph = {
|
// var graph = {
|
||||||
// a: {e:1, b:1, g:3},
|
// a: {e:1, b:1, g:3},
|
||||||
// b: {a:1, c:1},
|
// b: {a:1, c:1},
|
||||||
@ -72,25 +77,27 @@ var layout = {
|
|||||||
// h: {f:1}
|
// h: {f:1}
|
||||||
// };
|
// };
|
||||||
|
|
||||||
for (var id in layout) {
|
for(var id in layout) {
|
||||||
if (!graph[id]) { graph[id] = {} }
|
if(!graph[id])
|
||||||
layout[id].forEach(function (aid) {
|
graph[id] = {};
|
||||||
graph[id][aid] = 1
|
layout[id].forEach(function(aid) {
|
||||||
if (!graph[aid]) { graph[aid] = {} }
|
graph[id][aid] = 1;
|
||||||
graph[aid][id] = 1
|
if(!graph[aid])
|
||||||
})
|
graph[aid] = {};
|
||||||
|
graph[aid][id] = 1;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// choose start node
|
//choose start node
|
||||||
var start = '10'
|
var start = '10';
|
||||||
// get all solutions
|
//get all solutions
|
||||||
var solutions = solve(graph, start)
|
var solutions = solve(graph, start);
|
||||||
|
|
||||||
console.log("From '" + start + "' to")
|
console.log("From '"+start+"' to");
|
||||||
// display solutions
|
//display solutions
|
||||||
for (var s in solutions) {
|
for(var s in solutions) {
|
||||||
if (!solutions[s]) continue
|
if(!solutions[s]) continue;
|
||||||
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
|
console.log(" -> " + s + ": [" + solutions[s].join(", ") + "] (dist:" + solutions[s].dist + ")");
|
||||||
}
|
}
|
||||||
|
|
||||||
// From '10' to
|
// From '10' to
|
||||||
|
@ -2,9 +2,10 @@
|
|||||||
class Graph {
|
class Graph {
|
||||||
// defining vertex array and
|
// defining vertex array and
|
||||||
// adjacent list
|
// adjacent list
|
||||||
constructor (noOfVertices) {
|
constructor(noOfVertices)
|
||||||
this.noOfVertices = noOfVertices
|
{
|
||||||
this.AdjList = new Map()
|
this.noOfVertices = noOfVertices;
|
||||||
|
this.AdjList = new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
// functions to be implemented
|
// functions to be implemented
|
||||||
@ -22,7 +23,7 @@ addVertex(v)
|
|||||||
{
|
{
|
||||||
// initialize the adjacent list with a
|
// initialize the adjacent list with a
|
||||||
// null array
|
// null array
|
||||||
this.AdjList.set(v, [])
|
this.AdjList.set(v, []);
|
||||||
}
|
}
|
||||||
|
|
||||||
// add edge to the graph
|
// add edge to the graph
|
||||||
@ -30,53 +31,57 @@ addEdge(v, w)
|
|||||||
{
|
{
|
||||||
// get the list for vertex v and put the
|
// get the list for vertex v and put the
|
||||||
// vertex w denoting edge between v and w
|
// vertex w denoting edge between v and w
|
||||||
this.AdjList.get(v).push(w)
|
this.AdjList.get(v).push(w);
|
||||||
|
|
||||||
// Since graph is undirected,
|
// Since graph is undirected,
|
||||||
// add an edge from w to v also
|
// add an edge from w to v also
|
||||||
this.AdjList.get(w).push(v)
|
this.AdjList.get(w).push(v);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Prints the vertex and adjacency list
|
// Prints the vertex and adjacency list
|
||||||
printGraph()
|
printGraph()
|
||||||
{
|
{
|
||||||
// get all the vertices
|
// get all the vertices
|
||||||
var get_keys = this.AdjList.keys()
|
var get_keys = this.AdjList.keys();
|
||||||
|
|
||||||
// iterate over the vertices
|
// iterate over the vertices
|
||||||
for (var i of get_keys) {
|
for (var i of get_keys)
|
||||||
|
{
|
||||||
// great the corresponding adjacency list
|
// great the corresponding adjacency list
|
||||||
// for the vertex
|
// for the vertex
|
||||||
var get_values = this.AdjList.get(i)
|
var get_values = this.AdjList.get(i);
|
||||||
var conc = ''
|
var conc = "";
|
||||||
|
|
||||||
// iterate over the adjacency list
|
// iterate over the adjacency list
|
||||||
// concatenate the values into a string
|
// concatenate the values into a string
|
||||||
for (var j of get_values) { conc += j + ' ' }
|
for (var j of get_values)
|
||||||
|
conc += j + " ";
|
||||||
|
|
||||||
// print the vertex and its adjacency list
|
// print the vertex and its adjacency list
|
||||||
console.log(i + ' -> ' + conc)
|
console.log(i + " -> " + conc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Example
|
// Example
|
||||||
var graph = new Graph(6)
|
var graph = new Graph(6);
|
||||||
var vertices = ['A', 'B', 'C', 'D', 'E', 'F']
|
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];
|
||||||
|
|
||||||
// adding vertices
|
// adding vertices
|
||||||
for (var i = 0; i < vertices.length; i++) {
|
for (var i = 0; i < vertices.length; i++) {
|
||||||
g.addVertex(vertices[i])
|
g.addVertex(vertices[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// adding edges
|
// adding edges
|
||||||
g.addEdge('A', 'B')
|
g.addEdge('A', 'B');
|
||||||
g.addEdge('A', 'D')
|
g.addEdge('A', 'D');
|
||||||
g.addEdge('A', 'E')
|
g.addEdge('A', 'E');
|
||||||
g.addEdge('B', 'C')
|
g.addEdge('B', 'C');
|
||||||
g.addEdge('D', 'E')
|
g.addEdge('D', 'E');
|
||||||
g.addEdge('E', 'F')
|
g.addEdge('E', 'F');
|
||||||
g.addEdge('E', 'C')
|
g.addEdge('E', 'C');
|
||||||
g.addEdge('C', 'F')
|
g.addEdge('C', 'F');
|
||||||
|
|
||||||
// prints all vertex and
|
// prints all vertex and
|
||||||
// its adjacency list
|
// its adjacency list
|
||||||
@ -86,4 +91,5 @@ g.addEdge('C', 'F')
|
|||||||
// D -> A E
|
// D -> A E
|
||||||
// E -> A D F C
|
// E -> A D F C
|
||||||
// F -> E C
|
// F -> E C
|
||||||
g.printGraph()
|
g.printGraph();
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user