From cf4f22073c5eab07e297bf48e1bb8f086c64245b Mon Sep 17 00:00:00 2001
From: Ozlem <95313700+OzPol@users.noreply.github.com>
Date: Wed, 25 Sep 2024 16:21:25 -0400
Subject: [PATCH 06/58] Fix: Updated logos for missing algorithm
implementations
Replaced C and Python logos with GitHub logo for the following algorithms with missing implementations:
A* Algorithm
Bellman-Ford Algorithm
Ford-Fulkerson Algorithm
Gale-Shapley Algorithm
Hungarian Algorithm
Kruskal's Algorithm
Prim's Algorithm
Topological Sort
AVL Tree
Red-Black Tree
---
README.md | 36 ++++++++++++++++++------------------
1 file changed, 18 insertions(+), 18 deletions(-)
diff --git a/README.md b/README.md
index 1db56218..69bf752f 100644
--- a/README.md
+++ b/README.md
@@ -68,7 +68,7 @@ In order to achieve greater coverage and encourage more people to contribute to
A* Algorithm |
-
+
|
@@ -83,7 +83,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -126,7 +126,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Bellman-Ford Algorithm |
-
+
|
@@ -822,7 +822,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Ford-Fulkerson Algorithm |
-
+
|
@@ -837,7 +837,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -880,7 +880,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Gale-Shapley Algorithm |
-
+
|
@@ -895,7 +895,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -1170,7 +1170,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Hungarian Algorithm |
-
+
|
@@ -1185,7 +1185,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -1344,7 +1344,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Kruskal's Algorithm |
-
+
|
@@ -1359,7 +1359,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -1866,7 +1866,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Prim's Algorithm |
-
+
|
@@ -1881,7 +1881,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -2100,7 +2100,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| AVL Tree |
-
+
|
@@ -2115,7 +2115,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -2738,7 +2738,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Red-Black Tree |
-
+
|
@@ -4074,7 +4074,7 @@ In order to achieve greater coverage and encourage more people to contribute to
| Topological Sort |
-
+
|
@@ -4089,7 +4089,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
From 9cb749af7577365ce0e80a8dfd052bd616c39f78 Mon Sep 17 00:00:00 2001
From: Ozlem <95313700+OzPol@users.noreply.github.com>
Date: Wed, 25 Sep 2024 16:32:32 -0400
Subject: [PATCH 07/58] Fix: Updated Python logo placeholders for Red-Black
Tree and Bellman-Ford
Red-Black Tree and Bellman-Ford algorithms python placeholder logos changed to the correct GitHub logo. All logos are now consistent across the new additions.
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 69bf752f..08b49401 100644
--- a/README.md
+++ b/README.md
@@ -141,7 +141,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
@@ -2753,7 +2753,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
From cc8afba4a6f91bf2c3f9957be699e6392fb74b57 Mon Sep 17 00:00:00 2001
From: Hardik Pawar
Date: Wed, 2 Oct 2024 16:16:38 +0530
Subject: [PATCH 08/58] Add Floyd Warshall algorithm in C++
---
README.md | 4 +--
src/cpp/FloydWarshall.cpp | 71 +++++++++++++++++++++++++++++++++++++++
2 files changed, 73 insertions(+), 2 deletions(-)
create mode 100644 src/cpp/FloydWarshall.cpp
diff --git a/README.md b/README.md
index 39ae7d05..bcde5a3d 100644
--- a/README.md
+++ b/README.md
@@ -130,8 +130,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/cpp/FloydWarshall.cpp b/src/cpp/FloydWarshall.cpp
new file mode 100644
index 00000000..0609d7fa
--- /dev/null
+++ b/src/cpp/FloydWarshall.cpp
@@ -0,0 +1,71 @@
+#include
+
+using namespace std;
+
+// Function to display the matrix
+void showMatrix(const vector> &matrix, int numVertices)
+{
+ for (int i = 0; i < numVertices; i++)
+ {
+ for (int j = 0; j < numVertices; j++)
+ {
+ if (matrix[i][j] < 10) // For better alignment
+ cout << " ";
+ cout << matrix[i][j] << " ";
+ }
+ cout << endl;
+ }
+ cout << endl;
+}
+
+// Floyd-Warshall algorithm
+void floydWarshall(vector> &matrix, int n)
+{
+ for (int k = 0; k < n; k++) // Intermediary vertex
+ {
+ for (int i = 0; i < n; i++) // Origin vertex
+ {
+ for (int j = 0; j < n; j++) // Destination vertex
+ {
+ if (matrix[i][k] != LONG_MAX && // i -> k exists
+ matrix[k][j] != LONG_MAX && // k -> j exists
+ matrix[i][j] > matrix[i][k] + matrix[k][j]) // i -> j is shorter via k
+ {
+ matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j
+ }
+ }
+ }
+ }
+}
+
+int main()
+{
+ int numVertices = 5;
+
+ // Initialize matrix with given values
+ vector> matrix = {
+ {0, 2, 10, 5, 7},
+ {2, 0, 3, 3, 1},
+ {10, 3, 0, 1, 2},
+ {5, 3, 1, 0, LONG_MAX},
+ {7, 1, 2, 2, 0}};
+
+ // Display the original matrix
+ cout << "Original matrix:" << endl;
+ showMatrix(matrix, numVertices);
+
+ // Apply Floyd-Warshall algorithm
+ floydWarshall(matrix, numVertices);
+
+ // Display the updated matrix
+ cout << "Updated matrix:" << endl;
+ showMatrix(matrix, numVertices);
+
+ // Show all shortest paths in 3 columns: source, destination, shortest distance
+ cout << "Source\tDestination\tShortest Distance" << endl;
+ for (int i = 0; i < numVertices; i++)
+ for (int j = 0; j < numVertices; j++)
+ cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl;
+
+ return 0;
+}
From 70137b6c1cdf6464d89844fe2e173cb7e1da14ec Mon Sep 17 00:00:00 2001
From: Hardik Pawar
Date: Mon, 7 Oct 2024 16:02:50 +0530
Subject: [PATCH 09/58] Add `GraphSearch.cpp`
---
README.md | 4 +-
src/cpp/GraphSearch.cpp | 135 ++++++++++++++++++++++++++++++++++++++++
2 files changed, 137 insertions(+), 2 deletions(-)
create mode 100644 src/cpp/GraphSearch.cpp
diff --git a/README.md b/README.md
index bcde5a3d..883f27d4 100644
--- a/README.md
+++ b/README.md
@@ -246,8 +246,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/cpp/GraphSearch.cpp b/src/cpp/GraphSearch.cpp
new file mode 100644
index 00000000..4f9d9622
--- /dev/null
+++ b/src/cpp/GraphSearch.cpp
@@ -0,0 +1,135 @@
+#include
+#include
+#include
+
+#define MAX_VERTICES 6 // Maximum number of vertices in the graph
+
+// Structure that defines each Vertex of the Graph
+struct Vertex
+{
+ char id;
+ std::vector neighbors; // List of neighbors
+ bool visited;
+
+ Vertex(char id) : id(id), visited(false) {}
+};
+
+// Creates a vertex and returns it
+Vertex *createVertex(char id)
+{
+ return new Vertex(id);
+}
+
+// Links two vertices (makes them neighbors)
+void linkVertices(Vertex *v1, Vertex *v2)
+{
+ v1->neighbors.push_back(v2); // Add v2 as a neighbor of v1
+ v2->neighbors.push_back(v1); // Add v1 as a neighbor of v2
+}
+
+/*
+ * Depth First Search (DFS)
+ * Recursively visits neighbors of the starting vertex
+ */
+int depthFirstSearch(Vertex *start, Vertex *destination, int steps)
+{
+ start->visited = true; // Mark the current vertex as visited
+ if (start == destination)
+ return steps; // If found, return the distance
+
+ for (Vertex *neighbor : start->neighbors)
+ { // Visit all neighbors
+ if (!neighbor->visited)
+ { // If neighbor hasn't been visited
+ int result = depthFirstSearch(neighbor, destination, steps + 1);
+ if (result != -1)
+ return result; // If destination found, return result
+ }
+ }
+ return -1; // Destination not found
+}
+
+/*
+ * Breadth First Search (BFS)
+ * Uses a queue to traverse level by level
+ */
+int breadthFirstSearch(Vertex *start, Vertex *destination)
+{
+ std::queue q;
+ q.push(start); // Enqueue starting vertex
+ start->visited = true;
+
+ int steps = 0;
+
+ while (!q.empty())
+ {
+ int qSize = q.size(); // Current queue size (level size)
+
+ // Process all vertices at the current level
+ for (int i = 0; i < qSize; i++)
+ {
+ Vertex *current = q.front();
+ q.pop();
+
+ if (current == destination)
+ return steps; // If destination found, return steps
+
+ // Enqueue all unvisited neighbors
+ for (Vertex *neighbor : current->neighbors)
+ {
+ if (!neighbor->visited)
+ {
+ neighbor->visited = true;
+ q.push(neighbor);
+ }
+ }
+ }
+ steps++; // Increment the level
+ }
+ return -1; // Destination not found
+}
+
+int main()
+{
+ // Create vertices
+ Vertex *A = createVertex('A');
+ Vertex *B = createVertex('B');
+ Vertex *C = createVertex('C');
+ Vertex *D = createVertex('D');
+ Vertex *E = createVertex('E');
+ Vertex *F = createVertex('F');
+
+ // Link vertices as per the graph structure
+ linkVertices(A, B);
+ linkVertices(A, C);
+ linkVertices(B, D);
+ linkVertices(C, D);
+ linkVertices(B, E);
+ linkVertices(D, E);
+ linkVertices(E, F);
+ linkVertices(D, F);
+
+ // Perform Depth First Search
+ int result = depthFirstSearch(A, F, 0);
+ if (result != -1)
+ std::cout << "DFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "DFS - Not Found." << std::endl;
+
+ // Reset visited status for all vertices
+ A->visited = false;
+ B->visited = false;
+ C->visited = false;
+ D->visited = false;
+ E->visited = false;
+ F->visited = false;
+
+ // Perform Breadth First Search
+ result = breadthFirstSearch(A, F);
+ if (result != -1)
+ std::cout << "BFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "BFS - Not Found." << std::endl;
+
+ return 0;
+}
From bfb7e9a09390d945bed968a848587f540b108e6c Mon Sep 17 00:00:00 2001
From: Hardik Pawar
Date: Mon, 7 Oct 2024 16:07:27 +0530
Subject: [PATCH 10/58] Add `ConnectedComponents.cpp`
---
README.md | 4 +--
src/cpp/ConnectedComponents.cpp | 53 +++++++++++++++++++++++++++++++++
2 files changed, 55 insertions(+), 2 deletions(-)
create mode 100644 src/cpp/ConnectedComponents.cpp
diff --git a/README.md b/README.md
index bcde5a3d..1989c20b 100644
--- a/README.md
+++ b/README.md
@@ -652,8 +652,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/cpp/ConnectedComponents.cpp b/src/cpp/ConnectedComponents.cpp
new file mode 100644
index 00000000..ac565f58
--- /dev/null
+++ b/src/cpp/ConnectedComponents.cpp
@@ -0,0 +1,53 @@
+#include
+#include
+
+#define VERTICES 6
+#define INF -1
+
+std::vector visited(VERTICES, false); // Array to track visited vertices
+int components = 0;
+
+// Adjacency matrix representing the graph
+int matrix[VERTICES][VERTICES] = {{0, INF, 1, INF, INF, INF},
+ {INF, 0, INF, 1, 1, INF},
+ {1, INF, 0, INF, INF, INF},
+ {INF, 1, INF, 0, 1, 1},
+ {INF, 1, INF, 1, 0, 1},
+ {INF, INF, INF, 1, 1, 0}};
+
+// Recursive method to find connected components using adjacency matrix
+void findConnectedComponents(int current)
+{
+ for (int i = 0; i < VERTICES; i++)
+ {
+ if (!visited[i] && matrix[current][i] == 1)
+ {
+ visited[i] = true;
+ components++;
+ std::cout << "(" << i << ")-";
+ findConnectedComponents(i);
+ }
+ }
+}
+
+int main()
+{
+ // Initialize all vertices as unvisited
+ for (int i = 0; i < VERTICES; i++)
+ visited[i] = false;
+
+ // For each vertex, if it is unvisited, start a DFS and count components
+ for (int i = 0; i < VERTICES; i++)
+ {
+ if (!visited[i])
+ {
+ components = 0;
+ visited[i] = true;
+ std::cout << "Starting at vertex (" << i << ")-";
+ findConnectedComponents(i);
+ std::cout << "\nNumber of connected components starting from vertex " << i << ": " << components << "\n\n";
+ }
+ }
+
+ return 0;
+}
From 01d67edc71625a7ceb0d5f3c2ddb6924d38a3885 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 18 Oct 2024 15:46:45 -0300
Subject: [PATCH 11/58] Add bogosort in Scala
---
README.md | 4 ++--
src/scala/Bogosort.scala | 25 +++++++++++++++++++++++++
2 files changed, 27 insertions(+), 2 deletions(-)
create mode 100644 src/scala/Bogosort.scala
diff --git a/README.md b/README.md
index ac4442ac..68229401 100644
--- a/README.md
+++ b/README.md
@@ -3248,8 +3248,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/scala/Bogosort.scala b/src/scala/Bogosort.scala
new file mode 100644
index 00000000..fb4e1c4d
--- /dev/null
+++ b/src/scala/Bogosort.scala
@@ -0,0 +1,25 @@
+import scala.annotation.tailrec
+import scala.util.Random
+
+
+@tailrec
+def isSorted(data: Seq[Int]): Boolean = {
+ if (data.size < 2) true
+ else if (data(0) > data(1)) false
+ else isSorted(data.tail)
+}
+
+
+@tailrec
+def bogosort(data: Seq[Int]): Seq[Int] = {
+ val result: Seq[Int] = Random.shuffle(data)
+ if (isSorted(result)) result
+ else bogosort(data)
+}
+
+
+object Main extends App {
+ val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10))
+ println(s"Unsorted data: $data")
+ println(s"Sorted data: ${bogosort(data)}")
+}
From a108059b92d528ff0fae0d346b5c007108936297 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 18 Oct 2024 15:56:40 -0300
Subject: [PATCH 12/58] Apply scalfmt to Bogosort.scala
---
src/scala/Bogosort.scala | 22 ++++++++++------------
1 file changed, 10 insertions(+), 12 deletions(-)
diff --git a/src/scala/Bogosort.scala b/src/scala/Bogosort.scala
index fb4e1c4d..63ab3bb7 100644
--- a/src/scala/Bogosort.scala
+++ b/src/scala/Bogosort.scala
@@ -1,25 +1,23 @@
import scala.annotation.tailrec
import scala.util.Random
-
@tailrec
def isSorted(data: Seq[Int]): Boolean = {
- if (data.size < 2) true
- else if (data(0) > data(1)) false
- else isSorted(data.tail)
+ if (data.size < 2) true
+ else if (data(0) > data(1)) false
+ else isSorted(data.tail)
}
-
@tailrec
def bogosort(data: Seq[Int]): Seq[Int] = {
- val result: Seq[Int] = Random.shuffle(data)
- if (isSorted(result)) result
- else bogosort(data)
+ val result: Seq[Int] = Random.shuffle(data)
+ if (isSorted(result)) result
+ else bogosort(data)
}
-
object Main extends App {
- val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10))
- println(s"Unsorted data: $data")
- println(s"Sorted data: ${bogosort(data)}")
+ val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10))
+ println(s"Unsorted data: $data")
+ println(s"Sorted data: ${bogosort(data)}")
}
+
From 5bc31f45552350a69c29b0bf3b82a7111acb0b8d Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 18 Oct 2024 16:17:25 -0300
Subject: [PATCH 13/58] Fix Bogosort.scala formatting
---
src/scala/Bogosort.scala | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/scala/Bogosort.scala b/src/scala/Bogosort.scala
index 63ab3bb7..8a390de8 100644
--- a/src/scala/Bogosort.scala
+++ b/src/scala/Bogosort.scala
@@ -20,4 +20,3 @@ object Main extends App {
println(s"Unsorted data: $data")
println(s"Sorted data: ${bogosort(data)}")
}
-
From 5418241086a4787fe72bb5b7c5ec5f38d610be8a Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 15:36:42 -0300
Subject: [PATCH 14/58] Create BinarySearch in Scala
---
README.md | 4 ++--
src/scala/BinarySearch.scala | 23 +++++++++++++++++++++++
2 files changed, 25 insertions(+), 2 deletions(-)
create mode 100644 src/scala/BinarySearch.scala
diff --git a/README.md b/README.md
index 68229401..976fb00e 100644
--- a/README.md
+++ b/README.md
@@ -228,8 +228,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
new file mode 100644
index 00000000..693a2f84
--- /dev/null
+++ b/src/scala/BinarySearch.scala
@@ -0,0 +1,23 @@
+import scala.annotation.tailrec
+
+def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
+ @tailrec
+ def search(left: Int, right: Int): Option[Int] = {
+ if (left > right) None
+ else {
+ val middle: Int = (left + right) / 2
+ if (data(middle) == target) Some(middle)
+ else if (data(middle) < target) search(middle + 1, right)
+ else search(left, middle - 1)
+ }
+ }
+ search(0, data.size)
+}
+
+object Main extends App {
+ val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
+ val value: Int = 11
+ println(
+ s"Value '$value' found in position '${binarySearch(data, value).get}'"
+ )
+}
From 7945b36c4ac516d161d5a68097e9691a013e6617 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 15:49:07 -0300
Subject: [PATCH 15/58] Add blank line
---
src/scala/BinarySearch.scala | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index 693a2f84..2cacac6c 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -1,6 +1,7 @@
import scala.annotation.tailrec
def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
+
@tailrec
def search(left: Int, right: Int): Option[Int] = {
if (left > right) None
From e71ecf870f41c5009a27c41c7e0490a53828994a Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 15:54:44 -0300
Subject: [PATCH 16/58] Try to fix BinarySearch.scala
---
src/scala/BinarySearch.scala | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index 2cacac6c..c0261366 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -12,13 +12,12 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
else search(left, middle - 1)
}
}
+
search(0, data.size)
}
object Main extends App {
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
val value: Int = 11
- println(
- s"Value '$value' found in position '${binarySearch(data, value).get}'"
- )
+ println(s"Value '$value' found in position '${binarySearch(data, value).get}'")
}
From 0d3570ce6eaf63cabb75d68d150e69888b087bba Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 16:00:47 -0300
Subject: [PATCH 17/58] Try to fix BinarySearch.scala
---
src/scala/BinarySearch.scala | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index c0261366..2b723eb7 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -4,6 +4,7 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
@tailrec
def search(left: Int, right: Int): Option[Int] = {
+
if (left > right) None
else {
val middle: Int = (left + right) / 2
@@ -17,6 +18,7 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
}
object Main extends App {
+
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
val value: Int = 11
println(s"Value '$value' found in position '${binarySearch(data, value).get}'")
From 22742fbde249d6319d0350a3bd888822cd624ec4 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 16:07:03 -0300
Subject: [PATCH 18/58] Try to fix BinarySearch.scala
---
src/scala/BinarySearch.scala | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index 2b723eb7..5cc64586 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -4,9 +4,9 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
@tailrec
def search(left: Int, right: Int): Option[Int] = {
-
- if (left > right) None
- else {
+ if (left > right) {
+ None
+ } else {
val middle: Int = (left + right) / 2
if (data(middle) == target) Some(middle)
else if (data(middle) < target) search(middle + 1, right)
@@ -18,7 +18,6 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
}
object Main extends App {
-
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
val value: Int = 11
println(s"Value '$value' found in position '${binarySearch(data, value).get}'")
From f9ed5e976e7d83713c57eeea062323eaf6d4343b Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Mon, 21 Oct 2024 16:21:03 -0300
Subject: [PATCH 19/58] Try to fix BinarySearch.scala
---
src/scala/BinarySearch.scala | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index 5cc64586..daa77f75 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -19,6 +19,6 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
object Main extends App {
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
- val value: Int = 11
+ val value: Int = 11
println(s"Value '$value' found in position '${binarySearch(data, value).get}'")
}
From 390e9de26f57cc64389937be111528fc5b14a67a Mon Sep 17 00:00:00 2001
From: DavdaJames
Date: Tue, 22 Oct 2024 18:15:27 +0530
Subject: [PATCH 20/58] translated travelling salesman problem to english
---
src/c/TravellingSalesman.c | 132 ++++++++++++++++++-------------------
1 file changed, 63 insertions(+), 69 deletions(-)
diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c
index b7924423..570bccb2 100644
--- a/src/c/TravellingSalesman.c
+++ b/src/c/TravellingSalesman.c
@@ -1,7 +1,7 @@
/*
-* Problema do Caixeiro Viajante em C
-* Utilizando uma matriz de distância para representar um grafo não direcionado.
-* Objetivo: Encontrar o menor caminho que passe por todos os vértices sem repetir nenhum, e chegar novamente ao vértice de início
+* Traveling Salesman Problem in C
+* Using a distance matrix to represent an undirected graph.
+* Objective: Find the shortest path that visits all vertices without repeating any, and returns to the starting vertex.
*
* 6
* (4)-----(0)
@@ -16,92 +16,86 @@
* | | 3
* --------------
*
-*
-* Matriz de Distância
+* Distance Matrix
* 0 1 2 3 4
* 0 0 2 - 3 6
* 1 2 0 4 3 -
* 2 - 4 0 7 3
* 3 3 3 7 0 3
* 4 6 - 3 3 0
-*
-*
*/
#include
#define VERTICES 5
-#define INFINITO 429496729
-
-int tempSolucao[VERTICES];
-int melhorSolucao[VERTICES];
-bool visitados[VERTICES];
-int valorMelhorSolucao = INFINITO;
-int valorSolucaoAtual = 0;
+#define INFINITY 429496729
-int matriz[VERTICES][VERTICES] = {{ 0, 2, INFINITO, 3, 6 },
- { 2, 0, 4, 3, INFINITO },
- { INFINITO, 4, 0, 7, 3 },
- { 3, 3, 7, 0, 3 },
- { 6, INFINITO, 3, 3, 0 }};
+int tempSolution[VERTICES];
+int bestSolution[VERTICES];
+bool visited[VERTICES];
+int bestSolutionValue = INFINITY;
+int currentSolutionValue = 0;
-void caixeiroViajanteAux(int x){
- // Se o valor da solução atual já estiver maior que o valor da melhor solução já para, pois já não pode mais ser a melhor solução
- if( valorSolucaoAtual > valorMelhorSolucao )
- return;
+int matrix[VERTICES][VERTICES] = {{ 0, 2, INFINITY, 3, 6 },
+ { 2, 0, 4, 3, INFINITY },
+ { INFINITY, 4, 0, 7, 3 },
+ { 3, 3, 7, 0, 3 },
+ { 6, INFINITY, 3, 3, 0 }};
- if( x == VERTICES ){ // Se x == VERTICES significa que o vetor da solução temporária está completo
- int distancia = matriz[tempSolucao[x-1]][tempSolucao[0]];
- // Se encontrou uma solução melhor/menor
- if( distancia < INFINITO && valorSolucaoAtual + distancia < valorMelhorSolucao ){
- valorMelhorSolucao = valorSolucaoAtual + distancia; // Substitui a melhor solução pela melhor encontrada agora
- // Copia todo o vetor de solução temporária para o vetor de melhor solução encontrada
- for (int i = 0; i < VERTICES; ++i){
- melhorSolucao[i] = tempSolucao[i];
- }
- }
- return;
- }
+void travelingSalesmanAux(int x) {
+ // If the current solution value is already greater than the best solution, stop as it can't be the best solution
+ if (currentSolutionValue > bestSolutionValue)
+ return;
- int ultimo = tempSolucao[x-1]; // Ultimo recebe o número do último vértice que se encontra na solução temporária
- // For que percorre todas as colunas da matriz na linha do último vértice do vetor solução temporária
- for (int i = 0; i < VERTICES; i++){
- // Se a posição i do vetor ainda não foi visitada, e se o valor da matriz na posição é menor que INFINITO
- if( visitados[i] == false && matriz[ultimo][i] < INFINITO ){
- visitados[i] = true; // Marca como visitado
- tempSolucao[x] = i; // Carrega o vértice que está passando no vetor de solução temporária
- valorSolucaoAtual += matriz[ultimo][i]; // Incrementa o valor da matriz na variável que guarda o total do caminho percorrido
- caixeiroViajanteAux(x+1); // Chama recursivamente para o próximo vértice
- valorSolucaoAtual -= matriz[ultimo][i]; // Se ainda não terminou, diminuí o valor da váriavel que guarda o total da solução atual
- visitados[i] = false; // Seta como false a posição para poder ser utilizado por outro vértice
- }
-
- }
+ if (x == VERTICES) { // If x == VERTICES, it means the temporary solution array is complete
+ int distance = matrix[tempSolution[x-1]][tempSolution[0]];
+ // If a better (shorter) solution is found
+ if (distance < INFINITY && currentSolutionValue + distance < bestSolutionValue) {
+ bestSolutionValue = currentSolutionValue + distance; // Update the best solution with the new better one
+ // Copy the entire temporary solution array to the best solution array
+ for (int i = 0; i < VERTICES; ++i) {
+ bestSolution[i] = tempSolution[i];
+ }
+ }
+ return;
+ }
+ int last = tempSolution[x-1]; // 'last' holds the number of the last vertex in the temporary solution array
+ // Loop through all columns in the matrix on the row of the last vertex in the temporary solution array
+ for (int i = 0; i < VERTICES; i++) {
+ // If the i-th vertex hasn't been visited, and the matrix value is less than INFINITY
+ if (!visited[i] && matrix[last][i] < INFINITY) {
+ visited[i] = true; // Mark as visited
+ tempSolution[x] = i; // Add the current vertex to the temporary solution array
+ currentSolutionValue += matrix[last][i]; // Increment the path total
+ travelingSalesmanAux(x + 1); // Recursively call for the next vertex
+ currentSolutionValue -= matrix[last][i]; // Decrease the path total if not finished yet
+ visited[i] = false; // Mark the vertex as unvisited so it can be used again by another vertex
+ }
+ }
}
-void caixeiroViajante(int inicial){
- visitados[inicial] = true; // Marca o primeiro vértice como visitado (0)
- tempSolucao[0] = inicial; // Coloca o vértice 0 na primeira posição do vetor de solução temporária
- caixeiroViajanteAux(1); // Chama o método auxiliar do caixeiro viajante
+void travelingSalesman(int start) {
+ visited[start] = true; // Mark the starting vertex as visited (0)
+ tempSolution[0] = start; // Place vertex 0 in the first position of the temporary solution array
+ travelingSalesmanAux(1); // Call the auxiliary function for the traveling salesman problem
}
-void iniciaVetores(){
- for (int i = 0; i < VERTICES; i++){
- visitados[i] = false;
- tempSolucao[i] = -1;
- melhorSolucao[i] = -1;
- }
+void initializeArrays() {
+ for (int i = 0; i < VERTICES; i++) {
+ visited[i] = false;
+ tempSolution[i] = -1;
+ bestSolution[i] = -1;
+ }
}
-int main(){
-
- iniciaVetores();
- caixeiroViajante(0);
+int main() {
+ initializeArrays();
+ travelingSalesman(0);
- printf("Caminho mínimo: %d\n", valorMelhorSolucao);
- for (int i = 0; i < VERTICES; i++){
- printf("%d, ", melhorSolucao[i]);
- }
- printf("\n\n");
-}
\ No newline at end of file
+ printf("Minimum path cost: %d\n", bestSolutionValue);
+ for (int i = 0; i < VERTICES; i++) {
+ printf("%d, ", bestSolution[i]);
+ }
+ printf("\n\n");
+}
From 535b3f141d4e61e0f53376ea89ab8b513c808312 Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Tue, 22 Oct 2024 14:49:48 -0300
Subject: [PATCH 21/58] Update TravellingSalesman.c
---
src/c/TravellingSalesman.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c
index 570bccb2..46d435e9 100644
--- a/src/c/TravellingSalesman.c
+++ b/src/c/TravellingSalesman.c
@@ -26,6 +26,7 @@
*/
#include
+#include
#define VERTICES 5
#define INFINITY 429496729
From c136244f750706a2ca860c87d76d2a74f155d655 Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Wed, 23 Oct 2024 09:28:20 -0300
Subject: [PATCH 22/58] Update README.md
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 976fb00e..03c28ff1 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
# :abacus: Algorithms and Data Structures
+[](https://github.com/marketplace/actions/super-linter)
+
This repository provides several classic algorithms and data structures in **Computer Science**, as well as some extra problems that are frequently encountered in programming challenges.
In order to achieve greater coverage and encourage more people to contribute to the project, the algorithms are available in the following languages: **C**, **C++**, **Java**, **Python**, **Go**, **Ruby**, **Javascript**, **Swift**, **Rust**, **Scala** and **Kotlin**.
From 788cc11561bbc8b96696d88bedc22ff083b04181 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 09:36:38 -0300
Subject: [PATCH 23/58] Try to fix BinarySearch.scala
---
src/scala/BinarySearch.scala | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala
index daa77f75..2088863d 100644
--- a/src/scala/BinarySearch.scala
+++ b/src/scala/BinarySearch.scala
@@ -20,5 +20,7 @@ def binarySearch(data: Seq[Int], target: Int): Option[Int] = {
object Main extends App {
val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12)
val value: Int = 11
- println(s"Value '$value' found in position '${binarySearch(data, value).get}'")
+ println(
+ s"Value '$value' found in position '${binarySearch(data, value).get}'"
+ )
}
From b5c0e1f51b732bab64574f417371f72a62cfbc32 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 09:36:59 -0300
Subject: [PATCH 24/58] Remove super-linter badge
---
README.md | 2 --
1 file changed, 2 deletions(-)
diff --git a/README.md b/README.md
index 03c28ff1..976fb00e 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,5 @@
# :abacus: Algorithms and Data Structures
-[](https://github.com/marketplace/actions/super-linter)
-
This repository provides several classic algorithms and data structures in **Computer Science**, as well as some extra problems that are frequently encountered in programming challenges.
In order to achieve greater coverage and encourage more people to contribute to the project, the algorithms are available in the following languages: **C**, **C++**, **Java**, **Python**, **Go**, **Ruby**, **Javascript**, **Swift**, **Rust**, **Scala** and **Kotlin**.
From 2a5549351066d1a2bb7aa02d66c88336d9c867cf Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 09:42:30 -0300
Subject: [PATCH 25/58] Format C code using CLANG_FORMAT
---
src/c/BinarySearch.c | 56 ++---
src/c/BinarySearchTree.c | 351 +++++++++++++++--------------
src/c/BinaryTree.c | 278 +++++++++++------------
src/c/BubbleSort.c | 46 ++--
src/c/CalculatePi.c | 33 ++-
src/c/CircularLinkedList.c | 170 +++++++-------
src/c/ConnectedComponents.c | 108 ++++-----
src/c/CountingSort.c | 85 +++----
src/c/Dijkstra.c | 168 +++++++-------
src/c/DoublyLinkedList.c | 241 ++++++++++----------
src/c/DynamicQueue.c | 104 ++++-----
src/c/DynamicStack.c | 124 +++++-----
src/c/Exponentiation.c | 25 +-
src/c/ExponentiationRecursive.c | 20 +-
src/c/Factorial.c | 38 ++--
src/c/FactorialRecursive.c | 20 +-
src/c/FibonacciIterative.c | 20 +-
src/c/FibonacciMemoization.c | 31 +--
src/c/FibonacciRecursive.c | 20 +-
src/c/FloydWarshall.c | 147 ++++++------
src/c/GraphSearch.c | 388 +++++++++++++++++---------------
src/c/Graphs.c | 209 ++++++++---------
src/c/HamiltonianCycle.c | 238 ++++++++++----------
src/c/Heapsort.c | 105 ++++-----
src/c/InsertionSort.c | 71 +++---
src/c/LinearSearch.c | 23 +-
src/c/LinearSearchRecursive.c | 33 ++-
src/c/LinearSearchSentinel.c | 63 +++---
src/c/MaxRecursive.c | 109 ++++-----
src/c/MergeSort.c | 85 ++++---
src/c/MinMaxDC.c | 66 +++---
src/c/MinMaxIterative.c | 28 +--
src/c/MinMaxRecursive.c | 33 +--
src/c/Palindrome.c | 4 +-
src/c/Queue.c | 112 ++++-----
src/c/QuickSort.c | 112 ++++-----
src/c/RadixSort.c | 95 ++++----
src/c/SelectionSort.c | 54 ++---
src/c/SinglyLinkedList.c | 374 +++++++++++++++---------------
src/c/SortedLinkedList.c | 172 +++++++-------
src/c/Stack.c | 126 +++++------
src/c/Timsort.c | 186 ++++++++-------
src/c/TowerOfHanoi.c | 25 +-
src/c/TravellingSalesman.c | 158 +++++++------
src/c/TwoSum.c | 94 ++++----
src/c/UnorderedLinkedList.c | 125 +++++-----
46 files changed, 2589 insertions(+), 2584 deletions(-)
diff --git a/src/c/BinarySearch.c b/src/c/BinarySearch.c
index ae9e5cf5..4ab19f5d 100644
--- a/src/c/BinarySearch.c
+++ b/src/c/BinarySearch.c
@@ -1,43 +1,43 @@
-#include
+#include
int BinarySearch(int array[], int size, int value) {
- int start = 0;
- int end = size - 1;
- int middle = end / 2;
+ int start = 0;
+ int end = size - 1;
+ int middle = end / 2;
- while (start < end && array[middle] != value) {
- // new start
- if (value > array[middle])
- start = middle + 1;
+ while (start < end && array[middle] != value) {
+ // new start
+ if (value > array[middle])
+ start = middle + 1;
- // new end
- if (value < array[middle])
- end = middle - 1;
+ // new end
+ if (value < array[middle])
+ end = middle - 1;
- // new middle
- middle = (start + end) / 2;
- }
+ // new middle
+ middle = (start + end) / 2;
+ }
- if (array[middle] == value)
- return middle;
+ if (array[middle] == value)
+ return middle;
- return -1;
+ return -1;
}
int main() {
- int value;
- int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
- size_t size = sizeof(array) / sizeof(array[0]);
+ int value;
+ int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
+ size_t size = sizeof(array) / sizeof(array[0]);
- printf("Please provide the number you want to value for: ");
- scanf("%d", &value);
+ printf("Please provide the number you want to value for: ");
+ scanf("%d", &value);
- int pos = BinarySearch(array, size, value);
+ int pos = BinarySearch(array, size, value);
- if (pos != -1)
- printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
- else
- printf("Not found\n");
+ if (pos != -1)
+ printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
+ else
+ printf("Not found\n");
- return 0;
+ return 0;
}
diff --git a/src/c/BinarySearchTree.c b/src/c/BinarySearchTree.c
index e29bb525..bce19184 100644
--- a/src/c/BinarySearchTree.c
+++ b/src/c/BinarySearchTree.c
@@ -1,207 +1,214 @@
/*
-* Árvore Binária de Busca em C
-*
-* ( 6 )
-* / \
-* ( 2 ) ( 7 )
-* / \ \
-*( 1 ) ( 4 ) ( 8 )
-* / \
-* ( 3 ) ( 5 )
-*/
+ * Árvore Binária de Busca em C
+ *
+ * ( 6 )
+ * / \
+ * ( 2 ) ( 7 )
+ * / \ \
+ *( 1 ) ( 4 ) ( 8 )
+ * / \
+ * ( 3 ) ( 5 )
+ */
-#include
#include
+#include
typedef int TIPOCHAVE;
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX *esq, *dir;
-}NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *esq, *dir;
+} NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO
-int max(int a, int b){
- if( a > b )
- return a;
- return b;
+int max(int a, int b) {
+ if (a > b)
+ return a;
+ return b;
}
-int altura(PONT no){
- if( no == NULL ) // Mesma coisa que usar if(!no)
- return 0;
- return 1 + max( altura(no->esq), altura(no->dir) ); // Percorre a arvore pela esquerda e pela direita para ver qual tem altura maior
+int altura(PONT no) {
+ if (no == NULL) // Mesma coisa que usar if(!no)
+ return 0;
+ return 1 + max(altura(no->esq),
+ altura(no->dir)); // Percorre a arvore pela esquerda e pela
+ // direita para ver qual tem altura maior
}
-PONT buscaBinaria(TIPOCHAVE ch, PONT raiz){
- if( !raiz )
- return NULL;
- if( raiz->chave == ch )
- return raiz;
- if( raiz->chave < ch )
- buscaBinaria(ch, raiz->dir);
- else
- buscaBinaria(ch, raiz->esq);
+PONT buscaBinaria(TIPOCHAVE ch, PONT raiz) {
+ if (!raiz)
+ return NULL;
+ if (raiz->chave == ch)
+ return raiz;
+ if (raiz->chave < ch)
+ buscaBinaria(ch, raiz->dir);
+ else
+ buscaBinaria(ch, raiz->esq);
}
-PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual){
- while( atual != NULL ){
- if( atual->chave == ch )
- return atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- return NULL;
+PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual) {
+ while (atual != NULL) {
+ if (atual->chave == ch)
+ return atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ return NULL;
}
-PONT criaNo(TIPOCHAVE ch){
- PONT no = (PONT) malloc( sizeof(NO) );
- no->esq = NULL;
- no->dir = NULL;
- no->chave = ch;
- return no;
+PONT criaNo(TIPOCHAVE ch) {
+ PONT no = (PONT)malloc(sizeof(NO));
+ no->esq = NULL;
+ no->dir = NULL;
+ no->chave = ch;
+ return no;
}
-bool inserir(TIPOCHAVE ch, PONT atual){
- PONT ant;
- // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL (vazia)
- while(atual != NULL){
- ant = atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando'
- if( ant->chave < ch )
- ant->dir = atual;
- else
- ant->esq = atual;
- return true;
+bool inserir(TIPOCHAVE ch, PONT atual) {
+ PONT ant;
+ // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL
+ // (vazia)
+ while (atual != NULL) {
+ ant = atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando'
+ if (ant->chave < ch)
+ ant->dir = atual;
+ else
+ ant->esq = atual;
+ return true;
}
-PONT buscaNoPai(TIPOCHAVE ch, PONT atual){
- PONT noPai = atual;
- while( atual != NULL ){
- if( atual->chave == ch )
- return noPai;
- noPai = atual;
- if( atual->chave < ch )
- atual = atual->dir;
- else
- atual = atual->esq;
- }
- return noPai;
+PONT buscaNoPai(TIPOCHAVE ch, PONT atual) {
+ PONT noPai = atual;
+ while (atual != NULL) {
+ if (atual->chave == ch)
+ return noPai;
+ noPai = atual;
+ if (atual->chave < ch)
+ atual = atual->dir;
+ else
+ atual = atual->esq;
+ }
+ return noPai;
}
-PONT maiorAesquerda(PONT atual){
- atual = atual->esq;
- while( atual->dir != NULL )
- atual = atual->dir;
- return atual;
+PONT maiorAesquerda(PONT atual) {
+ atual = atual->esq;
+ while (atual->dir != NULL)
+ atual = atual->dir;
+ return atual;
}
-bool excluir(TIPOCHAVE ch, PONT raiz){
- PONT atual, noPai, substituto, paiSubstituto;
- substituto = NULL;
- atual = buscaBinaria(ch, raiz);
- if( atual == NULL ) return false; // Não encontrou a chave
- noPai = buscaNoPai(ch, raiz);
- if( atual->esq == NULL || atual->dir == NULL ){ // Se tem 0 ou 1 filho
- if( atual->esq == NULL )
- substituto = atual->dir;
- else
- substituto = atual->esq;
- if( noPai == NULL ){ // Único que não tem pai é a raiz
- raiz = substituto;
- }else{
- if( ch < noPai->chave)
- noPai->esq = substituto;
- else
- noPai->dir = substituto;
- }
- free(atual);
- }else{
- substituto = maiorAesquerda(atual);
- atual->chave = substituto->chave;
- if( substituto->esq != NULL )
- atual->esq = substituto->esq;
- else
- atual->esq = NULL;
- free(substituto);
- }
- return true;
+bool excluir(TIPOCHAVE ch, PONT raiz) {
+ PONT atual, noPai, substituto, paiSubstituto;
+ substituto = NULL;
+ atual = buscaBinaria(ch, raiz);
+ if (atual == NULL)
+ return false; // Não encontrou a chave
+ noPai = buscaNoPai(ch, raiz);
+ if (atual->esq == NULL || atual->dir == NULL) { // Se tem 0 ou 1 filho
+ if (atual->esq == NULL)
+ substituto = atual->dir;
+ else
+ substituto = atual->esq;
+ if (noPai == NULL) { // Único que não tem pai é a raiz
+ raiz = substituto;
+ } else {
+ if (ch < noPai->chave)
+ noPai->esq = substituto;
+ else
+ noPai->dir = substituto;
+ }
+ free(atual);
+ } else {
+ substituto = maiorAesquerda(atual);
+ atual->chave = substituto->chave;
+ if (substituto->esq != NULL)
+ atual->esq = substituto->esq;
+ else
+ atual->esq = NULL;
+ free(substituto);
+ }
+ return true;
}
-void preordem(PONT no){ // R - E - D
- if( !no ) return;
- printf("%d, ", no->chave);
- preordem(no->esq);
- preordem(no->dir);
+void preordem(PONT no) { // R - E - D
+ if (!no)
+ return;
+ printf("%d, ", no->chave);
+ preordem(no->esq);
+ preordem(no->dir);
}
-void posordem(PONT no){ // E - D - R
- if( !no ) return;
- posordem(no->esq);
- posordem(no->dir);
- printf("%d, ", no->chave);
+void posordem(PONT no) { // E - D - R
+ if (!no)
+ return;
+ posordem(no->esq);
+ posordem(no->dir);
+ printf("%d, ", no->chave);
}
-void emordem(PONT no){ // E - R - D
- if( !no ) return;
- emordem(no->esq);
- printf("%d, ", no->chave);
- emordem(no->dir);
+void emordem(PONT no) { // E - R - D
+ if (!no)
+ return;
+ emordem(no->esq);
+ printf("%d, ", no->chave);
+ emordem(no->dir);
}
// Esta função não está funcionando
-bool insereRecursivo(TIPOCHAVE ch, PONT no){
- PONT ant;
- if( !no ){
- no = criaNo(ch);
- }else{
- ant = no;
- if( ch < no->chave )
- insereRecursivo(ch, no->esq);
- else
- insereRecursivo(ch, no->dir);
- }
- if( ant->chave < ch )
- ant->dir = no;
- else
- ant->esq = no;
- return true;
+bool insereRecursivo(TIPOCHAVE ch, PONT no) {
+ PONT ant;
+ if (!no) {
+ no = criaNo(ch);
+ } else {
+ ant = no;
+ if (ch < no->chave)
+ insereRecursivo(ch, no->esq);
+ else
+ insereRecursivo(ch, no->dir);
+ }
+ if (ant->chave < ch)
+ ant->dir = no;
+ else
+ ant->esq = no;
+ return true;
}
-int main(){
- PONT noArvore = criaNo(6);
-
- inserir(2, noArvore);
- inserir(1, noArvore);
- inserir(4, noArvore);
- inserir(7, noArvore);
- inserir(8, noArvore);
- inserir(3, noArvore);
- inserir(5, noArvore);
-
- int valorBuscado = 7;
- if( buscaBinaria(valorBuscado, noArvore) )
- printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave );
- else
- printf("Não encontrou\n");
-
- excluir(4, noArvore);
-
- printf("Pre-ordem: ");
- preordem(noArvore);
- printf("\n");
- printf("Em-ordem: ");
- emordem(noArvore);
- printf("\n");
- printf("Pos-ordem: ");
- posordem(noArvore);
-
- printf("\nAltura: %d\n", altura(noArvore) );
- return 0;
+int main() {
+ PONT noArvore = criaNo(6);
+
+ inserir(2, noArvore);
+ inserir(1, noArvore);
+ inserir(4, noArvore);
+ inserir(7, noArvore);
+ inserir(8, noArvore);
+ inserir(3, noArvore);
+ inserir(5, noArvore);
+
+ int valorBuscado = 7;
+ if (buscaBinaria(valorBuscado, noArvore))
+ printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave);
+ else
+ printf("Não encontrou\n");
+
+ excluir(4, noArvore);
+
+ printf("Pre-ordem: ");
+ preordem(noArvore);
+ printf("\n");
+ printf("Em-ordem: ");
+ emordem(noArvore);
+ printf("\n");
+ printf("Pos-ordem: ");
+ posordem(noArvore);
+
+ printf("\nAltura: %d\n", altura(noArvore));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/BinaryTree.c b/src/c/BinaryTree.c
index 1d7e5a51..b1b6a162 100644
--- a/src/c/BinaryTree.c
+++ b/src/c/BinaryTree.c
@@ -5,198 +5,188 @@
struct No {
- int valor;
- struct No* esquerda;
- struct No* direita;
- int altura;
+ int valor;
+ struct No *esquerda;
+ struct No *direita;
+ int altura;
};
-int altura(struct No *n){
+int altura(struct No *n) {
- if(n == NULL)
- return 0;
- return n->altura;
+ if (n == NULL)
+ return 0;
+ return n->altura;
}
-int max(int a, int b){
- return (a > b)? a : b;
-}
+int max(int a, int b) { return (a > b) ? a : b; }
-struct No* novoNo(int valor){
+struct No *novoNo(int valor) {
- struct No* novoNo = (struct No*)malloc(sizeof(struct No));
+ struct No *novoNo = (struct No *)malloc(sizeof(struct No));
- novoNo->valor = valor;
- novoNo->esquerda = NULL;
- novoNo->direita = NULL;
- novoNo->altura = 1;
-
- return novoNo;
+ novoNo->valor = valor;
+ novoNo->esquerda = NULL;
+ novoNo->direita = NULL;
+ novoNo->altura = 1;
+
+ return novoNo;
}
-struct No* inserir(struct No* raiz, int valor){
+struct No *inserir(struct No *raiz, int valor) {
- if(raiz == NULL){
- return novoNo(valor);
- }
- if(valor <= raiz->valor) {
- raiz->esquerda = inserir(raiz->esquerda, valor);
- }
- else {
- raiz->direita = inserir(raiz->direita, valor);
- }
+ if (raiz == NULL) {
+ return novoNo(valor);
+ }
+ if (valor <= raiz->valor) {
+ raiz->esquerda = inserir(raiz->esquerda, valor);
+ } else {
+ raiz->direita = inserir(raiz->direita, valor);
+ }
- raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
+ raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
- return raiz;
+ return raiz;
}
-int busca(struct No* raiz, int valor){
-
- if(raiz == NULL){
- printf(" Valor [%d] não encontrado.\n", valor);
- }
- else if(raiz->valor == valor){
- printf(" Valor [%d] encontrado.\n", valor);
- }
- else if(valor <= raiz->valor){
- return busca(raiz->esquerda, valor);
- }
- else if(valor >= raiz->valor){
- return busca(raiz->direita, valor);
- }
+int busca(struct No *raiz, int valor) {
+
+ if (raiz == NULL) {
+ printf(" Valor [%d] não encontrado.\n", valor);
+ } else if (raiz->valor == valor) {
+ printf(" Valor [%d] encontrado.\n", valor);
+ } else if (valor <= raiz->valor) {
+ return busca(raiz->esquerda, valor);
+ } else if (valor >= raiz->valor) {
+ return busca(raiz->direita, valor);
+ }
}
-void preorder(struct No* raiz){
+void preorder(struct No *raiz) {
- if(raiz == NULL) return;
- printf("[%d]", raiz->valor);
- preorder(raiz->esquerda);
- preorder(raiz->direita);
+ if (raiz == NULL)
+ return;
+ printf("[%d]", raiz->valor);
+ preorder(raiz->esquerda);
+ preorder(raiz->direita);
}
-void inorder(struct No* raiz){
+void inorder(struct No *raiz) {
- if(raiz == NULL) return;
- inorder(raiz->esquerda);
- printf("[%d]", raiz->valor);
- inorder(raiz->direita);
+ if (raiz == NULL)
+ return;
+ inorder(raiz->esquerda);
+ printf("[%d]", raiz->valor);
+ inorder(raiz->direita);
}
-void postorder(struct No* raiz){
-
- if(raiz == NULL) return;
- postorder(raiz->esquerda);
- postorder(raiz->direita);
- printf("[%d]", raiz->valor);
+void postorder(struct No *raiz) {
+
+ if (raiz == NULL)
+ return;
+ postorder(raiz->esquerda);
+ postorder(raiz->direita);
+ printf("[%d]", raiz->valor);
}
-void levelOrder(struct No* raiz, int level){
+void levelOrder(struct No *raiz, int level) {
- if(raiz == NULL){
- return;
- }
- if(level == 0){
- printf("[%d]", raiz->valor);
- }
- else{
- levelOrder(raiz->esquerda, level-1);
- levelOrder(raiz->direita, level-1);
- }
+ if (raiz == NULL) {
+ return;
+ }
+ if (level == 0) {
+ printf("[%d]", raiz->valor);
+ } else {
+ levelOrder(raiz->esquerda, level - 1);
+ levelOrder(raiz->direita, level - 1);
+ }
}
-void printLevelOrder(struct No* raiz){
- int h = altura(raiz);
- for(int i = 0; i < h; i++){
- levelOrder(raiz, i);
- }
+void printLevelOrder(struct No *raiz) {
+ int h = altura(raiz);
+ for (int i = 0; i < h; i++) {
+ levelOrder(raiz, i);
+ }
}
-struct No* encontraMenor(struct No* raiz){
- struct No* atual = raiz;
- while(atual->esquerda != NULL){
- atual = atual->esquerda;
- }
- return atual;
+struct No *encontraMenor(struct No *raiz) {
+ struct No *atual = raiz;
+ while (atual->esquerda != NULL) {
+ atual = atual->esquerda;
+ }
+ return atual;
}
+struct No *deleta(struct No *raiz, int valor) {
-struct No* deleta(struct No* raiz, int valor){
-
- if(raiz == NULL){
- return raiz;
- }
- if(valor < raiz->valor) {
- raiz->esquerda = deleta(raiz->esquerda, valor);
- }
- else if(valor > raiz->valor){
- raiz->direita = deleta(raiz->direita, valor);
- }
- else{
- if( (raiz->esquerda == NULL) || (raiz->direita == NULL) ){
- struct No* temp = raiz->esquerda ? raiz->esquerda : raiz->direita;
-
- if(temp == NULL){
- temp = raiz;
- raiz = NULL;
- } else{
- *raiz = *temp;
- free(temp);
- }
- }
- else{
- struct No* temp = encontraMenor(raiz->direita);
- raiz->valor = temp->valor;
- raiz->direita = deleta(raiz->direita, temp->valor);
- }
- }
-
- if(raiz == NULL){
- return raiz;
+ if (raiz == NULL) {
+ return raiz;
+ }
+ if (valor < raiz->valor) {
+ raiz->esquerda = deleta(raiz->esquerda, valor);
+ } else if (valor > raiz->valor) {
+ raiz->direita = deleta(raiz->direita, valor);
+ } else {
+ if ((raiz->esquerda == NULL) || (raiz->direita == NULL)) {
+ struct No *temp = raiz->esquerda ? raiz->esquerda : raiz->direita;
+
+ if (temp == NULL) {
+ temp = raiz;
+ raiz = NULL;
+ } else {
+ *raiz = *temp;
+ free(temp);
+ }
+ } else {
+ struct No *temp = encontraMenor(raiz->direita);
+ raiz->valor = temp->valor;
+ raiz->direita = deleta(raiz->direita, temp->valor);
}
+ }
- raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
-
+ if (raiz == NULL) {
return raiz;
-}
+ }
+ raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita));
-int main(void){
+ return raiz;
+}
- struct No* raiz;
- raiz = inserir(raiz, 10);
- raiz = inserir(raiz, 2);
- raiz = inserir(raiz, 33);
- raiz = inserir(raiz, 4);
- raiz = inserir(raiz, 57);
- raiz = inserir(raiz, 6);
- raiz = inserir(raiz, 12);
+int main(void) {
- busca(raiz, 33);
- busca(raiz, 23);
+ struct No *raiz;
+ raiz = inserir(raiz, 10);
+ raiz = inserir(raiz, 2);
+ raiz = inserir(raiz, 33);
+ raiz = inserir(raiz, 4);
+ raiz = inserir(raiz, 57);
+ raiz = inserir(raiz, 6);
+ raiz = inserir(raiz, 12);
- printf("\n Preorder: ");
- preorder(raiz);
+ busca(raiz, 33);
+ busca(raiz, 23);
- printf("\n Inorder: ");
- inorder(raiz);
+ printf("\n Preorder: ");
+ preorder(raiz);
- printf("\n Postorder: ");
- postorder(raiz);
+ printf("\n Inorder: ");
+ inorder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ printf("\n Postorder: ");
+ postorder(raiz);
- raiz = deleta(raiz, 7);
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ raiz = deleta(raiz, 7);
- raiz = deleta(raiz, 6);
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
- printf("\n Levelorder: ");
- printLevelOrder(raiz);
+ raiz = deleta(raiz, 6);
- return 0;
+ printf("\n Levelorder: ");
+ printLevelOrder(raiz);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/BubbleSort.c b/src/c/BubbleSort.c
index 2b083c47..54e8dc44 100644
--- a/src/c/BubbleSort.c
+++ b/src/c/BubbleSort.c
@@ -1,38 +1,32 @@
#include
-void swap(int array[], int j)
-{
- int t = array[j];
- array[j] = array[j + 1];
- array[j + 1] = t;
+void swap(int array[], int j) {
+ int t = array[j];
+ array[j] = array[j + 1];
+ array[j + 1] = t;
}
-void bubble_sort(int array[], int n)
-{
- for (int i = 0; i < n - 1; i++)
- {
- for (int j = 0; j < n - i - 1; j++)
- {
- if (array[j] > array[j + 1])
- {
- swap(array, j);
- }
- }
+void bubble_sort(int array[], int n) {
+ for (int i = 0; i < n - 1; i++) {
+ for (int j = 0; j < n - i - 1; j++) {
+ if (array[j] > array[j + 1]) {
+ swap(array, j);
+ }
}
+ }
}
-int main()
-{
- int array_size = 9;
- int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27};
+int main() {
+ int array_size = 9;
+ int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27};
- bubble_sort(array, array_size);
+ bubble_sort(array, array_size);
- printf("Lista ordenada:\n");
- for (int i = 0; i < array_size - 1; i++)
- printf("%d, ", array[i]);
+ printf("Lista ordenada:\n");
+ for (int i = 0; i < array_size - 1; i++)
+ printf("%d, ", array[i]);
- printf("%d\n", array[array_size - 1]);
+ printf("%d\n", array[array_size - 1]);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CalculatePi.c b/src/c/CalculatePi.c
index a66e63f9..f104a9ff 100644
--- a/src/c/CalculatePi.c
+++ b/src/c/CalculatePi.c
@@ -4,25 +4,22 @@ Calculo de Pi em C
#include
-float leibniz_pi_calculation(int number)
-{
- float denominador = 1.0f;
- float operacao = 1.0f;
- float pi = 0.0f;
- for (int i = 0; i < number; i++)
- {
- pi += operacao * (4.0 / denominador);
- denominador += 2.0;
- operacao = operacao * -1.0;
- }
- return pi;
+float leibniz_pi_calculation(int number) {
+ float denominador = 1.0f;
+ float operacao = 1.0f;
+ float pi = 0.0f;
+ for (int i = 0; i < number; i++) {
+ pi += operacao * (4.0 / denominador);
+ denominador += 2.0;
+ operacao = operacao * -1.0;
+ }
+ return pi;
}
-int main()
-{
- int n_terms[4] = {10, 1000, 100000, 10000000};
- for (int n = 0; n < 4; n++)
- printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n]));
+int main() {
+ int n_terms[4] = {10, 1000, 100000, 10000000};
+ for (int n = 0; n < 4; n++)
+ printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n]));
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CircularLinkedList.c b/src/c/CircularLinkedList.c
index c1ebdfcc..0593d07c 100644
--- a/src/c/CircularLinkedList.c
+++ b/src/c/CircularLinkedList.c
@@ -1,104 +1,114 @@
/*
-*
-* Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica)
-*
-*/
+ *
+ * Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica)
+ *
+ */
-#include
#include
+#include
typedef int TIPOCHAVE; // Tipo de ID de cada nó da lista
// Estrutura de dados que representa cada nó da lista
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX* prox;
-}NO, *PONT;
-
-typedef struct{
- PONT cab; // Nó cabeça
-}LISTA;
-
-void inicializar(LISTA *L){
- // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como sentinela
- L->cab = (PONT) malloc( sizeof(NO) );
- L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *prox;
+} NO, *PONT;
+
+typedef struct {
+ PONT cab; // Nó cabeça
+} LISTA;
+
+void inicializar(LISTA *L) {
+ // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como
+ // sentinela
+ L->cab = (PONT)malloc(sizeof(NO));
+ L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular
}
-// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e não necessáriamente um ponteiro para ela
-PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT* ant){
- *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta (->), o ant guarda o ponteiro para o nó encontrado
- PONT pos = L.cab->prox;
- L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como sentinela, será o último a ser comparado
- while(pos->chave != ch){
- *ant = pos; // Guarda o ponteiro para o nó
- pos = pos->prox; // Vai para o próximo nó
- }
- if( pos != L.cab ) // Se o nó não é o nó cabeça é pq encontrou
- return pos; // Retorna o nó
- else
- return NULL; // Senão não encontrou retorna NULL
+// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e
+// não necessáriamente um ponteiro para ela
+PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT *ant) {
+ *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta
+ // (->), o ant guarda o ponteiro para o nó encontrado
+ PONT pos = L.cab->prox;
+ L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como
+ // sentinela, será o último a ser comparado
+ while (pos->chave != ch) {
+ *ant = pos; // Guarda o ponteiro para o nó
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ if (pos != L.cab) // Se o nó não é o nó cabeça é pq encontrou
+ return pos; // Retorna o nó
+ else
+ return NULL; // Senão não encontrou retorna NULL
}
-bool excluir(TIPOCHAVE ch, LISTA *L){
- PONT aux, ant;
- aux = buscaSequencial(ch, *L, &ant); // Busca o valor para excluir, o ant é passado como endereço de memória, assim a função busca altera ele, guardando o valor anterior
- if( aux == NULL ) return false; // Não encontrou
- ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo que o nó a ser excluído está apontando
- free(aux); // Libera a memória
- return true;
+bool excluir(TIPOCHAVE ch, LISTA *L) {
+ PONT aux, ant;
+ aux = buscaSequencial(ch, *L,
+ &ant); // Busca o valor para excluir, o ant é passado
+ // como endereço de memória, assim a função busca
+ // altera ele, guardando o valor anterior
+ if (aux == NULL)
+ return false; // Não encontrou
+ ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo
+ // que o nó a ser excluído está apontando
+ free(aux); // Libera a memória
+ return true;
}
-void inserir(TIPOCHAVE ch, LISTA *L){
- PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior
- PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual
-
- while(pos->chave < ch && pos != L->cab){
- ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior
- pos = pos->prox; // Vai para o próximo nó
- }
- // Quando encontrou a posição correta na ordem crescente
- PONT novo_no = (PONT) malloc( sizeof(NO) ); // Cria um novo nó
- novo_no->chave = ch; // Coloca a chave no nó
- novo_no->prox = pos; // Aponta para o próximo nó
- ant->prox = novo_no; // Nó anterior aponta para o novo nó
+void inserir(TIPOCHAVE ch, LISTA *L) {
+ PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior
+ PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual
+
+ while (pos->chave < ch && pos != L->cab) {
+ ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ // Quando encontrou a posição correta na ordem crescente
+ PONT novo_no = (PONT)malloc(sizeof(NO)); // Cria um novo nó
+ novo_no->chave = ch; // Coloca a chave no nó
+ novo_no->prox = pos; // Aponta para o próximo nó
+ ant->prox = novo_no; // Nó anterior aponta para o novo nó
}
-PONT mostrarLista(LISTA L){
- PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça
- while(pos != L.cab){ // Se não for o nó cabeça, a lista não está vazia
- printf("[ %d ]->", pos->chave); // Mostra o valor do nó
- pos = pos->prox; // Vai para o próximo nó
- }printf("\n");
+PONT mostrarLista(LISTA L) {
+ PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça
+ while (pos != L.cab) { // Se não for o nó cabeça, a lista não está vazia
+ printf("[ %d ]->", pos->chave); // Mostra o valor do nó
+ pos = pos->prox; // Vai para o próximo nó
+ }
+ printf("\n");
}
-int main(){
-
- LISTA lista;
- inicializar(&lista);
+int main() {
+
+ LISTA lista;
+ inicializar(&lista);
- inserir(4, &lista);
- inserir(6, &lista);
- inserir(2, &lista);
- inserir(3, &lista);
- inserir(1, &lista);
- inserir(5, &lista);
+ inserir(4, &lista);
+ inserir(6, &lista);
+ inserir(2, &lista);
+ inserir(3, &lista);
+ inserir(1, &lista);
+ inserir(5, &lista);
- mostrarLista(lista);
+ mostrarLista(lista);
- excluir(2, &lista);
- excluir(4, &lista);
- excluir(6, &lista);
+ excluir(2, &lista);
+ excluir(4, &lista);
+ excluir(6, &lista);
- mostrarLista(lista);
+ mostrarLista(lista);
- // Exemplo de busca na lista
- PONT aux;
- int valor = 2;
- if( buscaSequencial(valor, lista, &aux) != NULL )
- printf("Valor %d encontrado.\n", valor );
- else
- printf("Valor %d não encontrado.\n", valor);
+ // Exemplo de busca na lista
+ PONT aux;
+ int valor = 2;
+ if (buscaSequencial(valor, lista, &aux) != NULL)
+ printf("Valor %d encontrado.\n", valor);
+ else
+ printf("Valor %d não encontrado.\n", valor);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/ConnectedComponents.c b/src/c/ConnectedComponents.c
index cc3a5507..122f8575 100644
--- a/src/c/ConnectedComponents.c
+++ b/src/c/ConnectedComponents.c
@@ -1,30 +1,31 @@
/*
-*
-* Grafos - Algoritmo para calcular o número de componentes conexos em um determinado Grafo
-*
-* GRAFO
-* (0) (1)-------------(4)---------------(5)
-* | | | |
-* | | | |
-* | | | |
-* (2) (3)--------------- |
-* | |
-* -----------------------------------
-*
-*
-* Matriz de Adjacência
-* 0 1 2 3 4 5
-* 0 0 - 1 - - -
-* 1 - 0 - 1 1 -
-* 2 1 - 0 - - -
-* 3 - 1 - 0 1 1
-* 4 - 1 - 1 0 1
-* 5 - - - 1 1 0
-*
-*
-* 6 Vértices
-* 8 Arestas
-*/
+ *
+ * Grafos - Algoritmo para calcular o número de componentes conexos em um
+ *determinado Grafo
+ *
+ * GRAFO
+ * (0) (1)-------------(4)---------------(5)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (2) (3)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ *
+ * Matriz de Adjacência
+ * 0 1 2 3 4 5
+ * 0 0 - 1 - - -
+ * 1 - 0 - 1 1 -
+ * 2 1 - 0 - - -
+ * 3 - 1 - 0 1 1
+ * 4 - 1 - 1 0 1
+ * 5 - - - 1 1 0
+ *
+ *
+ * 6 Vértices
+ * 8 Arestas
+ */
#include
@@ -34,35 +35,36 @@
bool visitados[VERTICES];
int componentes = 0;
-int matriz[VERTICES][VERTICES] = { { 0, INF, 1, INF, INF, INF },
- { INF, 0, INF, 1, 1, INF },
- { 1, INF, 0, INF, INF, INF },
- { INF, 1, INF, 0, 1, 1 },
- { INF, 1, INF, 1, 0, 1 },
- { INF, INF, INF, 1, 1, 0 } };
+int matriz[VERTICES][VERTICES] = {
+ {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF},
+ {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1},
+ {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}};
-// Método recursivo que encontra os componentes conexos a partir de uma matriz de adjacências
-void calculaComponentesConexos(int atual){
- for (int i = 0; i < VERTICES; i++){
- if( visitados[i] == false && matriz[atual][i] == 1 ){
- visitados[i] = true;
- componentes++;
- printf("(%d)-", i);
- calculaComponentesConexos(i);
- }
- }
+// Método recursivo que encontra os componentes conexos a partir de uma matriz
+// de adjacências
+void calculaComponentesConexos(int atual) {
+ for (int i = 0; i < VERTICES; i++) {
+ if (visitados[i] == false && matriz[atual][i] == 1) {
+ visitados[i] = true;
+ componentes++;
+ printf("(%d)-", i);
+ calculaComponentesConexos(i);
+ }
+ }
}
-int main(){
- for (int i = 0; i < VERTICES; i++)
- visitados[i] = false;
+int main() {
+ for (int i = 0; i < VERTICES; i++)
+ visitados[i] = false;
- for (int i = 0; i < VERTICES; i++)
- if( visitados[i] == false ){
- componentes = 0;
- calculaComponentesConexos(i);
- printf("\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n", i, componentes);
- }
-
- return 0;
+ for (int i = 0; i < VERTICES; i++)
+ if (visitados[i] == false) {
+ componentes = 0;
+ calculaComponentesConexos(i);
+ printf(
+ "\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n",
+ i, componentes);
+ }
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/CountingSort.c b/src/c/CountingSort.c
index 523fb7a4..bebad0e8 100644
--- a/src/c/CountingSort.c
+++ b/src/c/CountingSort.c
@@ -1,61 +1,66 @@
#include
#include
-// CountingSort - Ordenação por Contagem - Matheus Martins Batista - Universidade Federal de Itajuba - 2021
+// CountingSort - Ordenação por Contagem - Matheus Martins Batista -
+// Universidade Federal de Itajuba - 2021
-// Necessário encontrar o maior elemento para alocar o vetor auxiliar de contagem
-int findMax (int *arr, int tam) {
- int max = arr[0];
+// Necessário encontrar o maior elemento para alocar o vetor auxiliar de
+// contagem
+int findMax(int *arr, int tam) {
+ int max = arr[0];
- for (int i = 1; i < tam; i++) {
- if (arr[i] > max) {
- max = arr[i];
- }
+ for (int i = 1; i < tam; i++) {
+ if (arr[i] > max) {
+ max = arr[i];
}
+ }
- return max;
+ return max;
}
// Ordena os valores presentes em A e armazena em B
void countingSort(int *arrA, int *arrB, int tam) {
- // Vetor de contagem terá a frequência que um número aparece no vetor
- // deve-se setar 0 para todos os elementos ou usar calloc
- int max = findMax(arrA, tam);
- int* count = calloc(max + 1, sizeof(int));
-
- // Frequência que determinado valor aparece no vetor
- for (int i = 0; i < tam; i++) {
- count[arrA[i]]++;
- }
+ // Vetor de contagem terá a frequência que um número aparece no vetor
+ // deve-se setar 0 para todos os elementos ou usar calloc
+ int max = findMax(arrA, tam);
+ int *count = calloc(max + 1, sizeof(int));
- // Acumulativo da frequência dos valores menores que um elemento i do vetor original (A)
- for (int i = 1; i <= max; i++) {
- count[i] += count[i - 1];
- }
+ // Frequência que determinado valor aparece no vetor
+ for (int i = 0; i < tam; i++) {
+ count[arrA[i]]++;
+ }
- // Percorrer o vetor original com início no último elemento, subtituindo os indices nos elementos do vetor count e decrescendo a cada atribuição
- for (int i = tam - 1; i >= 0; i--) {
- arrB[count[arrA[i]] - 1] = arrA[i];
- count[arrA[i]]--;
- }
+ // Acumulativo da frequência dos valores menores que um elemento i do vetor
+ // original (A)
+ for (int i = 1; i <= max; i++) {
+ count[i] += count[i - 1];
+ }
+
+ // Percorrer o vetor original com início no último elemento, subtituindo os
+ // indices nos elementos do vetor count e decrescendo a cada atribuição
+ for (int i = tam - 1; i >= 0; i--) {
+ arrB[count[arrA[i]] - 1] = arrA[i];
+ count[arrA[i]]--;
+ }
}
int main() {
- int *arrA, *arrB;
- int tam = 10;
- arrA = malloc(tam * sizeof(int));
- arrB = calloc(tam, sizeof(int));
+ int *arrA, *arrB;
+ int tam = 10;
+ arrA = malloc(tam * sizeof(int));
+ arrB = calloc(tam, sizeof(int));
- // Popular vetor A
- srand(48+tam);
- for(int j = 0; j < tam; j++) arrA[j] = rand()%100;
+ // Popular vetor A
+ srand(48 + tam);
+ for (int j = 0; j < tam; j++)
+ arrA[j] = rand() % 100;
- countingSort(arrA, arrB, tam);
+ countingSort(arrA, arrB, tam);
- printf("Vetor ordenado: ");
- for (int i = 0; i < tam; i++) {
- printf("%d ", arrB[i]);
- }
+ printf("Vetor ordenado: ");
+ for (int i = 0; i < tam; i++) {
+ printf("%d ", arrB[i]);
+ }
- return 0;
+ return 0;
}
diff --git a/src/c/Dijkstra.c b/src/c/Dijkstra.c
index 806ddbb2..107e0acf 100644
--- a/src/c/Dijkstra.c
+++ b/src/c/Dijkstra.c
@@ -1,98 +1,110 @@
/*
-* Graphs - Dijkstra Algorithm in C
-* Complexity: Theta(n^2)
-*
-* 1 for all - Edges with non-negative weights - Greedy algorithm
-* Finds the shortest path from one vertex (start) to another (destination)
-*
-* Graph with 5 vertices and 6 edges
-*
-* 6
-* (0)-----------------(1)
-* | |
-* 10 | | 2
-* | 1 |
-* (2)-----------------(3)
-* \ /
-* 3 \ / 8
-* \ /
-* -----(4)-----
-*
-* Distance Matrix
-* 0 1 2 3 4
-* 0 0 6 10 - -
-* 1 6 0 - 2 -
-* 2 10 - 0 1 3
-* 3 - 2 1 0 8
-* 4 - - 3 8 0
-*
-* For infinite values, the value will be considered: 4294967295
-* The objective is to leave the starting point (0) and reach the destination (4) by the shortest route
-* Response: (0)->(1)->(3)->(2)->(4) = 12
-*
-*/
+ * Graphs - Dijkstra Algorithm in C
+ * Complexity: Theta(n^2)
+ *
+ * 1 for all - Edges with non-negative weights - Greedy algorithm
+ * Finds the shortest path from one vertex (start) to another (destination)
+ *
+ * Graph with 5 vertices and 6 edges
+ *
+ * 6
+ * (0)-----------------(1)
+ * | |
+ * 10 | | 2
+ * | 1 |
+ * (2)-----------------(3)
+ * \ /
+ * 3 \ / 8
+ * \ /
+ * -----(4)-----
+ *
+ * Distance Matrix
+ * 0 1 2 3 4
+ * 0 0 6 10 - -
+ * 1 6 0 - 2 -
+ * 2 10 - 0 1 3
+ * 3 - 2 1 0 8
+ * 4 - - 3 8 0
+ *
+ * For infinite values, the value will be considered: 4294967295
+ * The objective is to leave the starting point (0) and reach the destination
+ * (4) by the shortest route Response: (0)->(1)->(3)->(2)->(4) = 12
+ *
+ */
-#include
#include
+#include
-#define noVertices 5 // Defines a constant 5 which is the number of vertices in the graph
+#define noVertices \
+ 5 // Defines a constant 5 which is the number of vertices in the graph
-// Dijkstra's algorithm takes as parameters the distance matrix and the number of vertices
-void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n){
-
-bool visited[n]; // Variable that holds true for visited vertices
+// Dijkstra's algorithm takes as parameters the distance matrix and the number
+// of vertices
+void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n) {
- // The value 'i' from the for below is not used, as the for is only used to traverse the entire number of columns in the matrix
- for(int i = 1; i < n; i++){ // Starts at 1 because you don't need to compare the vertex with itself
+ bool visited[n]; // Variable that holds true for visited vertices
-int min = -1; // Variable that stores the position of the smallest value, starts at -1 as it is an invalid position
- unsigned long int MinValue = 4294967295; // Variable that stores the smallest value found, starts with 'infinity', so always on the first pass the value will be smaller than this variable
- // For that loops through all rows in column [0]
- for(int j = 1; j < n; j++){
- // If the vertex has not yet been visited and the value is less than the 'MinValor'
- if( !visited[j] && matrix[j][0] < MinValue ){
- min = j; // Saves the position of the smallest
- MinValue = matrix[j][0]; // Save the smallest value
- }
- }
+ // The value 'i' from the for below is not used, as the for is only used to
+ // traverse the entire number of columns in the matrix
+ for (int i = 1; i < n; i++) { // Starts at 1 because you don't need to compare
+ // the vertex with itself
+
+ int min = -1; // Variable that stores the position of the smallest value,
+ // starts at -1 as it is an invalid position
+ unsigned long int MinValue =
+ 4294967295; // Variable that stores the smallest value found, starts
+ // with 'infinity', so always on the first pass the value
+ // will be smaller than this variable
+ // For that loops through all rows in column [0]
+ for (int j = 1; j < n; j++) {
+ // If the vertex has not yet been visited and the value is less than the
+ // 'MinValor'
+ if (!visited[j] && matrix[j][0] < MinValue) {
+ min = j; // Saves the position of the smallest
+ MinValue = matrix[j][0]; // Save the smallest value
+ }
+ }
- visited[min] = true; // Mark the value of the minimum position as visited
+ visited[min] = true; // Mark the value of the minimum position as visited
- // Goes from 1 to n
- for(int j = 1; j < n; j++){
- // If the value of column [0] + the value of the passing column is less than the value of the passing row and column [0]
- // Update the first column of the matrix, which will be used for the next iterations
- if( (matrix[min][0] + matrix[min][j]) < matrix[j][0] ){
- matrix[j][0] = matrix[min][0] + matrix[min][j];
- }
- }
+ // Goes from 1 to n
+ for (int j = 1; j < n; j++) {
+ // If the value of column [0] + the value of the passing column is less
+ // than the value of the passing row and column [0] Update the first
+ // column of the matrix, which will be used for the next iterations
+ if ((matrix[min][0] + matrix[min][j]) < matrix[j][0]) {
+ matrix[j][0] = matrix[min][0] + matrix[min][j];
+ }
}
+ }
}
-int main(){
+int main() {
- unsigned long int Matrix[noVertices][noVertices] = {{ 0, 6, 10, 4294967295, 4294967295 },
- { 6, 0, 4294967295, 2, 4294967295 },
- { 10, 4294967295, 0, 1, 3 },
- { 4294967295, 2, 1, 0, 8 },
- { 4294967295, 4294967295, 3, 8, 0 }};
+ unsigned long int Matrix[noVertices][noVertices] = {
+ {0, 6, 10, 4294967295, 4294967295},
+ {6, 0, 4294967295, 2, 4294967295},
+ {10, 4294967295, 0, 1, 3},
+ {4294967295, 2, 1, 0, 8},
+ {4294967295, 4294967295, 3, 8, 0}};
- Dijkstra(Matrix, noVertices);
+ Dijkstra(Matrix, noVertices);
- printf("Total shortest path from vertex 0 to 4: %lu\n", Matrix[4][0]); // Shortest total path
+ printf("Total shortest path from vertex 0 to 4: %lu\n",
+ Matrix[4][0]); // Shortest total path
- // Print the matrix with the updated values
- printf("Matrix:\n");
- for (int i = 0; i < noVertices; ++i){
- for (int e = 0; e < noVertices; ++e){
- if( Matrix[i][e] < 10 )
- printf(" %lu ", Matrix[i][e]);
- else
- printf("%lu ", Matrix[i][e]);
- }
- printf("\n");
+ // Print the matrix with the updated values
+ printf("Matrix:\n");
+ for (int i = 0; i < noVertices; ++i) {
+ for (int e = 0; e < noVertices; ++e) {
+ if (Matrix[i][e] < 10)
+ printf(" %lu ", Matrix[i][e]);
+ else
+ printf("%lu ", Matrix[i][e]);
}
printf("\n");
+ }
+ printf("\n");
- return 0;
+ return 0;
}
diff --git a/src/c/DoublyLinkedList.c b/src/c/DoublyLinkedList.c
index 1bf5cf3e..7be11ee4 100644
--- a/src/c/DoublyLinkedList.c
+++ b/src/c/DoublyLinkedList.c
@@ -1,7 +1,6 @@
/*
-* Exemplo Lista Duplamente Encadeada em C
-*/
-
+ * Exemplo Lista Duplamente Encadeada em C
+ */
#include
#include
@@ -9,149 +8,137 @@
/* Lista encadeada utilizando celula cabeça */
typedef struct cel celula;
-struct cel{
- int dado;
- struct cel *prox;
- struct cel *ant;
+struct cel {
+ int dado;
+ struct cel *prox;
+ struct cel *ant;
};
/* O ponteiro 'p' é a cabeça da lista*/
void insereInicio(int x, celula *p) /* Insere no inicio da lista*/
{
- celula *nova, *q;
- nova = malloc (sizeof (celula));
- nova->dado = x;
- nova->prox = p->prox;
- /* verifica se a lista está vazia*/
- if (p->prox != NULL)
- {
- q = nova->prox;
- q->ant = nova;
- }
- p->prox = nova;
- nova->ant = p;
+ celula *nova, *q;
+ nova = malloc(sizeof(celula));
+ nova->dado = x;
+ nova->prox = p->prox;
+ /* verifica se a lista está vazia*/
+ if (p->prox != NULL) {
+ q = nova->prox;
+ q->ant = nova;
+ }
+ p->prox = nova;
+ nova->ant = p;
}
void insereUltimo(int x, celula *p) /* Insere no final da lista*/
{
- celula *q;
- celula *nova;
- nova = malloc (sizeof (celula));
- nova->dado = x;
- q = p;
- while (q->prox != NULL)
- q = q->prox;
-
- q->prox = nova;
- nova->ant = q;
- nova->prox = NULL;
+ celula *q;
+ celula *nova;
+ nova = malloc(sizeof(celula));
+ nova->dado = x;
+ q = p;
+ while (q->prox != NULL)
+ q = q->prox;
+
+ q->prox = nova;
+ nova->ant = q;
+ nova->prox = NULL;
}
-
-void buscaEremove (int y, celula *p)
-{
- celula *w, *q;
- w = p;
- q = p->prox;
- while (q != NULL && q->dado != y) {
- w = q;
- q = q->prox;
- }
- if (q != NULL) {
- w->prox = q->prox;
- q->ant = w;
- free (q);
- }
- else{
- printf("\nLista nao contem item\n\n");
- system("pause");
- }
+void buscaEremove(int y, celula *p) {
+ celula *w, *q;
+ w = p;
+ q = p->prox;
+ while (q != NULL && q->dado != y) {
+ w = q;
+ q = q->prox;
+ }
+ if (q != NULL) {
+ w->prox = q->prox;
+ q->ant = w;
+ free(q);
+ } else {
+ printf("\nLista nao contem item\n\n");
+ system("pause");
+ }
}
-
-void imprime (celula *p)
-{
- celula *q;
- for (q = p->prox; q != NULL; q = q->prox)
- printf ("%d ", q->dado);
+void imprime(celula *p) {
+ celula *q;
+ for (q = p->prox; q != NULL; q = q->prox)
+ printf("%d ", q->dado);
}
-void Menu ()
-{
- printf(" Menu Principal\n");
- printf("1 - Insere inicio\n");
- printf("2 - Insere ultimo\n");
- printf("3 - Retira\n");
- printf("4 - Sair\n");
- printf("\nOpcao: ");
+void Menu() {
+ printf(" Menu Principal\n");
+ printf("1 - Insere inicio\n");
+ printf("2 - Insere ultimo\n");
+ printf("3 - Retira\n");
+ printf("4 - Sair\n");
+ printf("\nOpcao: ");
}
-void libera (celula *ini)
-{
- celula *p;
- p=ini;
- while (p != NULL) {
- celula *q = p->prox; /* guarda referência para o próximo elemento*/
- free(p); /* libera a memória apontada por p */
- p = q; /* faz p apontar para o próximo */
- }
+void libera(celula *ini) {
+ celula *p;
+ p = ini;
+ while (p != NULL) {
+ celula *q = p->prox; /* guarda referência para o próximo elemento*/
+ free(p); /* libera a memória apontada por p */
+ p = q; /* faz p apontar para o próximo */
+ }
}
+int main() {
+ celula *p;
+ int op = 0, item;
+ // inicializa lista
+ p = malloc(sizeof(celula));
+ p->ant = NULL;
+ p->prox = NULL;
+ // fim_inicializa
+
+ do {
+ system("cls");
+ printf("\nConteudo da lista: ");
+ if (p->prox != NULL) {
+ imprime(p);
+ } else {
+ printf("Lista VAZIA");
+ }
+ printf("\n\n");
+ Menu();
+ scanf("%d", &op);
+ switch (op) {
+ case 1:
+ printf("Insere no inicio da lista: ");
+ scanf("%d", &item);
+ insereInicio(item, p);
+ break;
+ case 2:
+ printf("Insere na ultima posicao da lista: ");
+ scanf("%d", &item);
+ insereUltimo(item, p);
+ break;
+ case 3:
+ if (p->prox != NULL) {
+ printf("Retirar um elemento: ");
+ scanf("%d", &item);
+ buscaEremove(item, p);
+ } else {
+ printf("\nLista VAZIA\n\n");
+ system("pause");
+ }
+ break;
+ case 4:
+ break;
+ default:
+ printf("Opcao invalida!\n");
+ system("pause");
+ break;
+ }
-int main()
-{
- celula *p;
- int op = 0,item;
- //inicializa lista
- p = malloc (sizeof (celula));
- p->ant = NULL;
- p->prox = NULL;
- //fim_inicializa
-
- do{
- system("cls");
- printf("\nConteudo da lista: ");
- if (p->prox != NULL){
- imprime(p);
- }
- else{
- printf("Lista VAZIA");
- }
- printf("\n\n");
- Menu();
- scanf("%d",&op);
- switch (op){
- case 1:
- printf("Insere no inicio da lista: ");
- scanf("%d",&item);
- insereInicio(item,p);
- break;
- case 2:
- printf("Insere na ultima posicao da lista: ");
- scanf("%d",&item);
- insereUltimo(item,p);
- break;
- case 3:
- if (p->prox != NULL){
- printf("Retirar um elemento: ");
- scanf("%d",&item);
- buscaEremove(item,p);
- }
- else{
- printf("\nLista VAZIA\n\n");
- system("pause");
- }
- break;
- case 4:
- break;
- default:
- printf("Opcao invalida!\n");
- system("pause");
- break;
- }
-
- }while(op!=4);
- libera(p);
- return 0;
+ } while (op != 4);
+ libera(p);
+ return 0;
}
diff --git a/src/c/DynamicQueue.c b/src/c/DynamicQueue.c
index 5b1d3711..074aebc6 100644
--- a/src/c/DynamicQueue.c
+++ b/src/c/DynamicQueue.c
@@ -1,72 +1,72 @@
/*
-* Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C
-*/
+ * Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C
+ */
-#include
#include
+#include
typedef int TIPOCHAVE;
-typedef struct NO{
- TIPOCHAVE chave;
- struct NO* prox;
-}*PONT;
+typedef struct NO {
+ TIPOCHAVE chave;
+ struct NO *prox;
+} *PONT;
-PONT novoNO(TIPOCHAVE ch){
- PONT aux = (PONT) malloc( sizeof(NO) );
- aux->chave = ch;
- aux->prox = NULL;
- return aux;
+PONT novoNO(TIPOCHAVE ch) {
+ PONT aux = (PONT)malloc(sizeof(NO));
+ aux->chave = ch;
+ aux->prox = NULL;
+ return aux;
}
-PONT insere(TIPOCHAVE ch, PONT no){
- PONT aux = novoNO(ch);
- aux->prox = no;
- return aux;
+PONT insere(TIPOCHAVE ch, PONT no) {
+ PONT aux = novoNO(ch);
+ aux->prox = no;
+ return aux;
}
-void mostraFila(PONT no){
- while(no != NULL){
- printf("[%d]->", no->chave);
- no = no->prox;
- }
- printf("\n");
+void mostraFila(PONT no) {
+ while (no != NULL) {
+ printf("[%d]->", no->chave);
+ no = no->prox;
+ }
+ printf("\n");
}
-void remove(PONT no){
- PONT noAnterior = no;
- while(no->prox != NULL){
- noAnterior = no;
- no = no->prox;
- }
- noAnterior->prox = NULL;
- free(no);
+void remove(PONT no) {
+ PONT noAnterior = no;
+ while (no->prox != NULL) {
+ noAnterior = no;
+ no = no->prox;
+ }
+ noAnterior->prox = NULL;
+ free(no);
}
-int tamanhoFila(PONT no){
- int cont = 0;
- while(no != NULL){
- cont++;
- no = no->prox;
- }
- return cont;
+int tamanhoFila(PONT no) {
+ int cont = 0;
+ while (no != NULL) {
+ cont++;
+ no = no->prox;
+ }
+ return cont;
}
-int main(){
- PONT fila = novoNO(5);
- fila = insere(8, fila);
- fila = insere(1, fila);
- fila = insere(3, fila);
- fila = insere(5, fila);
- fila = insere(4, fila);
- fila = insere(2, fila);
+int main() {
+ PONT fila = novoNO(5);
+ fila = insere(8, fila);
+ fila = insere(1, fila);
+ fila = insere(3, fila);
+ fila = insere(5, fila);
+ fila = insere(4, fila);
+ fila = insere(2, fila);
- mostraFila(fila);
- remove(fila);
- mostraFila(fila);
- remove(fila);
- mostraFila(fila);
+ mostraFila(fila);
+ remove(fila);
+ mostraFila(fila);
+ remove(fila);
+ mostraFila(fila);
- printf("Tamanho da fila: %d\n", tamanhoFila(fila) );
- return 0;
+ printf("Tamanho da fila: %d\n", tamanhoFila(fila));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/DynamicStack.c b/src/c/DynamicStack.c
index f32a6dcd..4e63e575 100644
--- a/src/c/DynamicStack.c
+++ b/src/c/DynamicStack.c
@@ -1,82 +1,82 @@
/*
-* Pilha Dinâmica utilizando uma Lista Ligada em C
-*/
+ * Pilha Dinâmica utilizando uma Lista Ligada em C
+ */
-#include
#include
+#include
#define ERRO -1
typedef int TIPOCHAVE;
-typedef struct AUX{
- TIPOCHAVE chave;
- struct AUX *prox;
-}*PILHA;
+typedef struct AUX {
+ TIPOCHAVE chave;
+ struct AUX *prox;
+} *PILHA;
-PILHA CREATE(TIPOCHAVE ch){
- PILHA novaPilha = (PILHA) malloc( sizeof(PILHA) );
- novaPilha->chave = ch;
- novaPilha->prox = NULL;
- return novaPilha;
+PILHA CREATE(TIPOCHAVE ch) {
+ PILHA novaPilha = (PILHA)malloc(sizeof(PILHA));
+ novaPilha->chave = ch;
+ novaPilha->prox = NULL;
+ return novaPilha;
}
-PILHA PUSH(TIPOCHAVE ch, PILHA pi){
- /*while( pi->prox != NULL ){
- pi = pi->prox;
- }*/
- PILHA novo = CREATE(ch);
- //pi->prox = novo;
- novo->prox = pi;
- return novo;
+PILHA PUSH(TIPOCHAVE ch, PILHA pi) {
+ /*while( pi->prox != NULL ){
+ pi = pi->prox;
+ }*/
+ PILHA novo = CREATE(ch);
+ // pi->prox = novo;
+ novo->prox = pi;
+ return novo;
}
-PILHA POP(PILHA pi){
- PILHA sub = pi->prox;
- free(pi);
- return sub;
+PILHA POP(PILHA pi) {
+ PILHA sub = pi->prox;
+ free(pi);
+ return sub;
}
-void SHOW(PILHA pi){
- printf("PILHA:\n");
- while( pi->prox != NULL ){
- printf("[ %d ]\n", pi->chave);
- pi = pi->prox;
- }
- printf("[ %d ]\n", pi->chave);
+void SHOW(PILHA pi) {
+ printf("PILHA:\n");
+ while (pi->prox != NULL) {
+ printf("[ %d ]\n", pi->chave);
+ pi = pi->prox;
+ }
+ printf("[ %d ]\n", pi->chave);
}
-bool SEARCH(TIPOCHAVE ch, PILHA pi){
- bool vAchou = false;
- while(pi != NULL){
- if( pi->chave == ch )
- vAchou = true;
- pi = pi->prox;
- }
- return vAchou;
+bool SEARCH(TIPOCHAVE ch, PILHA pi) {
+ bool vAchou = false;
+ while (pi != NULL) {
+ if (pi->chave == ch)
+ vAchou = true;
+ pi = pi->prox;
+ }
+ return vAchou;
}
-int main(){
- PILHA vPilha;
-
- vPilha = PUSH(1, vPilha);
- vPilha = PUSH(2, vPilha);
- vPilha = PUSH(3, vPilha);
- vPilha = PUSH(4, vPilha);
- vPilha = PUSH(5, vPilha);
- vPilha = PUSH(6, vPilha);
-
- SHOW(vPilha);
-
- vPilha = POP(vPilha);
- vPilha = POP(vPilha);
-
- SHOW(vPilha);
-
- if( SEARCH(6, vPilha) )
- printf("\nAchou\n");
- else
- printf("\nNão achou\n");
-
- return 0;
+int main() {
+ PILHA vPilha;
+
+ vPilha = PUSH(1, vPilha);
+ vPilha = PUSH(2, vPilha);
+ vPilha = PUSH(3, vPilha);
+ vPilha = PUSH(4, vPilha);
+ vPilha = PUSH(5, vPilha);
+ vPilha = PUSH(6, vPilha);
+
+ SHOW(vPilha);
+
+ vPilha = POP(vPilha);
+ vPilha = POP(vPilha);
+
+ SHOW(vPilha);
+
+ if (SEARCH(6, vPilha))
+ printf("\nAchou\n");
+ else
+ printf("\nNão achou\n");
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Exponentiation.c b/src/c/Exponentiation.c
index fb59d362..1abf4a77 100644
--- a/src/c/Exponentiation.c
+++ b/src/c/Exponentiation.c
@@ -1,24 +1,19 @@
-#include
+#include
+int exponenciacao(int base, int expoente) {
+ int i;
+ int result = base;
-int exponenciacao(int base, int expoente){
-
- int i;
- int result = base;
-
- for(i=0; i
+#include
+int exponenciacao(int base, int expoente) {
+ if (expoente == 0)
+ return 1;
-int exponenciacao(int base, int expoente){
-
- if(expoente==0) return 1;
-
- return (base * exponenciacao(base, expoente-1));
-
+ return (base * exponenciacao(base, expoente - 1));
}
+int main() {
+ printf("%d\n", exponenciacao(5, 3));
-int main(){
-
- printf("%d\n", exponenciacao(5, 3));
-
- return 0;
+ return 0;
}
diff --git a/src/c/Factorial.c b/src/c/Factorial.c
index 57dba9c7..bed39222 100644
--- a/src/c/Factorial.c
+++ b/src/c/Factorial.c
@@ -1,25 +1,25 @@
-#include
-#include
+#include
+#include
/*
-* Exemplos de função para retornar o fatorial de um número n
-* função recursiva
-*/
+ * Exemplos de função para retornar o fatorial de um número n
+ * função recursiva
+ */
-int main(){
- int num;
- printf("Digite um número: ");
- scanf("%d", &num);
- int result = fatorial(num);
- printf("1 => ");
- printf("%d! é : %d\n", num, result);
- return(0);
+int main() {
+ int num;
+ printf("Digite um número: ");
+ scanf("%d", &num);
+ int result = fatorial(num);
+ printf("1 => ");
+ printf("%d! é : %d\n", num, result);
+ return (0);
}
-int fatorial(int num){
- if(num <= 1 ){
- return 1;
- }
- printf("%d * ", num);
- return num * fatorial(num - 1);
+int fatorial(int num) {
+ if (num <= 1) {
+ return 1;
+ }
+ printf("%d * ", num);
+ return num * fatorial(num - 1);
}
diff --git a/src/c/FactorialRecursive.c b/src/c/FactorialRecursive.c
index a2390927..a4a2e4e6 100644
--- a/src/c/FactorialRecursive.c
+++ b/src/c/FactorialRecursive.c
@@ -1,20 +1,16 @@
-#include
+#include
+int fatorial(int n) {
+ if (n == 1)
+ return 1;
-int fatorial(int n){
-
- if(n==1) return 1;
-
- return (n * fatorial(n-1));
-
+ return (n * fatorial(n - 1));
}
+int main() {
+ printf("%d\n", fatorial(5));
-int main(){
-
- printf("%d\n", fatorial(5));
-
- return 0;
+ return 0;
}
diff --git a/src/c/FibonacciIterative.c b/src/c/FibonacciIterative.c
index 24177b90..36c7d1c1 100644
--- a/src/c/FibonacciIterative.c
+++ b/src/c/FibonacciIterative.c
@@ -1,18 +1,18 @@
#include
int fibonacci(int number) {
- int last_number = 0;
- int current_number = 1;
+ int last_number = 0;
+ int current_number = 1;
- for (int index = 0; index < number; ++index) {
- int temp = current_number;
- current_number += last_number;
- last_number = temp;
- }
- return last_number;
+ for (int index = 0; index < number; ++index) {
+ int temp = current_number;
+ current_number += last_number;
+ last_number = temp;
+ }
+ return last_number;
}
int main() {
- printf("Fibonacci Iterative: %d\n", fibonacci(12));
- return 0;
+ printf("Fibonacci Iterative: %d\n", fibonacci(12));
+ return 0;
}
diff --git a/src/c/FibonacciMemoization.c b/src/c/FibonacciMemoization.c
index 43cdaf9b..f8afb46b 100644
--- a/src/c/FibonacciMemoization.c
+++ b/src/c/FibonacciMemoization.c
@@ -1,27 +1,28 @@
#include
-#define MAX_N 100 // Define the maximum number for which you want to calculate Fibonacci
+#define MAX_N \
+ 100 // Define the maximum number for which you want to calculate Fibonacci
int memo[MAX_N]; // Memoization table to store computed values
int fibonacci(int number) {
- if (number <= 1) {
- return number;
- }
- if (memo[number] != -1) {
- return memo[number];
- }
-
- memo[number] = fibonacci(number - 1) + fibonacci(number - 2);
+ if (number <= 1) {
+ return number;
+ }
+ if (memo[number] != -1) {
return memo[number];
+ }
+
+ memo[number] = fibonacci(number - 1) + fibonacci(number - 2);
+ return memo[number];
}
int main(void) {
- // Initialize the memoization table with -1 (uncomputed)
- for (int i = 0; i < MAX_N; i++) {
- memo[i] = -1;
- }
+ // Initialize the memoization table with -1 (uncomputed)
+ for (int i = 0; i < MAX_N; i++) {
+ memo[i] = -1;
+ }
- printf("memoization: %d\n", fibonacci(12));
- return 0;
+ printf("memoization: %d\n", fibonacci(12));
+ return 0;
}
diff --git a/src/c/FibonacciRecursive.c b/src/c/FibonacciRecursive.c
index ecaff406..1054cc06 100644
--- a/src/c/FibonacciRecursive.c
+++ b/src/c/FibonacciRecursive.c
@@ -1,18 +1,18 @@
#include
int fibonacci(int number) {
- if (number == 0) {
- return 0;
- } else if (number == 1) {
- return 1;
- } else {
- return fibonacci(number - 1) + fibonacci(number - 2);
- }
+ if (number == 0) {
+ return 0;
+ } else if (number == 1) {
+ return 1;
+ } else {
+ return fibonacci(number - 1) + fibonacci(number - 2);
+ }
}
int main(void) {
- int test_nbr = 12;
+ int test_nbr = 12;
- printf("recursive: %d\n", fibonacci(test_nbr));
- return 0;
+ printf("recursive: %d\n", fibonacci(test_nbr));
+ return 0;
}
diff --git a/src/c/FloydWarshall.c b/src/c/FloydWarshall.c
index b6c6b68c..1ce22edc 100644
--- a/src/c/FloydWarshall.c
+++ b/src/c/FloydWarshall.c
@@ -1,85 +1,90 @@
/*
-* Grafos - Algoritmo de Floyd-Warshall em C
-* Complexidade: Teta de vértices ao cubo = Teta(n^3)
-*
-* Encontra o caminho de todos para todos os vértices
-*
-* Grafo com 5 vértices e 6 arestas
-*
-* 6
-* (0)-----------------(1)
-* | |
-* 10 | | 2
-* | 1 |
-* (2)-----------------(3)
-* \ /
-* 3 \ / 8
-* \ /
-* -----(4)-----
-*
-* Matriz de Distância
-* 0 1 2 3 4
-* 0 0 6 10 - -
-* 1 6 0 - 2 -
-* 2 10 - 0 1 3
-* 3 - 2 1 0 8
-* 4 - - 3 8 0
-*
-* Para valores infinitos será considerado o valor: 4294967295
-*
-*/
+ * Grafos - Algoritmo de Floyd-Warshall em C
+ * Complexidade: Teta de vértices ao cubo = Teta(n^3)
+ *
+ * Encontra o caminho de todos para todos os vértices
+ *
+ * Grafo com 5 vértices e 6 arestas
+ *
+ * 6
+ * (0)-----------------(1)
+ * | |
+ * 10 | | 2
+ * | 1 |
+ * (2)-----------------(3)
+ * \ /
+ * 3 \ / 8
+ * \ /
+ * -----(4)-----
+ *
+ * Matriz de Distância
+ * 0 1 2 3 4
+ * 0 0 6 10 - -
+ * 1 6 0 - 2 -
+ * 2 10 - 0 1 3
+ * 3 - 2 1 0 8
+ * 4 - - 3 8 0
+ *
+ * Para valores infinitos será considerado o valor: 4294967295
+ *
+ */
#include
-#define nroVertices 5 // Define uma constante 5 que é a quantidade de vértices do grafo
+#define nroVertices \
+ 5 // Define uma constante 5 que é a quantidade de vértices do grafo
-// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o número de vértices
-void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n){
- for(int x = 0; x < n; x++){
- for(int y = 0; y < n; y++){
- for(int z = 0; z < n; z++){
- if( matriz[y][z] > (matriz[y][x] + matriz[x][z]) )
- matriz[y][z] = matriz[y][x] + matriz[x][z];
- }
- }
- }
+// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o
+// número de vértices
+void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n) {
+ for (int x = 0; x < n; x++) {
+ for (int y = 0; y < n; y++) {
+ for (int z = 0; z < n; z++) {
+ if (matriz[y][z] > (matriz[y][x] + matriz[x][z]))
+ matriz[y][z] = matriz[y][x] + matriz[x][z];
+ }
+ }
+ }
}
-int main(){
+int main() {
- unsigned long int Matriz[nroVertices][nroVertices] = {{ 0, 6, 10, 4294967295, 4294967295 },
- { 6, 0, 4294967295, 2, 4294967295 },
- { 10, 4294967295, 0, 1, 3 },
- { 4294967295, 2, 1, 0, 8 },
- { 4294967295, 4294967295, 3, 8, 0 }};
+ unsigned long int Matriz[nroVertices][nroVertices] = {
+ {0, 6, 10, 4294967295, 4294967295},
+ {6, 0, 4294967295, 2, 4294967295},
+ {10, 4294967295, 0, 1, 3},
+ {4294967295, 2, 1, 0, 8},
+ {4294967295, 4294967295, 3, 8, 0}};
- FloydWarshall(Matriz, nroVertices);
+ FloydWarshall(Matriz, nroVertices);
- // Mostra a matriz com os valores atualizados
- printf("Matriz:\n");
- for (int i = 0; i < nroVertices; ++i){
- for (int e = 0; e < nroVertices; ++e){
- if( Matriz[i][e] < 10 )
- printf(" %lu ", Matriz[i][e]);
- else
- printf("%lu ", Matriz[i][e]);
- }
- printf("\n");
- }
- printf("\n");
+ // Mostra a matriz com os valores atualizados
+ printf("Matriz:\n");
+ for (int i = 0; i < nroVertices; ++i) {
+ for (int e = 0; e < nroVertices; ++e) {
+ if (Matriz[i][e] < 10)
+ printf(" %lu ", Matriz[i][e]);
+ else
+ printf("%lu ", Matriz[i][e]);
+ }
+ printf("\n");
+ }
+ printf("\n");
- //printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]); // [destino] [origem]
- //printf("Total caminho mais curto do vertice 2 ao 0: %lu\n", Matriz[0][2]);
- //printf("Total caminho mais curto do vertice 4 ao 3: %lu\n\n", Matriz[3][4]);
+ // printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]);
+ // // [destino] [origem] printf("Total caminho mais curto do vertice 2 ao 0:
+ // %lu\n", Matriz[0][2]); printf("Total caminho mais curto do vertice 4 ao 3:
+ // %lu\n\n", Matriz[3][4]);
- // Mostra todos os caminhos
- printf("\n");
- for (int i = 0; i < nroVertices; ++i){
- for (int x = 0; x < nroVertices; ++x){
- printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x, Matriz[x][i]);
- }
- }
- printf("\n\n");
+ // Mostra todos os caminhos
+ printf("\n");
+ for (int i = 0; i < nroVertices; ++i) {
+ for (int x = 0; x < nroVertices; ++x) {
+ printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x,
+ Matriz[x][i]);
+ }
+ }
+ printf("\n\n");
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/GraphSearch.c b/src/c/GraphSearch.c
index 2bfe7708..e6643f29 100644
--- a/src/c/GraphSearch.c
+++ b/src/c/GraphSearch.c
@@ -1,203 +1,225 @@
/*
-*
-* Grafos - Implementação de uma estrutura de Grafo não dirigido em C
-* Métodos de Busca: Busca em Profundidade e Busca em Largura
-*
-*
-* (A)---------------(B)-------------(E)---------------(F)
-* | | | |
-* | | | |
-* | | | |
-* (C)---------------(D)--------------- |
-* | |
-* -----------------------------------
-*
-* 6 Vértices
-* 8 Arestas
-*/
+ *
+ * Grafos - Implementação de uma estrutura de Grafo não dirigido em C
+ * Métodos de Busca: Busca em Profundidade e Busca em Largura
+ *
+ *
+ * (A)---------------(B)-------------(E)---------------(F)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (C)---------------(D)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ * 6 Vértices
+ * 8 Arestas
+ */
-#include
#include
+#include
-#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM
-#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
+#define MAX_VERTICES \
+ 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA
+ // VARIÁVEL TAMBÉM
+#define MAX_ARESTAS \
+ (MAX_VERTICES * \
+ (MAX_VERTICES - \
+ 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
// Estrutura que define cada Vértice do Grafo
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct NO* vizinhos[MAX_ARESTAS];
- bool visitado;
-}*VERTICE;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct NO *vizinhos[MAX_ARESTAS];
+ bool visitado;
+} *VERTICE;
// Cria Vértice e retorna
-VERTICE criaVertice(char id){
- VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice
- novoVertice->id = id;
- novoVertice->nroVizinhos = 0;
- novoVertice->visitado = false;
- for (int i = 0; i < MAX_ARESTAS; i++){
- novoVertice->vizinhos[i] = NULL;
- }
- return novoVertice;
+VERTICE criaVertice(char id) {
+ VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice
+ novoVertice->id = id;
+ novoVertice->nroVizinhos = 0;
+ novoVertice->visitado = false;
+ for (int i = 0; i < MAX_ARESTAS; i++) {
+ novoVertice->vizinhos[i] = NULL;
+ }
+ return novoVertice;
}
// Liga os vértices passados como parâmetro
-bool ligaVertices(VERTICE v1, VERTICE v2){
- int aux = 0;
- while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
- aux = 0;
- while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
- v1->nroVizinhos++; // Incrementa o número de vizinhos
- v2->nroVizinhos++; // Incrementa o número de vizinhos
+bool ligaVertices(VERTICE v1, VERTICE v2) {
+ int aux = 0;
+ while (v1->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
+ aux = 0;
+ while (v2->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
+ v1->nroVizinhos++; // Incrementa o número de vizinhos
+ v2->nroVizinhos++; // Incrementa o número de vizinhos
}
/*
-* Busca em Profundidade - DFS - Depht First Search
-* Percorre primeiro todos os vizinhos que foram ligados primeiro ao vértice
-*
-*/
-int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados){
- inicio->visitado = true; // Marca o Vértice que está passando inicio como já visitado
- if( inicio == destino ) return visitados; // Se for o buscado (destino) retorna ele
-
- int aux = 0;
- while( inicio->vizinhos[aux] != NULL ){ // Enquanto existe vizinhos a serem visitados
- if( inicio->vizinhos[aux]->visitado == false ){ // Se o vizinho ainda não foi visitado
- // Chama recursivamente passando novo vizinho como iniício, ou seja, irá percorrer todos os vizinhos dele, e assim, sucessivamente
- int resposta = buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados+1);
- // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já retorna a resposta
- if( resposta != -1 ) return resposta;
- }
- aux++; // Incrementa 1 na lista de vizinhos
- }
-
- return -1; // Não encontrou o vértice
+ * Busca em Profundidade - DFS - Depht First Search
+ * Percorre primeiro todos os vizinhos que foram ligados primeiro ao
+ *vértice
+ *
+ */
+int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados) {
+ inicio->visitado =
+ true; // Marca o Vértice que está passando inicio como já visitado
+ if (inicio == destino)
+ return visitados; // Se for o buscado (destino) retorna ele
+
+ int aux = 0;
+ while (inicio->vizinhos[aux] !=
+ NULL) { // Enquanto existe vizinhos a serem visitados
+ if (inicio->vizinhos[aux]->visitado ==
+ false) { // Se o vizinho ainda não foi visitado
+ // Chama recursivamente passando novo vizinho como iniício, ou seja, irá
+ // percorrer todos os vizinhos dele, e assim, sucessivamente
+ int resposta =
+ buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados + 1);
+ // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já
+ // retorna a resposta
+ if (resposta != -1)
+ return resposta;
+ }
+ aux++; // Incrementa 1 na lista de vizinhos
+ }
+
+ return -1; // Não encontrou o vértice
}
/*
-* Busca em Largura - BFS - Breadth First Search
-* Implementada com o conceito de fila, porém utilizando um array simples
-* Assim ela não excluí o 'vértice' do array, apenas pula uma posição para a frente
-* Percorre todos os vértices por nível
-*/
-int buscaEmLargura(VERTICE inicio, VERTICE destino){
- int iniFila = 0; // Variável que controla a posição do inicio da fila, é utilizada para controlar o WHILE
- int tamFila = 1; // Variável que controla o tamanho da fila
-
- VERTICE FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
- for (int i = 0; i < MAX_VERTICES; i++){ // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro
- FILA[i] = NULL;
- }
- FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início
-
- // Enquanto não terminar a fila faça
- while( iniFila < tamFila ){
- // Se o elemento que está para 'sair' da fila for o buscado (destino) então retorna iniFila, que foi a distância percorrida para encontrar
- if( FILA[iniFila] == destino ) return iniFila;
-
- /*
- * Para todos os vizinhos do vértice que está para 'sair' da fila:
- * Marca todos como visitado, para não coloca-los na fila novamente,
- * e então os coloca na fila, e aumenta o tamanho da fila
- */
- for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++){
- if( FILA[iniFila]->vizinhos[i]->visitado == false ){
- FILA[iniFila]->vizinhos[i]->visitado = true;
- FILA[tamFila] = FILA[iniFila]->vizinhos[i];
- tamFila++;
- }
- }
- iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o primeiro que entrou na fila (FIFO - First In First Out)
- }
- return -1;
+ * Busca em Largura - BFS - Breadth First Search
+ * Implementada com o conceito de fila, porém utilizando um array simples
+ * Assim ela não excluí o 'vértice' do array, apenas pula uma posição para
+ *a frente Percorre todos os vértices por nível
+ */
+int buscaEmLargura(VERTICE inicio, VERTICE destino) {
+ int iniFila = 0; // Variável que controla a posição do inicio da fila, é
+ // utilizada para controlar o WHILE
+ int tamFila = 1; // Variável que controla o tamanho da fila
+
+ VERTICE
+ FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
+ for (int i = 0; i < MAX_VERTICES;
+ i++) { // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro
+ FILA[i] = NULL;
+ }
+ FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início
+
+ // Enquanto não terminar a fila faça
+ while (iniFila < tamFila) {
+ // Se o elemento que está para 'sair' da fila for o buscado (destino) então
+ // retorna iniFila, que foi a distância percorrida para encontrar
+ if (FILA[iniFila] == destino)
+ return iniFila;
+
+ /*
+ * Para todos os vizinhos do vértice que está para 'sair' da fila:
+ * Marca todos como visitado, para não coloca-los na fila novamente,
+ * e então os coloca na fila, e aumenta o tamanho da fila
+ */
+ for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++) {
+ if (FILA[iniFila]->vizinhos[i]->visitado == false) {
+ FILA[iniFila]->vizinhos[i]->visitado = true;
+ FILA[tamFila] = FILA[iniFila]->vizinhos[i];
+ tamFila++;
+ }
+ }
+ iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o
+ // primeiro que entrou na fila (FIFO - First In First Out)
+ }
+ return -1;
}
-int main(){
-
- // Grafo conjunto de vértices independentes
- VERTICE A = criaVertice('A');
- VERTICE B = criaVertice('B');
- VERTICE C = criaVertice('C');
- VERTICE D = criaVertice('D');
- VERTICE E = criaVertice('E');
- VERTICE F = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(A, B);
- ligaVertices(A, C);
- ligaVertices(B, D);
- ligaVertices(C, D);
- ligaVertices(B, E);
- ligaVertices(D, E);
- ligaVertices(E, F);
- ligaVertices(D, F);
-
- // Realiza a busca em profundidade
- int res = buscaEmProfundidade(A, F, 0);
- if( res != -1 )
- printf("DFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("DFS - Não encontrou.\n");
-
- // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
- A->visitado = false;
- B->visitado = false;
- C->visitado = false;
- D->visitado = false;
- E->visitado = false;
- F->visitado = false;
-
- // Realiza a busca em largura
- res = buscaEmLargura(A, F);
- if( res != -1 )
- printf("BFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("BFS - Não encontrou.\n");
-
- // Grafo conjunto de vértices em um array
- VERTICE GRAFO[MAX_VERTICES];
- GRAFO[0] = criaVertice('A');
- GRAFO[1] = criaVertice('B');
- GRAFO[2] = criaVertice('C');
- GRAFO[3] = criaVertice('D');
- GRAFO[4] = criaVertice('E');
- GRAFO[5] = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(GRAFO[0], GRAFO[1]);
- ligaVertices(GRAFO[0], GRAFO[2]);
- ligaVertices(GRAFO[1], GRAFO[3]);
- ligaVertices(GRAFO[2], GRAFO[3]);
- ligaVertices(GRAFO[1], GRAFO[4]);
- ligaVertices(GRAFO[3], GRAFO[4]);
- ligaVertices(GRAFO[4], GRAFO[5]);
- ligaVertices(GRAFO[3], GRAFO[5]);
-
- // Realiza a busca em profundidade
- res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0);
- if( res != -1 )
- printf("DFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("DFS - Não encontrou.\n");
-
- // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
- for (int i = 0; i < MAX_VERTICES; i++){
- GRAFO[i]->visitado = false;
- }
-
- // Realiza a busca em largura
- res = buscaEmLargura(GRAFO[0], GRAFO[5]);
- if( res != -1 )
- printf("BFS - Encontrou. Distancia: %d.\n", res);
- else
- printf("BFS - Não encontrou.\n");
-
- return 0;
+int main() {
+
+ // Grafo conjunto de vértices independentes
+ VERTICE A = criaVertice('A');
+ VERTICE B = criaVertice('B');
+ VERTICE C = criaVertice('C');
+ VERTICE D = criaVertice('D');
+ VERTICE E = criaVertice('E');
+ VERTICE F = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(A, B);
+ ligaVertices(A, C);
+ ligaVertices(B, D);
+ ligaVertices(C, D);
+ ligaVertices(B, E);
+ ligaVertices(D, E);
+ ligaVertices(E, F);
+ ligaVertices(D, F);
+
+ // Realiza a busca em profundidade
+ int res = buscaEmProfundidade(A, F, 0);
+ if (res != -1)
+ printf("DFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("DFS - Não encontrou.\n");
+
+ // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
+ A->visitado = false;
+ B->visitado = false;
+ C->visitado = false;
+ D->visitado = false;
+ E->visitado = false;
+ F->visitado = false;
+
+ // Realiza a busca em largura
+ res = buscaEmLargura(A, F);
+ if (res != -1)
+ printf("BFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("BFS - Não encontrou.\n");
+
+ // Grafo conjunto de vértices em um array
+ VERTICE GRAFO[MAX_VERTICES];
+ GRAFO[0] = criaVertice('A');
+ GRAFO[1] = criaVertice('B');
+ GRAFO[2] = criaVertice('C');
+ GRAFO[3] = criaVertice('D');
+ GRAFO[4] = criaVertice('E');
+ GRAFO[5] = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(GRAFO[0], GRAFO[1]);
+ ligaVertices(GRAFO[0], GRAFO[2]);
+ ligaVertices(GRAFO[1], GRAFO[3]);
+ ligaVertices(GRAFO[2], GRAFO[3]);
+ ligaVertices(GRAFO[1], GRAFO[4]);
+ ligaVertices(GRAFO[3], GRAFO[4]);
+ ligaVertices(GRAFO[4], GRAFO[5]);
+ ligaVertices(GRAFO[3], GRAFO[5]);
+
+ // Realiza a busca em profundidade
+ res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0);
+ if (res != -1)
+ printf("DFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("DFS - Não encontrou.\n");
+
+ // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false'
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ GRAFO[i]->visitado = false;
+ }
+
+ // Realiza a busca em largura
+ res = buscaEmLargura(GRAFO[0], GRAFO[5]);
+ if (res != -1)
+ printf("BFS - Encontrou. Distancia: %d.\n", res);
+ else
+ printf("BFS - Não encontrou.\n");
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Graphs.c b/src/c/Graphs.c
index bd46e85a..85495e11 100644
--- a/src/c/Graphs.c
+++ b/src/c/Graphs.c
@@ -1,125 +1,126 @@
/*
-*
-*
-* ---------------------
-* | |
-* | |
-* 5 V 8 |
-* (A)------------->(B)------------ | 2
-* \ | |
-* \ | |
-* \ 6 4 V |
-* ---------->(C)--------->(D)------
-*
-*
-*/
+ *
+ *
+ * ---------------------
+ * | |
+ * | |
+ * 5 V 8 |
+ * (A)------------->(B)------------ | 2
+ * \ | |
+ * \ | |
+ * \ 6 4 V |
+ * ---------->(C)--------->(D)------
+ *
+ *
+ */
-#include
#include
+#include
-#define MAX_VERTICES 20 // Constante que define o máximo de vertices que o grafo pode ter
+#define MAX_VERTICES \
+ 20 // Constante que define o máximo de vertices que o grafo pode ter
-int nroVertices = 0; // Guarda o número de vértices atual
+int nroVertices = 0; // Guarda o número de vértices atual
int matriz[MAX_VERTICES][MAX_VERTICES]; // Matriz de Distancia
int componentes;
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct AUX* vizinhos[];
- bool visitado;
- int indice; // Guarda a ordem em que o vértice foi criado
-}*VERTICE;
-
-typedef struct AUX{
- VERTICE vizinho;
- int valor;
-}*ARESTA;
-
-VERTICE criaVertice(char id){
- matriz[nroVertices][nroVertices] = 0;
- VERTICE novo = (VERTICE) malloc( sizeof(NO) );
- novo->id = id;
- novo->nroVizinhos = 0;
- novo->visitado = false;
- novo->indice = nroVertices;
- nroVertices++;
- return novo;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct AUX *vizinhos[];
+ bool visitado;
+ int indice; // Guarda a ordem em que o vértice foi criado
+} *VERTICE;
+
+typedef struct AUX {
+ VERTICE vizinho;
+ int valor;
+} *ARESTA;
+
+VERTICE criaVertice(char id) {
+ matriz[nroVertices][nroVertices] = 0;
+ VERTICE novo = (VERTICE)malloc(sizeof(NO));
+ novo->id = id;
+ novo->nroVizinhos = 0;
+ novo->visitado = false;
+ novo->indice = nroVertices;
+ nroVertices++;
+ return novo;
}
-void ligaVertice(VERTICE v1, VERTICE v2, int valor){
- matriz[v1->indice][v2->indice] = valor;
- ARESTA nova = (ARESTA) malloc( sizeof(AUX) );
- nova->vizinho = v2;
- nova->valor = valor;
- v1->vizinhos[v1->nroVizinhos] = nova;
- v1->nroVizinhos++;
+void ligaVertice(VERTICE v1, VERTICE v2, int valor) {
+ matriz[v1->indice][v2->indice] = valor;
+ ARESTA nova = (ARESTA)malloc(sizeof(AUX));
+ nova->vizinho = v2;
+ nova->valor = valor;
+ v1->vizinhos[v1->nroVizinhos] = nova;
+ v1->nroVizinhos++;
}
-void mostraMatrizDistancia(){
- printf("\nMatriz de Distancia\n");
- for(int l = 0; l < nroVertices; l++){
- for(int c = 0; c < nroVertices; c++){
- if( matriz[l][c] == -1 )
- printf("%d, ", matriz[l][c]);
- else
- printf(" %d, ", matriz[l][c]);
- }
- printf("\n");
- }
- printf("\n");
+void mostraMatrizDistancia() {
+ printf("\nMatriz de Distancia\n");
+ for (int l = 0; l < nroVertices; l++) {
+ for (int c = 0; c < nroVertices; c++) {
+ if (matriz[l][c] == -1)
+ printf("%d, ", matriz[l][c]);
+ else
+ printf(" %d, ", matriz[l][c]);
+ }
+ printf("\n");
+ }
+ printf("\n");
}
-void zeraVariaveis(){
- for(int l = 0; l < MAX_VERTICES; l++){
- for(int c = 0; c < MAX_VERTICES; c++){
- matriz[l][c] = -1;
- }
- }
+void zeraVariaveis() {
+ for (int l = 0; l < MAX_VERTICES; l++) {
+ for (int c = 0; c < MAX_VERTICES; c++) {
+ matriz[l][c] = -1;
+ }
+ }
}
-void visitaVizinhos(bool visitados[], int atual){
- for (int i = 0; i < nroVertices; i++){
- if( visitados[i] == false && matriz[atual][i] > 0 ){
- visitados[i] = true;
- componentes++;
- visitaVizinhos(visitados, i);
- }
- }
+void visitaVizinhos(bool visitados[], int atual) {
+ for (int i = 0; i < nroVertices; i++) {
+ if (visitados[i] == false && matriz[atual][i] > 0) {
+ visitados[i] = true;
+ componentes++;
+ visitaVizinhos(visitados, i);
+ }
+ }
}
-void calculaComponentesConexos(){
- bool visitados[nroVertices];
- for (int i = 0; i < nroVertices; ++i){
- visitados[i] = false;
- }
- for (int i = 0; i < nroVertices; i++){
- if( visitados[i] == false ){
- visitaVizinhos(visitados, i);
- }
- }
+void calculaComponentesConexos() {
+ bool visitados[nroVertices];
+ for (int i = 0; i < nroVertices; ++i) {
+ visitados[i] = false;
+ }
+ for (int i = 0; i < nroVertices; i++) {
+ if (visitados[i] == false) {
+ visitaVizinhos(visitados, i);
+ }
+ }
}
-int main(){
- zeraVariaveis();
-
- // Matriz de Distância funciona conforme a ordem inserida
- VERTICE A = criaVertice('A');
- VERTICE B = criaVertice('B');
- VERTICE C = criaVertice('C');
- VERTICE D = criaVertice('D');
- VERTICE E = criaVertice('E');
-
- ligaVertice(A, B, 5);
- ligaVertice(A, C, 6);
- ligaVertice(B, D, 8);
- ligaVertice(C, D, 4);
- ligaVertice(D, B, 2);
-
- calculaComponentesConexos();
- printf("\nComponentes Conexos: %d\n", componentes) ;
-
- mostraMatrizDistancia();
-
- return 0;
+int main() {
+ zeraVariaveis();
+
+ // Matriz de Distância funciona conforme a ordem inserida
+ VERTICE A = criaVertice('A');
+ VERTICE B = criaVertice('B');
+ VERTICE C = criaVertice('C');
+ VERTICE D = criaVertice('D');
+ VERTICE E = criaVertice('E');
+
+ ligaVertice(A, B, 5);
+ ligaVertice(A, C, 6);
+ ligaVertice(B, D, 8);
+ ligaVertice(C, D, 4);
+ ligaVertice(D, B, 2);
+
+ calculaComponentesConexos();
+ printf("\nComponentes Conexos: %d\n", componentes);
+
+ mostraMatrizDistancia();
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/HamiltonianCycle.c b/src/c/HamiltonianCycle.c
index f54c950c..aea872f6 100644
--- a/src/c/HamiltonianCycle.c
+++ b/src/c/HamiltonianCycle.c
@@ -1,133 +1,143 @@
/*
-*
-* Grafos - CICLO HAMILTONIANO em C
-*
-* -----------------------------------
-* | |
-* (A)---------------(B)-------------(E)---------------(F)
-* | | | |
-* | | | |
-* | | | |
-* (C)---------------(D)--------------- |
-* | |
-* -----------------------------------
-*
-* 6 Vértices
-* 9 Arestas
-*/
+ *
+ * Grafos - CICLO HAMILTONIANO em C
+ *
+ * -----------------------------------
+ * | |
+ * (A)---------------(B)-------------(E)---------------(F)
+ * | | | |
+ * | | | |
+ * | | | |
+ * (C)---------------(D)--------------- |
+ * | |
+ * -----------------------------------
+ *
+ * 6 Vértices
+ * 9 Arestas
+ */
-#include
#include
+#include
-#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM
-#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
+#define MAX_VERTICES \
+ 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA
+ // VARIÁVEL TAMBÉM
+#define MAX_ARESTAS \
+ (MAX_VERTICES * \
+ (MAX_VERTICES - \
+ 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER
// Estrutura que define cada Vértice do Grafo
-typedef struct NO{
- char id;
- int nroVizinhos;
- struct NO* vizinhos[MAX_ARESTAS];
- bool visitado;
-}*VERTICE;
+typedef struct NO {
+ char id;
+ int nroVizinhos;
+ struct NO *vizinhos[MAX_ARESTAS];
+ bool visitado;
+} *VERTICE;
-VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo hamiltoniano
+VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo
+ // hamiltoniano
// Cria Vértice e retorna
-VERTICE criaVertice(char id){
- VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice
- novoVertice->id = id;
- novoVertice->nroVizinhos = 0;
- novoVertice->visitado = false;
- for (int i = 0; i < MAX_ARESTAS; i++){
- novoVertice->vizinhos[i] = NULL;
- }
- return novoVertice;
+VERTICE criaVertice(char id) {
+ VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice
+ novoVertice->id = id;
+ novoVertice->nroVizinhos = 0;
+ novoVertice->visitado = false;
+ for (int i = 0; i < MAX_ARESTAS; i++) {
+ novoVertice->vizinhos[i] = NULL;
+ }
+ return novoVertice;
}
// Liga os vértices passados como parâmetro
-bool ligaVertices(VERTICE v1, VERTICE v2){
- int aux = 0;
- while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
- aux = 0;
- while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos
- aux++;
- }
- v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
- v1->nroVizinhos++; // Incrementa o número de vizinhos
- v2->nroVizinhos++; // Incrementa o número de vizinhos
+bool ligaVertices(VERTICE v1, VERTICE v2) {
+ int aux = 0;
+ while (v1->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos
+ aux = 0;
+ while (v2->vizinhos[aux] !=
+ NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos
+ aux++;
+ }
+ v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos
+ v1->nroVizinhos++; // Incrementa o número de vizinhos
+ v2->nroVizinhos++; // Incrementa o número de vizinhos
}
-bool cicloHamiltonianoAuxiliar(int aux){
-
- if( aux == MAX_VERTICES ){
- for (int i = 0; i < solucao[aux-1]->nroVizinhos; i++){
- if( solucao[aux-1]->vizinhos[i] == solucao[0] ){
- return true;
- }
- }
- return false;
- }
-
- VERTICE s = solucao[aux-1]; // Auxiliar para simplificar o código
-
- for (int i = 0; i < s->nroVizinhos; i++){ // Percorre todos os vizinhos do vértice de posição aux-1 no array solução
- if( s->vizinhos[i]->visitado == false ){
- s->vizinhos[i]->visitado = true;
- solucao[aux] = s->vizinhos[i];
- if( cicloHamiltonianoAuxiliar(aux+1) == true ){
- return true;
- }
- s->vizinhos[i]->visitado = false;
- }
- }
-
- return false;
+bool cicloHamiltonianoAuxiliar(int aux) {
+
+ if (aux == MAX_VERTICES) {
+ for (int i = 0; i < solucao[aux - 1]->nroVizinhos; i++) {
+ if (solucao[aux - 1]->vizinhos[i] == solucao[0]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ VERTICE s = solucao[aux - 1]; // Auxiliar para simplificar o código
+
+ for (int i = 0; i < s->nroVizinhos;
+ i++) { // Percorre todos os vizinhos do vértice de posição aux-1 no array
+ // solução
+ if (s->vizinhos[i]->visitado == false) {
+ s->vizinhos[i]->visitado = true;
+ solucao[aux] = s->vizinhos[i];
+ if (cicloHamiltonianoAuxiliar(aux + 1) == true) {
+ return true;
+ }
+ s->vizinhos[i]->visitado = false;
+ }
+ }
+
+ return false;
}
-bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]){
- grafo[0]->visitado = true; // Marca a posição inicial como visitada
- solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo
- return cicloHamiltonianoAuxiliar(1);
+bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]) {
+ grafo[0]->visitado = true; // Marca a posição inicial como visitada
+ solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo
+ return cicloHamiltonianoAuxiliar(1);
}
-int main(){
-
- // Grafo conjunto de vértices em um array
- VERTICE GRAFO[MAX_VERTICES];
- GRAFO[0] = criaVertice('A');
- GRAFO[1] = criaVertice('B');
- GRAFO[2] = criaVertice('C');
- GRAFO[3] = criaVertice('D');
- GRAFO[4] = criaVertice('E');
- GRAFO[5] = criaVertice('F');
-
- // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
- ligaVertices(GRAFO[0], GRAFO[1]); // A - B
- ligaVertices(GRAFO[0], GRAFO[2]); // A - C
- ligaVertices(GRAFO[1], GRAFO[3]); // B - D
- ligaVertices(GRAFO[2], GRAFO[3]); // D - C
- ligaVertices(GRAFO[1], GRAFO[4]); // B - E
- ligaVertices(GRAFO[3], GRAFO[4]); // D - E
- ligaVertices(GRAFO[4], GRAFO[5]); // E - F
- ligaVertices(GRAFO[3], GRAFO[5]); // D - F
- ligaVertices(GRAFO[1], GRAFO[5]); // B - F
-
- for (int i = 0; i < MAX_VERTICES; i++){
- solucao[i] = criaVertice('0');
- }
-
- if( cicloHamiltoniano(GRAFO) ){
- printf("Ciclo Hamiltoniano:\n");
- for (int i = 0; i < MAX_VERTICES; i++){
- printf("%c, ",solucao[i]->id);
- }
- printf("\n\n");
- }else{
- printf("Nao possui Ciclo Hamiltoniano\n");
- }
-
- return 0;
+int main() {
+
+ // Grafo conjunto de vértices em um array
+ VERTICE GRAFO[MAX_VERTICES];
+ GRAFO[0] = criaVertice('A');
+ GRAFO[1] = criaVertice('B');
+ GRAFO[2] = criaVertice('C');
+ GRAFO[3] = criaVertice('D');
+ GRAFO[4] = criaVertice('E');
+ GRAFO[5] = criaVertice('F');
+
+ // Liga todos os vértices de acordo com o GRAFO apresentado na introdução
+ ligaVertices(GRAFO[0], GRAFO[1]); // A - B
+ ligaVertices(GRAFO[0], GRAFO[2]); // A - C
+ ligaVertices(GRAFO[1], GRAFO[3]); // B - D
+ ligaVertices(GRAFO[2], GRAFO[3]); // D - C
+ ligaVertices(GRAFO[1], GRAFO[4]); // B - E
+ ligaVertices(GRAFO[3], GRAFO[4]); // D - E
+ ligaVertices(GRAFO[4], GRAFO[5]); // E - F
+ ligaVertices(GRAFO[3], GRAFO[5]); // D - F
+ ligaVertices(GRAFO[1], GRAFO[5]); // B - F
+
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ solucao[i] = criaVertice('0');
+ }
+
+ if (cicloHamiltoniano(GRAFO)) {
+ printf("Ciclo Hamiltoniano:\n");
+ for (int i = 0; i < MAX_VERTICES; i++) {
+ printf("%c, ", solucao[i]->id);
+ }
+ printf("\n\n");
+ } else {
+ printf("Nao possui Ciclo Hamiltoniano\n");
+ }
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Heapsort.c b/src/c/Heapsort.c
index ca6e1699..4437c6e9 100644
--- a/src/c/Heapsort.c
+++ b/src/c/Heapsort.c
@@ -1,66 +1,61 @@
#include
-void heapify(int arr[], int n, int i)
-{
- int largest = i;
- int left = 2 * i + 1;
- int right = 2 * i + 2;
-
- if (left < n && arr[left] > arr[largest])
- largest = left;
-
- // If the right child is larger than the largest so far
- if (right < n && arr[right] > arr[largest])
- largest = right;
-
- // If the largest element is not the root
- if (largest != i)
- {
- // Swap the largest element with the root
- int temp = arr[i];
- arr[i] = arr[largest];
- arr[largest] = temp;
-
- // Recursively heapify the affected sub-tree
- heapify(arr, n, largest);
- }
+void heapify(int arr[], int n, int i) {
+ int largest = i;
+ int left = 2 * i + 1;
+ int right = 2 * i + 2;
+
+ if (left < n && arr[left] > arr[largest])
+ largest = left;
+
+ // If the right child is larger than the largest so far
+ if (right < n && arr[right] > arr[largest])
+ largest = right;
+
+ // If the largest element is not the root
+ if (largest != i) {
+ // Swap the largest element with the root
+ int temp = arr[i];
+ arr[i] = arr[largest];
+ arr[largest] = temp;
+
+ // Recursively heapify the affected sub-tree
+ heapify(arr, n, largest);
+ }
}
-void heapsort(int arr[], int n)
-{
- // Build a max heap
- int i;
- for (i = n / 2 - 1; i >= 0; i--)
- heapify(arr, n, i);
-
- // One by one extract elements from the heap
- for (i = n - 1; i > 0; i--)
- {
- // Move the current root to the end
- int temp = arr[0];
- arr[0] = arr[i];
- arr[i] = temp;
-
- // Call max heapify on the reduced heap
- heapify(arr, i, 0);
- }
+void heapsort(int arr[], int n) {
+ // Build a max heap
+ int i;
+ for (i = n / 2 - 1; i >= 0; i--)
+ heapify(arr, n, i);
+
+ // One by one extract elements from the heap
+ for (i = n - 1; i > 0; i--) {
+ // Move the current root to the end
+ int temp = arr[0];
+ arr[0] = arr[i];
+ arr[i] = temp;
+
+ // Call max heapify on the reduced heap
+ heapify(arr, i, 0);
+ }
}
-int main()
-{
- int arr[] = {12, 21, 13, 5, 1, 7};
- int i;
- int n = sizeof(arr) / sizeof(arr[0]);
+int main() {
+ int arr[] = {12, 21, 13, 5, 1, 7};
+ int i;
+ int n = sizeof(arr) / sizeof(arr[0]);
- printf("Original array: ");
- for (i = 0; i < n; i++)
- printf("%d ", arr[i]);
+ printf("Original array: ");
+ for (i = 0; i < n; i++)
+ printf("%d ", arr[i]);
- heapsort(arr, n);
+ heapsort(arr, n);
- printf("\nSorted array: ");
- for (i = 0; i < n; i++)
- printf("%d ", arr[i]);
+ printf("\nSorted array: ");
+ for (i = 0; i < n; i++)
+ printf("%d ", arr[i]);
- return 0;
+ return 0;
}
diff --git a/src/c/InsertionSort.c b/src/c/InsertionSort.c
index 69c9b8fb..5605bd91 100644
--- a/src/c/InsertionSort.c
+++ b/src/c/InsertionSort.c
@@ -4,45 +4,48 @@ Algoritmo de ordenação Insertion Sort em C
#include // Necessário para usar input e output
#include // Necessário para usar a função rand()
-#include // Necessário para inicializar a semente de números aleatórios
+#include // Necessário para inicializar a semente de números aleatórios
-// Definimos a função insertion_sort que recebe como argumento o vetor a ser ordenado e seu tamanho n
+// Definimos a função insertion_sort que recebe como argumento o vetor a ser
+// ordenado e seu tamanho n
void insertion_sort(int arr[], int n) {
- int i, j, key;
- // Percorremos todos os elementos do vetor a partir do segundo elemento
- for (i = 1; i < n; i++) {
- // Armazenamos o valor do elemento atual em key
- key = arr[i];
- // Inicializamos o índice j como o elemento anterior ao elemento atual
- j = i - 1;
- // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o elemento na posição j do vetor,
- // movemos o elemento na posição j uma posição para a direita e decrementamos j
- while (j >= 0 && arr[j] > key) {
- arr[j + 1] = arr[j];
- j = j - 1;
- }
- // Quando o loop interno termina, colocamos o elemento atual em sua posição correta
- arr[j + 1] = key;
+ int i, j, key;
+ // Percorremos todos os elementos do vetor a partir do segundo elemento
+ for (i = 1; i < n; i++) {
+ // Armazenamos o valor do elemento atual em key
+ key = arr[i];
+ // Inicializamos o índice j como o elemento anterior ao elemento atual
+ j = i - 1;
+ // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o
+ // elemento na posição j do vetor, movemos o elemento na posição j uma
+ // posição para a direita e decrementamos j
+ while (j >= 0 && arr[j] > key) {
+ arr[j + 1] = arr[j];
+ j = j - 1;
}
+ // Quando o loop interno termina, colocamos o elemento atual em sua posição
+ // correta
+ arr[j + 1] = key;
+ }
}
// Função principal
int main() {
- int i, n, arr[100];
- srand(time(NULL)); // Inicializa a semente de números aleatórios
- printf("Entre com o numero de elementos no vetor: ");
- scanf("%d", &n);
- printf("Vetor de entrada:\n");
- for (i = 0; i < n; i++) {
- arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99
- printf("%d ", arr[i]); // Imprime o valor gerado
- }
- printf("\n");
- insertion_sort(arr, n);
- printf("Vetor ordenado em ordem crescente:\n");
- for (i = 0; i < n; i++) {
- printf("%d ", arr[i]);
- }
- printf("\n");
- return 0;
+ int i, n, arr[100];
+ srand(time(NULL)); // Inicializa a semente de números aleatórios
+ printf("Entre com o numero de elementos no vetor: ");
+ scanf("%d", &n);
+ printf("Vetor de entrada:\n");
+ for (i = 0; i < n; i++) {
+ arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99
+ printf("%d ", arr[i]); // Imprime o valor gerado
+ }
+ printf("\n");
+ insertion_sort(arr, n);
+ printf("Vetor ordenado em ordem crescente:\n");
+ for (i = 0; i < n; i++) {
+ printf("%d ", arr[i]);
+ }
+ printf("\n");
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/LinearSearch.c b/src/c/LinearSearch.c
index bf28b592..39e5c991 100644
--- a/src/c/LinearSearch.c
+++ b/src/c/LinearSearch.c
@@ -1,21 +1,18 @@
#include
int buscaSequencial(int vetor[], int size, int buscado) {
- for (int i = 0; i < size; i++)
- {
- if (vetor[i] == buscado)
- {
- return i;
- }
+ for (int i = 0; i < size; i++) {
+ if (vetor[i] == buscado) {
+ return i;
}
- return -1;
+ }
+ return -1;
}
-int main(){
+int main() {
- int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
- int n = sizeof(a) / sizeof(a[0]);
- printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3));
- printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9));
+ int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
+ int n = sizeof(a) / sizeof(a[0]);
+ printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3));
+ printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9));
}
-
diff --git a/src/c/LinearSearchRecursive.c b/src/c/LinearSearchRecursive.c
index ef5159a3..ffdb2001 100644
--- a/src/c/LinearSearchRecursive.c
+++ b/src/c/LinearSearchRecursive.c
@@ -1,25 +1,22 @@
#include
int buscaSequencialRecursiva(int vetor[], int i, int buscado, int size) {
-
- if (i == size)
- {
- return -1;
- }
- else if (vetor[i] == buscado)
- {
- return i;
- }
- else
- {
- return buscaSequencialRecursiva(vetor, i+1, buscado, size);
- }
+
+ if (i == size) {
+ return -1;
+ } else if (vetor[i] == buscado) {
+ return i;
+ } else {
+ return buscaSequencialRecursiva(vetor, i + 1, buscado, size);
+ }
}
-int main(){
+int main() {
- int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8};
- size_t n = sizeof(vetor) / sizeof(vetor[0]);
- printf("Valor %d no índice %d\n", 1, buscaSequencialRecursiva(vetor, 0, 1, n));
- printf("Valor %d no índice %d\n", 10, buscaSequencialRecursiva(vetor, 0, 10, n));
+ int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8};
+ size_t n = sizeof(vetor) / sizeof(vetor[0]);
+ printf("Valor %d no índice %d\n", 1,
+ buscaSequencialRecursiva(vetor, 0, 1, n));
+ printf("Valor %d no índice %d\n", 10,
+ buscaSequencialRecursiva(vetor, 0, 10, n));
}
diff --git a/src/c/LinearSearchSentinel.c b/src/c/LinearSearchSentinel.c
index 67f32822..37071d8b 100644
--- a/src/c/LinearSearchSentinel.c
+++ b/src/c/LinearSearchSentinel.c
@@ -1,7 +1,8 @@
/*
-* Exemplo de Busca Sentinela em C
-* Objetivo: Encontrar um valor em um vetor sem precisar testar todos os valores dentro do laço
-*/
+ * Exemplo de Busca Sentinela em C
+ * Objetivo: Encontrar um valor em um vetor sem precisar testar todos os
+ *valores dentro do laço
+ */
#include
#include
@@ -9,35 +10,41 @@
#define TAM_VETOR 10
-// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a cada passo do laço de busca
-int buscaSentinela(int vetor[], int chave){
- vetor[TAM_VETOR] = chave; // Coloca o valor buscado (chave) na última posição do vetor
- int aux = 0; // Variável de controle do laço
- while( vetor[aux] != chave ) // Enquanto não encontrar o valor (chave) incrementa 1 em aux
- aux++;
- if( aux == TAM_VETOR ) // Caso o valor de aux seja igual ao tamanho do vetor, significa que foi até o final e não encontrou o valor
- return -1; // Não encontrou
- else // Caso aux seja diferente, significa que encontrou o valor e quebrou o laço, o aux é a posição do valor buscado
- return aux; // Encontrou
+// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a
+// cada passo do laço de busca
+int buscaSentinela(int vetor[], int chave) {
+ vetor[TAM_VETOR] =
+ chave; // Coloca o valor buscado (chave) na última posição do vetor
+ int aux = 0; // Variável de controle do laço
+ while (vetor[aux] !=
+ chave) // Enquanto não encontrar o valor (chave) incrementa 1 em aux
+ aux++;
+ if (aux == TAM_VETOR) // Caso o valor de aux seja igual ao tamanho do vetor,
+ // significa que foi até o final e não encontrou o valor
+ return -1; // Não encontrou
+ else // Caso aux seja diferente, significa que encontrou o valor e quebrou o
+ // laço, o aux é a posição do valor buscado
+ return aux; // Encontrou
}
-int main(){
+int main() {
- int vetor[TAM_VETOR+1]; // Declara o vetor com +1 pois é a posição que será utilizada pela sentinela
+ int vetor[TAM_VETOR + 1]; // Declara o vetor com +1 pois é a posição que será
+ // utilizada pela sentinela
- // Preenche o vetor com valores aleatórios 0-1000
- srand(time(NULL));
- for(int i = 0; i < TAM_VETOR; i++){
- vetor[i] = rand()%1000;
- printf("%d, ", vetor[i]);
- }
+ // Preenche o vetor com valores aleatórios 0-1000
+ srand(time(NULL));
+ for (int i = 0; i < TAM_VETOR; i++) {
+ vetor[i] = rand() % 1000;
+ printf("%d, ", vetor[i]);
+ }
- // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar
- int res = buscaSentinela(vetor, vetor[TAM_VETOR-2]);
- if( res != -1 )
- printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res);
- else
- printf("\n\nValor não encontrado no vetor\n\n");
+ // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar
+ int res = buscaSentinela(vetor, vetor[TAM_VETOR - 2]);
+ if (res != -1)
+ printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res);
+ else
+ printf("\n\nValor não encontrado no vetor\n\n");
- return 0;
+ return 0;
}
diff --git a/src/c/MaxRecursive.c b/src/c/MaxRecursive.c
index 9c9ac09e..b173c575 100644
--- a/src/c/MaxRecursive.c
+++ b/src/c/MaxRecursive.c
@@ -1,7 +1,7 @@
/*
-* Exemplos de funções para achar maior número de um vetor
-* As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista
-*/
+ * Exemplos de funções para achar maior número de um vetor
+ * As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista
+ */
#include
#include
@@ -9,81 +9,62 @@
#define MAX 10
// Maximo usando Divisão e Conquista
-int MaxDC(int *vetor, int inicio, int fim)
-{
- int aux1, aux2;
- int meio = ( inicio + fim ) / 2;
+int MaxDC(int *vetor, int inicio, int fim) {
+ int aux1, aux2;
+ int meio = (inicio + fim) / 2;
- if( inicio == fim )
- {
- return vetor[inicio];
- }
+ if (inicio == fim) {
+ return vetor[inicio];
+ }
- aux1 = MaxDC(vetor, inicio, meio);
- aux2 = MaxDC(vetor, meio+1, fim);
+ aux1 = MaxDC(vetor, inicio, meio);
+ aux2 = MaxDC(vetor, meio + 1, fim);
- if( aux1 > aux2 )
- {
- return aux1;
- }
- else
- {
- return aux2;
- }
+ if (aux1 > aux2) {
+ return aux1;
+ } else {
+ return aux2;
+ }
}
-void max1(int *vetor, int maximo, int indice)
-{
- if( vetor[indice] > maximo )
- {
- maximo = vetor[indice];
- }
+void max1(int *vetor, int maximo, int indice) {
+ if (vetor[indice] > maximo) {
+ maximo = vetor[indice];
+ }
- if( indice < MAX-1 )
- {
- max1(vetor, maximo, indice+1);
- }
- else
- {
- printf("\n\nMax1: %d\n",maximo);
- }
+ if (indice < MAX - 1) {
+ max1(vetor, maximo, indice + 1);
+ } else {
+ printf("\n\nMax1: %d\n", maximo);
+ }
}
-int max2(int vetor[], int tamVetor)
-{
- if (tamVetor == 1)
- {
- return vetor[0]; // só tem 1 elemento
- }
- else
- {
- int x = max2(vetor, tamVetor-1);
+int max2(int vetor[], int tamVetor) {
+ if (tamVetor == 1) {
+ return vetor[0]; // só tem 1 elemento
+ } else {
+ int x = max2(vetor, tamVetor - 1);
- if (x > vetor[tamVetor-1])
- {
- return x;
- }
- else
- {
- return vetor[tamVetor-1];
- }
+ if (x > vetor[tamVetor - 1]) {
+ return x;
+ } else {
+ return vetor[tamVetor - 1];
}
+ }
}
-int main()
-{
- int vetor[MAX];
+int main() {
+ int vetor[MAX];
- for (int i = 0; i < MAX; ++i)
- {
- vetor[i] = (rand() % 90) + 10; // 10 a 99
- printf("%d, ", vetor[i]);
- }
+ for (int i = 0; i < MAX; ++i) {
+ vetor[i] = (rand() % 90) + 10; // 10 a 99
+ printf("%d, ", vetor[i]);
+ }
- max1(vetor, vetor[0], 1);
+ max1(vetor, vetor[0], 1);
- printf("\nMax2: %d\n", max2(vetor, MAX) );
- printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX-1) );
+ printf("\nMax2: %d\n", max2(vetor, MAX));
+ printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX - 1));
- return 0;
+ return 0;
}
diff --git a/src/c/MergeSort.c b/src/c/MergeSort.c
index f536e462..f3470e26 100644
--- a/src/c/MergeSort.c
+++ b/src/c/MergeSort.c
@@ -1,13 +1,13 @@
/*
-* Exemplo de Ordenação utilizando Merge Sort
-*
-* Dividir para conquistar:
-*
-* Dividir: Dividir os dados em subsequências pequenas;
-* Conquistar: Classificar as duas metades recursivamente aplicando o merge sort;
-* Combinar: Juntar as duas metades em um único conjunto já classificado.
-*
-*/
+ * Exemplo de Ordenação utilizando Merge Sort
+ *
+ * Dividir para conquistar:
+ *
+ * Dividir: Dividir os dados em subsequências pequenas;
+ * Conquistar: Classificar as duas metades recursivamente aplicando o merge
+ *sort; Combinar: Juntar as duas metades em um único conjunto já classificado.
+ *
+ */
#include
#include
@@ -20,54 +20,53 @@ void merge(int vetor[], int tamanho) {
int i = 0, j = meio, k = 0;
int aux[tamanho];
- while( i < meio && j < tamanho ){
- if( vetor[i] <= vetor[j] )
+ while (i < meio && j < tamanho) {
+ if (vetor[i] <= vetor[j])
aux[k] = vetor[i++];
else
aux[k] = vetor[j++];
k++;
}
-
- if( i == meio )
- while( j < tamanho )
+
+ if (i == meio)
+ while (j < tamanho)
aux[k++] = vetor[j++];
else
- while( i < meio )
+ while (i < meio)
aux[k++] = vetor[i++];
-
- for( i = 0; i < tamanho; i++ )
+
+ for (i = 0; i < tamanho; i++)
vetor[i] = aux[i];
}
-
-int mergeSort(int vetor[], int tamanho){
- int meio = tamanho / 2;
- if( tamanho > 1 ){
- mergeSort(vetor, meio);
- mergeSort(vetor + meio, tamanho - meio);
- merge(vetor, tamanho);
- }
+int mergeSort(int vetor[], int tamanho) {
+ int meio = tamanho / 2;
+ if (tamanho > 1) {
+ mergeSort(vetor, meio);
+ mergeSort(vetor + meio, tamanho - meio);
+ merge(vetor, tamanho);
+ }
}
-int main(){
+int main() {
+
+ int vetor[TAM_VETOR];
- int vetor[TAM_VETOR];
-
- // Preenche o vetor com valores aleatórios 0-1000
- srand(time(NULL));
- for(int i = 0; i < TAM_VETOR; i++){
- vetor[i] = rand()%1000;
- printf("%d, ", vetor[i]);
- }
-
- printf("\n\n");
-
- mergeSort(vetor, TAM_VETOR);
+ // Preenche o vetor com valores aleatórios 0-1000
+ srand(time(NULL));
+ for (int i = 0; i < TAM_VETOR; i++) {
+ vetor[i] = rand() % 1000;
+ printf("%d, ", vetor[i]);
+ }
+
+ printf("\n\n");
+
+ mergeSort(vetor, TAM_VETOR);
+
+ for (int i = 0; i < TAM_VETOR; i++) {
+ printf("%d, ", vetor[i]);
+ }
- for(int i = 0; i < TAM_VETOR; i++){
- printf("%d, ", vetor[i]);
- }
-
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/MinMaxDC.c b/src/c/MinMaxDC.c
index b45f0205..aac43e07 100644
--- a/src/c/MinMaxDC.c
+++ b/src/c/MinMaxDC.c
@@ -10,48 +10,48 @@
* @param max Pointer to store the maximum element
*/
-void MinAndMax(int arr[], int left, int right, int* min, int* max) {
- // if there is only one element in the sub-array, set it as both min and max
- if (left == right) {
- *min = *max = arr[left];
- return;
+void MinAndMax(int arr[], int left, int right, int *min, int *max) {
+ // if there is only one element in the sub-array, set it as both min and max
+ if (left == right) {
+ *min = *max = arr[left];
+ return;
+ }
+
+ // if there are two elements in the sub-array, compare and set min and max
+ if (right - left == 1) {
+ if (arr[left] < arr[right]) {
+ *min = arr[left];
+ *max = arr[right];
+ } else {
+ *min = arr[right];
+ *max = arr[left];
}
+ return;
+ }
- // if there are two elements in the sub-array, compare and set min and max
- if (right - left == 1) {
- if (arr[left] < arr[right]) {
- *min = arr[left];
- *max = arr[right];
- } else {
- *min = arr[right];
- *max = arr[left];
- }
- return;
- }
-
- // calculate the middle index of the sub-array
- int mid = (left + right) / 2;
- int leftMin, leftMax, rightMin, rightMax;
+ // calculate the middle index of the sub-array
+ int mid = (left + right) / 2;
+ int leftMin, leftMax, rightMin, rightMax;
- // recursively find min and max in the left and right sub-arrays
- MinAndMax(arr, left, mid, &leftMin, &leftMax);
- MinAndMax(arr, mid + 1, right, &rightMin, &rightMax);
+ // recursively find min and max in the left and right sub-arrays
+ MinAndMax(arr, left, mid, &leftMin, &leftMax);
+ MinAndMax(arr, mid + 1, right, &rightMin, &rightMax);
- // update the minimum and maximum values
- *min = (leftMin < rightMin) ? leftMin : rightMin;
- *max = (leftMax > rightMax) ? leftMax : rightMax;
+ // update the minimum and maximum values
+ *min = (leftMin < rightMin) ? leftMin : rightMin;
+ *max = (leftMax > rightMax) ? leftMax : rightMax;
}
int main() {
- int arr[] = {10, 5, 20, 8, 15, 30, -12, 24};
- int arrSize = sizeof(arr) / sizeof(arr[0]);
+ int arr[] = {10, 5, 20, 8, 15, 30, -12, 24};
+ int arrSize = sizeof(arr) / sizeof(arr[0]);
- int min, max;
+ int min, max;
- MinAndMax(arr, 0, arrSize - 1, &min, &max);
+ MinAndMax(arr, 0, arrSize - 1, &min, &max);
- printf("Minimum element: %d\n", min);
- printf("Maximum element: %d\n", max);
+ printf("Minimum element: %d\n", min);
+ printf("Maximum element: %d\n", max);
- return 0;
+ return 0;
}
diff --git a/src/c/MinMaxIterative.c b/src/c/MinMaxIterative.c
index 87fda2c0..0ae3e0b9 100644
--- a/src/c/MinMaxIterative.c
+++ b/src/c/MinMaxIterative.c
@@ -1,23 +1,23 @@
#include
int main() {
- int array[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
+ int array[8] = {1, 2, 3, 4, 5, 6, 7, 8};
- int min = array[0];
- int max = array[0];
+ int min = array[0];
+ int max = array[0];
- size_t length = sizeof(array) / sizeof(array[0]);
+ size_t length = sizeof(array) / sizeof(array[0]);
- for (int i = 1; i < length; ++i) {
- if (array[i] < min) {
- min = array[i];
- }
- if (array[i] > max) {
- max = array[i];
- }
+ for (int i = 1; i < length; ++i) {
+ if (array[i] < min) {
+ min = array[i];
}
+ if (array[i] > max) {
+ max = array[i];
+ }
+ }
- printf("min: %d\n", min);
- printf("max: %d\n", max);
- return 0;
+ printf("min: %d\n", min);
+ printf("max: %d\n", max);
+ return 0;
}
diff --git a/src/c/MinMaxRecursive.c b/src/c/MinMaxRecursive.c
index fcb64997..dcbdb235 100644
--- a/src/c/MinMaxRecursive.c
+++ b/src/c/MinMaxRecursive.c
@@ -1,25 +1,26 @@
/*
-* Exemplo de algoritmo recursivo.
-* Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando recursividade
-*/
+ * Exemplo de algoritmo recursivo.
+ * Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando
+ *recursividade
+ */
#include
#define TAM 10
-void MaxMin(int vetor[], int min, int max, int indice){
- if( vetor[indice] < min )
- min = vetor[indice];
- if( vetor[indice] > max )
- max = vetor[indice];
- if( indice < TAM-1 )
- MaxMin(vetor, min, max, indice+1);
- else
- printf("Min: %d \nMax: %d\n\n", min, max);
+void MaxMin(int vetor[], int min, int max, int indice) {
+ if (vetor[indice] < min)
+ min = vetor[indice];
+ if (vetor[indice] > max)
+ max = vetor[indice];
+ if (indice < TAM - 1)
+ MaxMin(vetor, min, max, indice + 1);
+ else
+ printf("Min: %d \nMax: %d\n\n", min, max);
}
-int main(){
- int vetor[TAM] = {9,2,1,8,6,3,4,5,0,7};
- MaxMin(vetor, vetor[0], vetor[0], 0);
- return 0;
+int main() {
+ int vetor[TAM] = {9, 2, 1, 8, 6, 3, 4, 5, 0, 7};
+ MaxMin(vetor, vetor[0], vetor[0], 0);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Palindrome.c b/src/c/Palindrome.c
index 6698f6dd..cdc59d0f 100644
--- a/src/c/Palindrome.c
+++ b/src/c/Palindrome.c
@@ -8,7 +8,7 @@ void calc_reverse(char *input, char *output) {
char *last_char = input + len_input - 1;
- for (int i=0; i < len_input; i++) {
+ for (int i = 0; i < len_input; i++) {
output[i] = *(last_char - i);
}
output[len_input] = '\0';
@@ -21,7 +21,7 @@ int main() {
printf("Digite uma palavra: ");
fgets(input, MAX_SIZE_WORD, stdin);
- //remove New Line from the end
+ // remove New Line from the end
input[strlen(input) - 1] = '\0';
calc_reverse(input, reverse);
diff --git a/src/c/Queue.c b/src/c/Queue.c
index 75efce52..35ad7a8c 100644
--- a/src/c/Queue.c
+++ b/src/c/Queue.c
@@ -1,6 +1,6 @@
/*
-* Exemplo de implementação de Fila em C
-*/
+ * Exemplo de implementação de Fila em C
+ */
#include
@@ -9,72 +9,74 @@
typedef int TIPOCHAVE;
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
-typedef struct{
- REGISTRO A[MAX+1];
- int nroRegistros;
-}FILA;
+typedef struct {
+ REGISTRO A[MAX + 1];
+ int nroRegistros;
+} FILA;
-void inicializa(FILA* F){
- int i = 0;
- for (i; i < MAX-2; i++){
- F->A[i].chave = i*2;
- }
- F->nroRegistros = i;
+void inicializa(FILA *F) {
+ int i = 0;
+ for (i; i < MAX - 2; i++) {
+ F->A[i].chave = i * 2;
+ }
+ F->nroRegistros = i;
}
-void mostraFila(FILA* F){
- int i = 0;
- printf("FILA:\n");
- for (i; i < F->nroRegistros; i++){
- printf("[ %d ] ", F->A[i].chave);
- }
- printf("\n\n");
+void mostraFila(FILA *F) {
+ int i = 0;
+ printf("FILA:\n");
+ for (i; i < F->nroRegistros; i++) {
+ printf("[ %d ] ", F->A[i].chave);
+ }
+ printf("\n\n");
}
-bool insereFila(TIPOCHAVE ch, FILA* F){
- if( F->nroRegistros >= MAX )
- return false;
- F->A[F->nroRegistros].chave = ch;
- F->nroRegistros++;
- return true;
+bool insereFila(TIPOCHAVE ch, FILA *F) {
+ if (F->nroRegistros >= MAX)
+ return false;
+ F->A[F->nroRegistros].chave = ch;
+ F->nroRegistros++;
+ return true;
}
-bool removeFila(FILA* F){
- if( F->nroRegistros <= 0 )
- return false;
- int i = 1;
- for (i; i < F->nroRegistros; i++){
- F->A[i-1].chave = F->A[i].chave;
- }
- F->nroRegistros--;
- return true;
+bool removeFila(FILA *F) {
+ if (F->nroRegistros <= 0)
+ return false;
+ int i = 1;
+ for (i; i < F->nroRegistros; i++) {
+ F->A[i - 1].chave = F->A[i].chave;
+ }
+ F->nroRegistros--;
+ return true;
}
-int buscaFila(TIPOCHAVE ch, FILA* F){
- F->A[F->nroRegistros].chave = ch; // Coloca a ch na ultima posição para fazer busca Sentinela
- int i = 0;
- while( F->A[i].chave != ch )
- i++;
- if( i >= F->nroRegistros )
- return ERRO;
- return i;
+int buscaFila(TIPOCHAVE ch, FILA *F) {
+ F->A[F->nroRegistros].chave =
+ ch; // Coloca a ch na ultima posição para fazer busca Sentinela
+ int i = 0;
+ while (F->A[i].chave != ch)
+ i++;
+ if (i >= F->nroRegistros)
+ return ERRO;
+ return i;
}
-int main(){
- FILA fi;
- inicializa(&fi);
- mostraFila(&fi);
+int main() {
+ FILA fi;
+ inicializa(&fi);
+ mostraFila(&fi);
- insereFila(15, &fi);
- mostraFila(&fi);
+ insereFila(15, &fi);
+ mostraFila(&fi);
- removeFila(&fi);
- mostraFila(&fi);
+ removeFila(&fi);
+ mostraFila(&fi);
- printf("A chave buscada se encontra na posicao %d da fila\n\n", buscaFila(8, &fi) );
- return 0;
+ printf("A chave buscada se encontra na posicao %d da fila\n\n",
+ buscaFila(8, &fi));
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/QuickSort.c b/src/c/QuickSort.c
index 98c49507..87fae0c9 100644
--- a/src/c/QuickSort.c
+++ b/src/c/QuickSort.c
@@ -1,87 +1,87 @@
-#include
#include
+#include
void print_array(int array[], int size) {
- printf("[ ");
- for (int index = 0; index < size; ++index) {
- printf("%d", array[index]);
- if (index < size - 1) {
- printf(", ");
- }
+ printf("[ ");
+ for (int index = 0; index < size; ++index) {
+ printf("%d", array[index]);
+ if (index < size - 1) {
+ printf(", ");
}
- printf(" ]\n");
+ }
+ printf(" ]\n");
}
void swap(int array[], int src_index, int dest_index) {
- int temp = array[src_index];
- array[src_index] = array[dest_index];
- array[dest_index] = temp;
+ int temp = array[src_index];
+ array[src_index] = array[dest_index];
+ array[dest_index] = temp;
}
int lomuto_partition(int array[], int low, int high) {
- int pivot = array[high];
- int index = low;
+ int pivot = array[high];
+ int index = low;
- for (int j = low; j < high; ++j) {
- if (array[j] < pivot) {
- swap(array, index, j);
- ++index;
- }
+ for (int j = low; j < high; ++j) {
+ if (array[j] < pivot) {
+ swap(array, index, j);
+ ++index;
}
- swap(array, index, high);
- return index;
+ }
+ swap(array, index, high);
+ return index;
}
void quicksort_lomuto(int array[], int low, int high) {
- if (low < high) {
- int pivot = lomuto_partition(array, low, high);
- quicksort_lomuto(array, low, pivot - 1);
- quicksort_lomuto(array, pivot + 1, high);
- }
+ if (low < high) {
+ int pivot = lomuto_partition(array, low, high);
+ quicksort_lomuto(array, low, pivot - 1);
+ quicksort_lomuto(array, pivot + 1, high);
+ }
}
int hoare_partition(int array[], int low, int high) {
- int pivot = array[low];
- int i = low - 1;
- int j = high + 1;
+ int pivot = array[low];
+ int i = low - 1;
+ int j = high + 1;
- while (true) {
- do {
- ++i;
- } while (array[i] < pivot);
+ while (true) {
+ do {
+ ++i;
+ } while (array[i] < pivot);
- do {
- --j;
- } while (array[j] > pivot);
+ do {
+ --j;
+ } while (array[j] > pivot);
- if (i >= j) {
- return j;
- }
- swap(array, i, j);
+ if (i >= j) {
+ return j;
}
+ swap(array, i, j);
+ }
}
void quicksort_hoare(int array[], int low, int high) {
- if (low < high) {
- int pivot = hoare_partition(array, low, high);
- quicksort_hoare(array, low, pivot);
- quicksort_hoare(array, pivot + 1, high);
- }
+ if (low < high) {
+ int pivot = hoare_partition(array, low, high);
+ quicksort_hoare(array, low, pivot);
+ quicksort_hoare(array, pivot + 1, high);
+ }
}
int main() {
- int example_lomuto[] = {5, 3, 1, 4, 2};
- int example_hoare[] = {5, 3, 1, 4, 2};
- int size = 5;
+ int example_lomuto[] = {5, 3, 1, 4, 2};
+ int example_hoare[] = {5, 3, 1, 4, 2};
+ int size = 5;
- printf("lomuto quicksort partition:\n");
- print_array(example_lomuto, size);
- quicksort_lomuto(example_lomuto, 0, size - 1);
- print_array(example_lomuto, size);
+ printf("lomuto quicksort partition:\n");
+ print_array(example_lomuto, size);
+ quicksort_lomuto(example_lomuto, 0, size - 1);
+ print_array(example_lomuto, size);
- printf("hoare quicksort partition:\n");
- print_array(example_hoare, size);
- quicksort_hoare(example_hoare, 0, size - 1);
- print_array(example_hoare, size);
- return 0;
+ printf("hoare quicksort partition:\n");
+ print_array(example_hoare, size);
+ quicksort_hoare(example_hoare, 0, size - 1);
+ print_array(example_hoare, size);
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/RadixSort.c b/src/c/RadixSort.c
index 2c63dc6b..b4382076 100644
--- a/src/c/RadixSort.c
+++ b/src/c/RadixSort.c
@@ -1,65 +1,54 @@
#include
-void print_array(int array[], int size)
-{
- printf("[ ");
- for (int i = 0; i < size; i++)
- {
- printf("%d ", array[i]);
- }
- printf("]\n");
+void print_array(int array[], int size) {
+ printf("[ ");
+ for (int i = 0; i < size; i++) {
+ printf("%d ", array[i]);
+ }
+ printf("]\n");
}
-int get_max(int array[], int size)
-{
- int max = array[0];
- for (int i = 1; i < size; i++)
- {
- if (array[i] > max)
- max = array[i];
- }
- return max;
+int get_max(int array[], int size) {
+ int max = array[0];
+ for (int i = 1; i < size; i++) {
+ if (array[i] > max)
+ max = array[i];
+ }
+ return max;
}
-void radix_sort(int array[], int size)
-{
- int i;
- int semi_sorted[size];
- int significant_digit = 1;
- int largest_number = get_max(array, size);
+void radix_sort(int array[], int size) {
+ int i;
+ int semi_sorted[size];
+ int significant_digit = 1;
+ int largest_number = get_max(array, size);
- while (largest_number / significant_digit > 0)
- {
- int bucket[10] = {0};
- for (i = 0; i < size; i++)
- {
- bucket[(array[i] / significant_digit) % 10]++;
- }
- for (i = 1; i < 10; i++)
- {
- bucket[i] += bucket[i - 1];
- }
- for (i = size - 1; i >= 0; i--)
- {
- semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i];
- }
- for (i = 0; i < size; i++)
- {
- array[i] = semi_sorted[i];
- }
- significant_digit *= 10;
- }
+ while (largest_number / significant_digit > 0) {
+ int bucket[10] = {0};
+ for (i = 0; i < size; i++) {
+ bucket[(array[i] / significant_digit) % 10]++;
+ }
+ for (i = 1; i < 10; i++) {
+ bucket[i] += bucket[i - 1];
+ }
+ for (i = size - 1; i >= 0; i--) {
+ semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i];
+ }
+ for (i = 0; i < size; i++) {
+ array[i] = semi_sorted[i];
+ }
+ significant_digit *= 10;
+ }
}
-int main()
-{
- int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11};
- printf("Unsorted Array\n");
- print_array(array, 10);
+int main() {
+ int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11};
+ printf("Unsorted Array\n");
+ print_array(array, 10);
- radix_sort(array, 10);
+ radix_sort(array, 10);
- printf("Sorted Array\n");
- print_array(array, 10);
- return 0;
+ printf("Sorted Array\n");
+ print_array(array, 10);
+ return 0;
}
diff --git a/src/c/SelectionSort.c b/src/c/SelectionSort.c
index 8fc38542..4cbee813 100644
--- a/src/c/SelectionSort.c
+++ b/src/c/SelectionSort.c
@@ -1,41 +1,35 @@
#include
-void swap(int array[], int i, int j)
-{
- int temp = array[i];
- array[i] = array[j];
- array[j] = temp;
+void swap(int array[], int i, int j) {
+ int temp = array[i];
+ array[i] = array[j];
+ array[j] = temp;
}
-void selection_sort(int array[], int n)
-{
- int min, i, j;
- for (i = 0; i < n; i++)
- {
- min = i;
- for (j = i + 1; j < n; j++)
- {
- if (array[min] > array[j])
- {
- min = j;
- }
- }
- if (min != i)
- swap(array, min, i);
+void selection_sort(int array[], int n) {
+ int min, i, j;
+ for (i = 0; i < n; i++) {
+ min = i;
+ for (j = i + 1; j < n; j++) {
+ if (array[min] > array[j]) {
+ min = j;
+ }
}
+ if (min != i)
+ swap(array, min, i);
+ }
}
-int main()
-{
- int array_size = 10;
- int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4};
+int main() {
+ int array_size = 10;
+ int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4};
- selection_sort(array, array_size);
+ selection_sort(array, array_size);
- printf("Sorted Array:\n");
- int i;
- for (i = 0; i < array_size; i++)
- printf("%d ", array[i]);
+ printf("Sorted Array:\n");
+ int i;
+ for (i = 0; i < array_size; i++)
+ printf("%d ", array[i]);
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/SinglyLinkedList.c b/src/c/SinglyLinkedList.c
index 9e5cad76..5411563c 100644
--- a/src/c/SinglyLinkedList.c
+++ b/src/c/SinglyLinkedList.c
@@ -1,272 +1,266 @@
-#include
#include
+#include
typedef struct tno {
- int dado;
- struct tno * anterior;
- struct tno * proximo;
+ int dado;
+ struct tno *anterior;
+ struct tno *proximo;
} tipoNo;
-typedef tipoNo * pnoh;
+typedef tipoNo *pnoh;
typedef struct {
- int tamanho;
- pnoh primeiro;
- pnoh ultimo;
+ int tamanho;
+ pnoh primeiro;
+ pnoh ultimo;
} tcabec;
-typedef tcabec * TLista;
+typedef tcabec *TLista;
TLista criaLista() {
- TLista c = (tcabec*) malloc(sizeof(tcabec));
+ TLista c = (tcabec *)malloc(sizeof(tcabec));
- c->tamanho = 0;
- c->primeiro = NULL;
- c->ultimo = NULL;
+ c->tamanho = 0;
+ c->primeiro = NULL;
+ c->ultimo = NULL;
- return c;
+ return c;
}
TLista appendLista(TLista lst, int dado) {
- pnoh novono = (tipoNo*) malloc(sizeof(tipoNo));
+ pnoh novono = (tipoNo *)malloc(sizeof(tipoNo));
- novono->dado = dado;
- novono->anterior = lst->ultimo;
- novono->proximo = NULL;
+ novono->dado = dado;
+ novono->anterior = lst->ultimo;
+ novono->proximo = NULL;
- if (lst->tamanho == 0) {
- lst->primeiro = novono;
- } else {
- lst->ultimo->proximo = novono;
- }
+ if (lst->tamanho == 0) {
+ lst->primeiro = novono;
+ } else {
+ lst->ultimo->proximo = novono;
+ }
- lst->ultimo = novono;
- lst->tamanho++;
+ lst->ultimo = novono;
+ lst->tamanho++;
- return lst;
+ return lst;
}
-int lenLista(TLista lst) {
- return lst->tamanho;
-}
+int lenLista(TLista lst) { return lst->tamanho; }
-int primLista(TLista lst) {
- return lst->primeiro->dado;
-}
+int primLista(TLista lst) { return lst->primeiro->dado; }
-int ultLista(TLista lst) {
- return lst->ultimo->dado;
-}
+int ultLista(TLista lst) { return lst->ultimo->dado; }
-TLista insertLista(TLista lst, int i, int dado)
-{
- int tam = lenLista(lst);
+TLista insertLista(TLista lst, int i, int dado) {
+ int tam = lenLista(lst);
- if ((i < 0) || (i > tam)) {
- return NULL;
- }
+ if ((i < 0) || (i > tam)) {
+ return NULL;
+ }
- if ((lenLista(lst) == 0) || (i == tam)) {
- appendLista(lst, dado);
+ if ((lenLista(lst) == 0) || (i == tam)) {
+ appendLista(lst, dado);
+ } else {
+ pnoh novono = (tipoNo *)malloc(sizeof(tipoNo));
+ novono->dado = dado;
+
+ if (i == 0) {
+ novono->proximo = lst->primeiro;
+ lst->primeiro = novono;
} else {
- pnoh novono = (tipoNo*) malloc(sizeof(tipoNo));
- novono->dado = dado;
-
- if (i == 0) {
- novono->proximo = lst->primeiro;
- lst->primeiro = novono;
- } else {
- pnoh aux = lst->primeiro;
- int pos = 0;
-
- while (pos != (i - 1))
- {
- aux = aux->proximo;
- pos++;
- }
- novono->proximo = aux->proximo;
- aux->proximo = novono;
- }
+ pnoh aux = lst->primeiro;
+ int pos = 0;
- lst->tamanho++;
+ while (pos != (i - 1)) {
+ aux = aux->proximo;
+ pos++;
+ }
+ novono->proximo = aux->proximo;
+ aux->proximo = novono;
}
- return lst;
+ lst->tamanho++;
+ }
+
+ return lst;
}
pnoh infoLista(TLista lst, int i) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if ((tam == 0) || (i < 0) || (i > tam)) {
- return NULL;
- }
+ if ((tam == 0) || (i < 0) || (i > tam)) {
+ return NULL;
+ }
- if (i == 0) {
- return lst->primeiro;
- }
+ if (i == 0) {
+ return lst->primeiro;
+ }
- if (i == tam - 1) {
- return lst->ultimo;
- }
+ if (i == tam - 1) {
+ return lst->ultimo;
+ }
- pnoh aux = lst->primeiro;
- int pos = 0;
+ pnoh aux = lst->primeiro;
+ int pos = 0;
- while (pos != i) {
- aux = aux->proximo;
- pos++;
- }
+ while (pos != i) {
+ aux = aux->proximo;
+ pos++;
+ }
- return aux;
+ return aux;
}
void removeLista(TLista lst, int i) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if ((i < 0) || (i > tam) || (tam == 0)) {
- printf("Erro: indice inexistente dentro da Lista.");
- return;
- }
+ if ((i < 0) || (i > tam) || (tam == 0)) {
+ printf("Erro: indice inexistente dentro da Lista.");
+ return;
+ }
- if (tam == 1) {
- pnoh aux = lst->primeiro;
- lst->primeiro = NULL;
- lst->ultimo = NULL;
- lst->tamanho--;
+ if (tam == 1) {
+ pnoh aux = lst->primeiro;
+ lst->primeiro = NULL;
+ lst->ultimo = NULL;
+ lst->tamanho--;
- free(aux);
- } else {
- if (i == 0) {
- pnoh aux = lst->primeiro;
- lst->primeiro = aux->proximo;
- lst->tamanho--;
+ free(aux);
+ } else {
+ if (i == 0) {
+ pnoh aux = lst->primeiro;
+ lst->primeiro = aux->proximo;
+ lst->tamanho--;
- free(aux);
- } else {
- if (i == tam - 1) {
- pnoh aux = lst->ultimo;
+ free(aux);
+ } else {
+ if (i == tam - 1) {
+ pnoh aux = lst->ultimo;
- pnoh penultimo = lst->primeiro;
- int pos = 0;
+ pnoh penultimo = lst->primeiro;
+ int pos = 0;
- while (pos != i - 1) {
- penultimo = penultimo->proximo;
- pos++;
- }
+ while (pos != i - 1) {
+ penultimo = penultimo->proximo;
+ pos++;
+ }
- penultimo->proximo = NULL;
- lst->ultimo = penultimo;
+ penultimo->proximo = NULL;
+ lst->ultimo = penultimo;
- lst->tamanho--;
+ lst->tamanho--;
- free(aux);
- } else {
- pnoh anterior = lst->primeiro;
- int pos = 0;
+ free(aux);
+ } else {
+ pnoh anterior = lst->primeiro;
+ int pos = 0;
- while (pos != i - 1) {
- anterior = anterior->proximo;
- pos++;
- }
+ while (pos != i - 1) {
+ anterior = anterior->proximo;
+ pos++;
+ }
- pnoh aux = anterior->proximo;
- anterior->proximo = aux->proximo;
- lst->tamanho--;
+ pnoh aux = anterior->proximo;
+ anterior->proximo = aux->proximo;
+ lst->tamanho--;
- free(aux);
- }
- }
+ free(aux);
+ }
}
+ }
}
int indexLista(TLista lst, int dado) {
- int tam = lenLista(lst);
- int i, dadolst;
- pnoh no_dadolst;
+ int tam = lenLista(lst);
+ int i, dadolst;
+ pnoh no_dadolst;
- if (tam == 0) {
- return -1;
- }
+ if (tam == 0) {
+ return -1;
+ }
- i = 0;
+ i = 0;
+ no_dadolst = infoLista(lst, i);
+ dadolst = no_dadolst->dado;
+ while ((i < tam) && (dado != dadolst)) {
+ i++;
no_dadolst = infoLista(lst, i);
dadolst = no_dadolst->dado;
- while ((i < tam) && (dado != dadolst)) {
- i++;
- no_dadolst = infoLista(lst, i);
- dadolst = no_dadolst->dado;
- }
+ }
- if (i < tam) {
- return i;
- }
+ if (i < tam) {
+ return i;
+ }
- return -1;
+ return -1;
}
TLista clearLista(TLista lst) {
- int tam = lenLista(lst);
+ int tam = lenLista(lst);
- if (tam == 0) {
- return lst;
- }
+ if (tam == 0) {
+ return lst;
+ }
- while (lenLista(lst) > 0) {
- removeLista(lst, 0);
- }
+ while (lenLista(lst) > 0) {
+ removeLista(lst, 0);
+ }
- return lst;
+ return lst;
}
TLista clonaLista(TLista lst) {
- TLista clone = criaLista();
- int tam = lenLista(lst);
+ TLista clone = criaLista();
+ int tam = lenLista(lst);
- if (tam == 0) {
- return clone;
- }
+ if (tam == 0) {
+ return clone;
+ }
- for (int i = 0; i < tam; i++) {
- pnoh no = infoLista(lst, i);
- if (no != NULL) {
- appendLista(clone, no->dado);
- }
+ for (int i = 0; i < tam; i++) {
+ pnoh no = infoLista(lst, i);
+ if (no != NULL) {
+ appendLista(clone, no->dado);
}
+ }
- return clone;
+ return clone;
}
int main() {
- TLista lista = criaLista();
- appendLista(lista, 3);
- appendLista(lista, 5);
- appendLista(lista, 7);
-
- printf("Lista criada e adicionado 3 numeros\n");
- int tamanho = lenLista(lista);
- int primeiro = primLista(lista);
- int ultimo = ultLista(lista);
- pnoh valor = infoLista(lista, 1);
- int valor_dado = valor->dado;
- printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: %d\nSegundo valor: %d\n", tamanho, primeiro, ultimo, valor_dado);
-
- insertLista(lista, 2, 6);
- valor = infoLista(lista, 2);
- valor_dado = valor->dado;
- printf("Adicionando 6 na posição 2: %d\n", valor_dado);
-
- removeLista(lista, 1);
- tamanho = lenLista(lista);
- printf("Novo tamanho após adicionar e remover: %d\n", tamanho);
-
- int index = indexLista(lista, 3);
- printf("Index do elemento com valor 3 na lista: %d\n", index);
-
- TLista cloneLista = clonaLista(lista);
- printf("Lista Duplicada\n");
-
- clearLista(lista);
- printf("Lista Apagada");
-
- return 0;
+ TLista lista = criaLista();
+ appendLista(lista, 3);
+ appendLista(lista, 5);
+ appendLista(lista, 7);
+
+ printf("Lista criada e adicionado 3 numeros\n");
+ int tamanho = lenLista(lista);
+ int primeiro = primLista(lista);
+ int ultimo = ultLista(lista);
+ pnoh valor = infoLista(lista, 1);
+ int valor_dado = valor->dado;
+ printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: "
+ "%d\nSegundo valor: %d\n",
+ tamanho, primeiro, ultimo, valor_dado);
+
+ insertLista(lista, 2, 6);
+ valor = infoLista(lista, 2);
+ valor_dado = valor->dado;
+ printf("Adicionando 6 na posição 2: %d\n", valor_dado);
+
+ removeLista(lista, 1);
+ tamanho = lenLista(lista);
+ printf("Novo tamanho após adicionar e remover: %d\n", tamanho);
+
+ int index = indexLista(lista, 3);
+ printf("Index do elemento com valor 3 na lista: %d\n", index);
+
+ TLista cloneLista = clonaLista(lista);
+ printf("Lista Duplicada\n");
+
+ clearLista(lista);
+ printf("Lista Apagada");
+
+ return 0;
}
diff --git a/src/c/SortedLinkedList.c b/src/c/SortedLinkedList.c
index 29c37489..8fc5b4ff 100644
--- a/src/c/SortedLinkedList.c
+++ b/src/c/SortedLinkedList.c
@@ -1,6 +1,7 @@
/*
-* Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando sentinela
-*/
+ * Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando
+ *sentinela
+ */
#include
@@ -9,96 +10,105 @@
typedef int TIPOCHAVE; // Define um nome TIPOCHAVE para um tipo inteiro
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
-
-typedef struct{
- REGISTRO A[MAX+1]; // O +1 é a posição que será utilizada para a 'sentinela'
- int nroElementos;
-}LISTA;
-
-void inicializar(LISTA* L){
- L->nroElementos = 0; // Acessa a lista pelo endereço de memória
- int i = 0;
- for (i; i < MAX-2; ++i){ // Preenche a lista até -2 para deixar espaço para inserir mais depois
- L->A[i].chave = i*2;
- }
- L->nroElementos = MAX-2;
- // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o ponteiro
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
+
+typedef struct {
+ REGISTRO A[MAX + 1]; // O +1 é a posição que será utilizada para a 'sentinela'
+ int nroElementos;
+} LISTA;
+
+void inicializar(LISTA *L) {
+ L->nroElementos = 0; // Acessa a lista pelo endereço de memória
+ int i = 0;
+ for (i; i < MAX - 2; ++i) { // Preenche a lista até -2 para deixar espaço para
+ // inserir mais depois
+ L->A[i].chave = i * 2;
+ }
+ L->nroElementos = MAX - 2;
+ // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o
+ // ponteiro
}
-/* A função do sentinela é adicionar a chave ao final da lista, ou seja,
+/* A função do sentinela é adicionar a chave ao final da lista, ou seja,
* sempre irá encontrar a chave, mesmo que seja na útlima posição da lista.
* Caso seja o último elemento, significa que não encontrou.
* Deste modo elimina o 'if' dentro do laço, poupando várias comparações
- */
-int buscaSentinela(TIPOCHAVE ch, LISTA* L){ // Poderia usar aqui busca binária, o que seria mais apropriado.
- int i = 0;
- L->A[L->nroElementos].chave = ch; // Atribui a 'chave'/valor buscado a ultima posição do array A
- while(L->A[i].chave != ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado se encontra no array (senão será o sentinela)
- i++;
- if(i == L->nroElementos) // Se o valor chegou até o final, significa que não encontrou o valor, retorna ERRO (-1)
- return ERRO;
- return i; // Caso contrário retorna a posição do valor/'chave' no array
+ */
+int buscaSentinela(
+ TIPOCHAVE ch,
+ LISTA *L) { // Poderia usar aqui busca binária, o que seria mais apropriado.
+ int i = 0;
+ L->A[L->nroElementos].chave =
+ ch; // Atribui a 'chave'/valor buscado a ultima posição do array A
+ while (L->A[i].chave !=
+ ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado
+ // se encontra no array (senão será o sentinela)
+ i++;
+ if (i == L->nroElementos) // Se o valor chegou até o final, significa que não
+ // encontrou o valor, retorna ERRO (-1)
+ return ERRO;
+ return i; // Caso contrário retorna a posição do valor/'chave' no array
}
-bool inserirOrdenado(REGISTRO reg, LISTA* L){
- int i = 0;
- if(L->nroElementos >= MAX)
- return false;
- L->A[L->nroElementos].chave = reg.chave;
- while(L->A[i].chave < reg.chave)
- i++;
- int p = L->nroElementos-1;
- while(p >= i){
- L->A[p+1] = L->A[p];
- p--;
- }
- L->A[i] = reg;
- L->nroElementos++;
- return true;
+bool inserirOrdenado(REGISTRO reg, LISTA *L) {
+ int i = 0;
+ if (L->nroElementos >= MAX)
+ return false;
+ L->A[L->nroElementos].chave = reg.chave;
+ while (L->A[i].chave < reg.chave)
+ i++;
+ int p = L->nroElementos - 1;
+ while (p >= i) {
+ L->A[p + 1] = L->A[p];
+ p--;
+ }
+ L->A[i] = reg;
+ L->nroElementos++;
+ return true;
}
-bool deletaValor(REGISTRO reg, LISTA* L){
- int posicao = buscaSentinela(reg.chave, L);
- if( posicao >= 0 ){
- for( posicao; posicao < L->nroElementos; posicao++ ){
- L->A[posicao] = L->A[posicao+1];
- }
- L->nroElementos--;
- return true;
- }else{
- return false;
- }
+bool deletaValor(REGISTRO reg, LISTA *L) {
+ int posicao = buscaSentinela(reg.chave, L);
+ if (posicao >= 0) {
+ for (posicao; posicao < L->nroElementos; posicao++) {
+ L->A[posicao] = L->A[posicao + 1];
+ }
+ L->nroElementos--;
+ return true;
+ } else {
+ return false;
+ }
}
-void mostraLista(LISTA* L){
- int i = 0;
- for (i; i < L->nroElementos; ++i){ // Percorre e mostra todos os valores do array
- printf("%d, ", L->A[i].chave);
- }
- printf("\n\n");
+void mostraLista(LISTA *L) {
+ int i = 0;
+ for (i; i < L->nroElementos;
+ ++i) { // Percorre e mostra todos os valores do array
+ printf("%d, ", L->A[i].chave);
+ }
+ printf("\n\n");
}
-int main(){
-
- LISTA LISTA;
- inicializar(&LISTA);
-
- printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA) );
- mostraLista(&LISTA);
-
- REGISTRO reg;
- reg.chave = 7;
- printf("Insere o valor: %d\n", reg.chave);
- inserirOrdenado(reg, &LISTA);
- mostraLista(&LISTA);
-
- reg.chave = 12;
- printf("Deleta o valor: %d\n", reg.chave);
- deletaValor(reg, &LISTA);
- mostraLista(&LISTA);
-
- return 0;
+int main() {
+
+ LISTA LISTA;
+ inicializar(&LISTA);
+
+ printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA));
+ mostraLista(&LISTA);
+
+ REGISTRO reg;
+ reg.chave = 7;
+ printf("Insere o valor: %d\n", reg.chave);
+ inserirOrdenado(reg, &LISTA);
+ mostraLista(&LISTA);
+
+ reg.chave = 12;
+ printf("Deleta o valor: %d\n", reg.chave);
+ deletaValor(reg, &LISTA);
+ mostraLista(&LISTA);
+
+ return 0;
}
\ No newline at end of file
diff --git a/src/c/Stack.c b/src/c/Stack.c
index 4f91e9f4..e3b290dd 100644
--- a/src/c/Stack.c
+++ b/src/c/Stack.c
@@ -1,6 +1,6 @@
-/*
-* Exemplo de implementação de Pilha em C - Utiliza Sentinela
-*/
+/*
+ * Exemplo de implementação de Pilha em C - Utiliza Sentinela
+ */
#include
@@ -9,76 +9,76 @@
typedef int TIPOCHAVE;
-typedef struct{
- TIPOCHAVE chave;
-}REGISTRO;
+typedef struct {
+ TIPOCHAVE chave;
+} REGISTRO;
-typedef struct{
- REGISTRO A[MAX+1];
- int nroRegistros;
-}PILHA;
+typedef struct {
+ REGISTRO A[MAX + 1];
+ int nroRegistros;
+} PILHA;
-int inicializa(PILHA* p){
- p->nroRegistros = 0;
- int i = 0;
- for (i; i < MAX-2; i++){ // Preenche a Pilha *para testes
- p->A[i].chave = i*2; // É um array de REGISTRO (semelhante a class), poderia ter mais campos, por isso se define A[i].chave, irá inserir o valor no campo chave
- }
- p->nroRegistros = i;
+int inicializa(PILHA *p) {
+ p->nroRegistros = 0;
+ int i = 0;
+ for (i; i < MAX - 2; i++) { // Preenche a Pilha *para testes
+ p->A[i].chave = i * 2; // É um array de REGISTRO (semelhante a class),
+ // poderia ter mais campos, por isso se define
+ // A[i].chave, irá inserir o valor no campo chave
+ }
+ p->nroRegistros = i;
}
-bool inserePilha(int valor, PILHA* p){
- if( p->nroRegistros < MAX ){
- p->A[p->nroRegistros].chave = valor;
- p->nroRegistros++;
- return true;
- }else{
- return false;
- }
+bool inserePilha(int valor, PILHA *p) {
+ if (p->nroRegistros < MAX) {
+ p->A[p->nroRegistros].chave = valor;
+ p->nroRegistros++;
+ return true;
+ } else {
+ return false;
+ }
}
-bool removePilha(PILHA* p){
- p->nroRegistros--;
-}
+bool removePilha(PILHA *p) { p->nroRegistros--; }
-void mostraPilha(PILHA* p){
- int i = p->nroRegistros-1;
- printf("\nPilha:\n");
- for (i; i >= 0; i--){
- printf("%d = [ %d ]\n", i, p->A[i].chave);
- }
- printf("------------------\n");
+void mostraPilha(PILHA *p) {
+ int i = p->nroRegistros - 1;
+ printf("\nPilha:\n");
+ for (i; i >= 0; i--) {
+ printf("%d = [ %d ]\n", i, p->A[i].chave);
+ }
+ printf("------------------\n");
}
-int buscaPilha(int chave, PILHA* p){
- p->A[p->nroRegistros].chave = chave;
- int aux = 0;
- while( p->A[aux].chave != chave )
- aux++;
- if( aux == p->nroRegistros )
- return ERRO;
- return aux;
+int buscaPilha(int chave, PILHA *p) {
+ p->A[p->nroRegistros].chave = chave;
+ int aux = 0;
+ while (p->A[aux].chave != chave)
+ aux++;
+ if (aux == p->nroRegistros)
+ return ERRO;
+ return aux;
}
-int main(){
- PILHA vPilha;
- inicializa(&vPilha);
+int main() {
+ PILHA vPilha;
+ inicializa(&vPilha);
+
+ mostraPilha(&vPilha);
+ if (inserePilha(10, &vPilha)) {
+ printf("Inserido com sucesso");
+ } else {
+ printf("Pilha cheia");
+ }
+
+ mostraPilha(&vPilha);
+ removePilha(&vPilha);
+ mostraPilha(&vPilha);
- mostraPilha(&vPilha);
- if( inserePilha(10, &vPilha) ){
- printf("Inserido com sucesso");
- }else{
- printf("Pilha cheia");
- }
-
- mostraPilha(&vPilha);
- removePilha(&vPilha);
- mostraPilha(&vPilha);
-
- int aux = buscaPilha(8, &vPilha);
- if( aux != -1 ){
- printf("Valor 8 encontrado na posicao %d da pilha\n", aux);
- }else{
- printf("Valor nao encontrado\n");
- }
+ int aux = buscaPilha(8, &vPilha);
+ if (aux != -1) {
+ printf("Valor 8 encontrado na posicao %d da pilha\n", aux);
+ } else {
+ printf("Valor nao encontrado\n");
+ }
}
\ No newline at end of file
diff --git a/src/c/Timsort.c b/src/c/Timsort.c
index 51ab4c44..fba68ebc 100644
--- a/src/c/Timsort.c
+++ b/src/c/Timsort.c
@@ -2,127 +2,123 @@
const int THRESHOLD = 32;
-int is_odd(int n) {
- return n & 1;
-}
+int is_odd(int n) { return n & 1; }
int get_fmin(int a, int b) {
- if (a < b) {
- return a;
- }
- return b;
+ if (a < b) {
+ return a;
+ }
+ return b;
}
-int get_floor(int n) {
- return n / 2;
-}
+int get_floor(int n) { return n / 2; }
void print_array(int array[], int size) {
- printf("[");
- for (int i = 0; i < size; i++) {
- printf("%d", array[i]);
- if (i != size - 1) {
- printf(", ");
- }
+ printf("[");
+ for (int i = 0; i < size; i++) {
+ printf("%d", array[i]);
+ if (i != size - 1) {
+ printf(", ");
}
- printf("]\n");
+ }
+ printf("]\n");
}
int get_run_length(int size_of_array) {
- int run_length = size_of_array;
- int remainder = 0;
-
- while (run_length >= THRESHOLD) {
- if (is_odd(run_length)) {
- remainder = 1;
- }
- run_length = get_floor(run_length / 2);
+ int run_length = size_of_array;
+ int remainder = 0;
+
+ while (run_length >= THRESHOLD) {
+ if (is_odd(run_length)) {
+ remainder = 1;
}
- return run_length + remainder;
+ run_length = get_floor(run_length / 2);
+ }
+ return run_length + remainder;
}
void insertion_sort(int array[], int left_index, int right_index) {
- for (int i = left_index + 1; i <= right_index; i++) {
- int temp = array[i];
- int j = i - 1;
- while (j >= left_index && array[j] > temp) {
- array[j + 1] = array[j];
- j--;
- }
- array[j + 1] = temp;
+ for (int i = left_index + 1; i <= right_index; i++) {
+ int temp = array[i];
+ int j = i - 1;
+ while (j >= left_index && array[j] > temp) {
+ array[j + 1] = array[j];
+ j--;
}
+ array[j + 1] = temp;
+ }
}
-void merge_runs(int array[], int left_index, int middle_index, int right_index) {
- int left_size = middle_index - left_index + 1;
- int right_size = right_index - middle_index;
- int left[left_size];
- int right[right_size];
-
- for (int i = 0; i < left_size; i++) {
- left[i] = array[left_index + i];
- }
- for (int j = 0; j < right_size; j++) {
- right[j] = array[middle_index + 1 + j];
- }
-
- int i = 0;
- int j = 0;
- int k = left_index;
-
- while (i < left_size && j < right_size) {
- if (left[i] <= right[j]) {
- array[k] = left[i];
- i++;
- } else {
- array[k] = right[j];
- j++;
- }
- k++;
- }
-
- while (i < left_size) {
- array[k] = left[i];
- i++;
- k++;
- }
-
- while (j < right_size) {
- array[k] = right[j];
- j++;
- k++;
+void merge_runs(int array[], int left_index, int middle_index,
+ int right_index) {
+ int left_size = middle_index - left_index + 1;
+ int right_size = right_index - middle_index;
+ int left[left_size];
+ int right[right_size];
+
+ for (int i = 0; i < left_size; i++) {
+ left[i] = array[left_index + i];
+ }
+ for (int j = 0; j < right_size; j++) {
+ right[j] = array[middle_index + 1 + j];
+ }
+
+ int i = 0;
+ int j = 0;
+ int k = left_index;
+
+ while (i < left_size && j < right_size) {
+ if (left[i] <= right[j]) {
+ array[k] = left[i];
+ i++;
+ } else {
+ array[k] = right[j];
+ j++;
}
+ k++;
+ }
+
+ while (i < left_size) {
+ array[k] = left[i];
+ i++;
+ k++;
+ }
+
+ while (j < right_size) {
+ array[k] = right[j];
+ j++;
+ k++;
+ }
}
void timsort(int array[], int size) {
- int run_length = get_run_length(size);
-
- for (int i = 0; i < size; i += run_length) {
- insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1)));
- }
-
- for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) {
- for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) {
- int middle_index = left_index + size_of_run - 1;
- int right_index = get_fmin((left_index + 2 * size_of_run - 1), (size - 1));
- merge_runs(array, left_index, middle_index, right_index);
- }
+ int run_length = get_run_length(size);
+
+ for (int i = 0; i < size; i += run_length) {
+ insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1)));
+ }
+
+ for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) {
+ for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) {
+ int middle_index = left_index + size_of_run - 1;
+ int right_index =
+ get_fmin((left_index + 2 * size_of_run - 1), (size - 1));
+ merge_runs(array, left_index, middle_index, right_index);
}
+ }
}
int main() {
- int array[] = { 5, 2, -2147483648, 1, 4, 5323, -1, 0, 10, 9, 8, 7, 6, 2147483647, 4, 3, 2 };
- int size = sizeof(array) / sizeof(array[0]);
+ int array[] = {5, 2, -2147483648, 1, 4, 5323, -1, 0, 10,
+ 9, 8, 7, 6, 2147483647, 4, 3, 2};
+ int size = sizeof(array) / sizeof(array[0]);
- printf("Original array:\t");
- print_array(array, size);
+ printf("Original array:\t");
+ print_array(array, size);
- timsort(array, size);
+ timsort(array, size);
- printf("Sorted array:\t");
- print_array(array, size);
- return 0;
+ printf("Sorted array:\t");
+ print_array(array, size);
+ return 0;
}
-
-
-
diff --git a/src/c/TowerOfHanoi.c b/src/c/TowerOfHanoi.c
index 0e4affca..91ec0226 100644
--- a/src/c/TowerOfHanoi.c
+++ b/src/c/TowerOfHanoi.c
@@ -4,21 +4,18 @@ Torre de Hanoi em C
#include
-void hanoi(int pino0, int pino2, int pino1, int discos)
-{
- if (discos == 1)
- printf("Move de %i para %i\n", pino0, pino2);
+void hanoi(int pino0, int pino2, int pino1, int discos) {
+ if (discos == 1)
+ printf("Move de %i para %i\n", pino0, pino2);
- else
- {
- hanoi(pino0, pino1, pino2, discos - 1);
- hanoi(pino0, pino2, pino1, 1);
- hanoi(pino1, pino2, pino0, discos - 1);
- }
+ else {
+ hanoi(pino0, pino1, pino2, discos - 1);
+ hanoi(pino0, pino2, pino1, 1);
+ hanoi(pino1, pino2, pino0, discos - 1);
+ }
}
-int main()
-{
- hanoi(0, 2, 1, 3);
- return 0;
+int main() {
+ hanoi(0, 2, 1, 3);
+ return 0;
}
diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c
index 46d435e9..d165ebe4 100644
--- a/src/c/TravellingSalesman.c
+++ b/src/c/TravellingSalesman.c
@@ -1,32 +1,33 @@
/*
-* Traveling Salesman Problem in C
-* Using a distance matrix to represent an undirected graph.
-* Objective: Find the shortest path that visits all vertices without repeating any, and returns to the starting vertex.
-*
-* 6
-* (4)-----(0)
-* | \ / \
-* | \ 3/ \2
-* | \/ \
-* 3| /\ (1)
-* | / 3\ 4/ |
-* | / \ / |
-* (3)-----(2) |
-* | 7 |
-* | | 3
-* --------------
-*
-* Distance Matrix
-* 0 1 2 3 4
-* 0 0 2 - 3 6
-* 1 2 0 4 3 -
-* 2 - 4 0 7 3
-* 3 3 3 7 0 3
-* 4 6 - 3 3 0
-*/
+ * Traveling Salesman Problem in C
+ * Using a distance matrix to represent an undirected graph.
+ * Objective: Find the shortest path that visits all vertices without
+ *repeating any, and returns to the starting vertex.
+ *
+ * 6
+ * (4)-----(0)
+ * | \ / \
+ * | \ 3/ \2
+ * | \/ \
+ * 3| /\ (1)
+ * | / 3\ 4/ |
+ * | / \ / |
+ * (3)-----(2) |
+ * | 7 |
+ * | | 3
+ * --------------
+ *
+ * Distance Matrix
+ * 0 1 2 3 4
+ * 0 0 2 - 3 6
+ * 1 2 0 4 3 -
+ * 2 - 4 0 7 3
+ * 3 3 3 7 0 3
+ * 4 6 - 3 3 0
+ */
-#include
#include
+#include
#define VERTICES 5
#define INFINITY 429496729
@@ -37,66 +38,79 @@ bool visited[VERTICES];
int bestSolutionValue = INFINITY;
int currentSolutionValue = 0;
-int matrix[VERTICES][VERTICES] = {{ 0, 2, INFINITY, 3, 6 },
- { 2, 0, 4, 3, INFINITY },
- { INFINITY, 4, 0, 7, 3 },
- { 3, 3, 7, 0, 3 },
- { 6, INFINITY, 3, 3, 0 }};
+int matrix[VERTICES][VERTICES] = {{0, 2, INFINITY, 3, 6},
+ {2, 0, 4, 3, INFINITY},
+ {INFINITY, 4, 0, 7, 3},
+ {3, 3, 7, 0, 3},
+ {6, INFINITY, 3, 3, 0}};
void travelingSalesmanAux(int x) {
- // If the current solution value is already greater than the best solution, stop as it can't be the best solution
- if (currentSolutionValue > bestSolutionValue)
- return;
+ // If the current solution value is already greater than the best solution,
+ // stop as it can't be the best solution
+ if (currentSolutionValue > bestSolutionValue)
+ return;
- if (x == VERTICES) { // If x == VERTICES, it means the temporary solution array is complete
- int distance = matrix[tempSolution[x-1]][tempSolution[0]];
- // If a better (shorter) solution is found
- if (distance < INFINITY && currentSolutionValue + distance < bestSolutionValue) {
- bestSolutionValue = currentSolutionValue + distance; // Update the best solution with the new better one
- // Copy the entire temporary solution array to the best solution array
- for (int i = 0; i < VERTICES; ++i) {
- bestSolution[i] = tempSolution[i];
- }
- }
- return;
+ if (x == VERTICES) { // If x == VERTICES, it means the temporary solution
+ // array is complete
+ int distance = matrix[tempSolution[x - 1]][tempSolution[0]];
+ // If a better (shorter) solution is found
+ if (distance < INFINITY &&
+ currentSolutionValue + distance < bestSolutionValue) {
+ bestSolutionValue =
+ currentSolutionValue +
+ distance; // Update the best solution with the new better one
+ // Copy the entire temporary solution array to the best solution array
+ for (int i = 0; i < VERTICES; ++i) {
+ bestSolution[i] = tempSolution[i];
+ }
}
+ return;
+ }
- int last = tempSolution[x-1]; // 'last' holds the number of the last vertex in the temporary solution array
- // Loop through all columns in the matrix on the row of the last vertex in the temporary solution array
- for (int i = 0; i < VERTICES; i++) {
- // If the i-th vertex hasn't been visited, and the matrix value is less than INFINITY
- if (!visited[i] && matrix[last][i] < INFINITY) {
- visited[i] = true; // Mark as visited
- tempSolution[x] = i; // Add the current vertex to the temporary solution array
- currentSolutionValue += matrix[last][i]; // Increment the path total
- travelingSalesmanAux(x + 1); // Recursively call for the next vertex
- currentSolutionValue -= matrix[last][i]; // Decrease the path total if not finished yet
- visited[i] = false; // Mark the vertex as unvisited so it can be used again by another vertex
- }
+ int last = tempSolution[x - 1]; // 'last' holds the number of the last vertex
+ // in the temporary solution array
+ // Loop through all columns in the matrix on the row of the last vertex in the
+ // temporary solution array
+ for (int i = 0; i < VERTICES; i++) {
+ // If the i-th vertex hasn't been visited, and the matrix value is less than
+ // INFINITY
+ if (!visited[i] && matrix[last][i] < INFINITY) {
+ visited[i] = true; // Mark as visited
+ tempSolution[x] =
+ i; // Add the current vertex to the temporary solution array
+ currentSolutionValue += matrix[last][i]; // Increment the path total
+ travelingSalesmanAux(x + 1); // Recursively call for the next vertex
+ currentSolutionValue -=
+ matrix[last][i]; // Decrease the path total if not finished yet
+ visited[i] = false; // Mark the vertex as unvisited so it can be used
+ // again by another vertex
}
+ }
}
void travelingSalesman(int start) {
- visited[start] = true; // Mark the starting vertex as visited (0)
- tempSolution[0] = start; // Place vertex 0 in the first position of the temporary solution array
- travelingSalesmanAux(1); // Call the auxiliary function for the traveling salesman problem
+ visited[start] = true; // Mark the starting vertex as visited (0)
+ tempSolution[0] = start; // Place vertex 0 in the first position of the
+ // temporary solution array
+ travelingSalesmanAux(
+ 1); // Call the auxiliary function for the traveling salesman problem
}
void initializeArrays() {
- for (int i = 0; i < VERTICES; i++) {
- visited[i] = false;
- tempSolution[i] = -1;
- bestSolution[i] = -1;
- }
+ for (int i = 0; i < VERTICES; i++) {
+ visited[i] = false;
+ tempSolution[i] = -1;
+ bestSolution[i] = -1;
+ }
}
int main() {
- initializeArrays();
- travelingSalesman(0);
+ initializeArrays();
+ travelingSalesman(0);
- printf("Minimum path cost: %d\n", bestSolutionValue);
- for (int i = 0; i < VERTICES; i++) {
- printf("%d, ", bestSolution[i]);
- }
- printf("\n\n");
+ printf("Minimum path cost: %d\n", bestSolutionValue);
+ for (int i = 0; i < VERTICES; i++) {
+ printf("%d, ", bestSolution[i]);
+ }
+ printf("\n\n");
}
diff --git a/src/c/TwoSum.c b/src/c/TwoSum.c
index 65162435..ec52ae66 100644
--- a/src/c/TwoSum.c
+++ b/src/c/TwoSum.c
@@ -1,61 +1,59 @@
/*
TwoSum Algorithm in C
- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
-
- You may assume that each input would have exactly one solution, and you may not use the same element twice.
-
- You can return the answer in any order.
+ Given an array of integers nums and an integer target, return indices of
+the two numbers such that they add up to target.
+
+ You may assume that each input would have exactly one solution, and you
+may not use the same element twice.
+
+ You can return the answer in any order.
*/
#include
#include
-int* twoSum(int* nums, int numsSize, int target){
-
- for(int i=0;i
#include
+#include
#define ERRO -1
typedef int TIPOCHAVE;
-typedef struct aux{
- TIPOCHAVE chave;
- struct aux *prox;
-}REGISTRO, *PONT;
+typedef struct aux {
+ TIPOCHAVE chave;
+ struct aux *prox;
+} REGISTRO, *PONT;
-PONT criaRegistro(TIPOCHAVE ch){
- PONT rg = (PONT) malloc( sizeof(PONT) );
- rg->chave = ch;
- rg->prox = NULL;
- return rg;
+PONT criaRegistro(TIPOCHAVE ch) {
+ PONT rg = (PONT)malloc(sizeof(PONT));
+ rg->chave = ch;
+ rg->prox = NULL;
+ return rg;
}
-PONT insereRegistro(TIPOCHAVE ch, PONT rg){
- if( rg == NULL )
- return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo
- while( rg->prox != NULL )
- rg = rg->prox;
- rg->prox = criaRegistro(ch);
- return NULL;
+PONT insereRegistro(TIPOCHAVE ch, PONT rg) {
+ if (rg == NULL)
+ return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo
+ while (rg->prox != NULL)
+ rg = rg->prox;
+ rg->prox = criaRegistro(ch);
+ return NULL;
}
-void mostraLista(PONT rg){
- if( rg == NULL ) return;
- printf("%d, ", rg->chave);
- mostraLista(rg->prox);
+void mostraLista(PONT rg) {
+ if (rg == NULL)
+ return;
+ printf("%d, ", rg->chave);
+ mostraLista(rg->prox);
}
-PONT buscaSequencial(TIPOCHAVE ch, PONT rg){
- while( rg != NULL ){
- if( rg->chave == ch )
- return rg;
- rg = rg->prox;
- }
- return NULL;
+PONT buscaSequencial(TIPOCHAVE ch, PONT rg) {
+ while (rg != NULL) {
+ if (rg->chave == ch)
+ return rg;
+ rg = rg->prox;
+ }
+ return NULL;
}
-bool deletaRegistro(TIPOCHAVE ch, PONT rg){
- PONT ant;
- while( rg != NULL ){
- if( rg->chave == ch ){
- ant->prox = rg->prox;
- free(rg);
- return true;
- }
- ant = rg;
- rg = rg->prox;
- }
- printf("\nChave %d não encontrada.\n",ch);
- return false;
+bool deletaRegistro(TIPOCHAVE ch, PONT rg) {
+ PONT ant;
+ while (rg != NULL) {
+ if (rg->chave == ch) {
+ ant->prox = rg->prox;
+ free(rg);
+ return true;
+ }
+ ant = rg;
+ rg = rg->prox;
+ }
+ printf("\nChave %d não encontrada.\n", ch);
+ return false;
}
-int main(){
- PONT RG = insereRegistro(23, RG);
- insereRegistro(34, RG);
- insereRegistro(12, RG);
- insereRegistro(63, RG);
- insereRegistro(45, RG);
+int main() {
+ PONT RG = insereRegistro(23, RG);
+ insereRegistro(34, RG);
+ insereRegistro(12, RG);
+ insereRegistro(63, RG);
+ insereRegistro(45, RG);
+
+ mostraLista(RG);
- mostraLista(RG);
+ TIPOCHAVE ch = 64;
+ if (buscaSequencial(ch, RG) != NULL)
+ printf("\nEncontrou chave %d\n", ch);
+ else
+ printf("\nNão encontrou chave %d\n", ch);
- TIPOCHAVE ch = 64;
- if( buscaSequencial(ch, RG) != NULL )
- printf("\nEncontrou chave %d\n", ch);
- else
- printf("\nNão encontrou chave %d\n", ch);
+ deletaRegistro(63, RG);
+ mostraLista(RG);
- deletaRegistro(63, RG);
- mostraLista(RG);
-
- printf("\n");
- deletaRegistro(34, RG);
- mostraLista(RG);
- return 0;
+ printf("\n");
+ deletaRegistro(34, RG);
+ mostraLista(RG);
+ return 0;
}
\ No newline at end of file
From b495efaf553693a93d1e43bfbda9c3076fe6c87f Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 09:42:53 -0300
Subject: [PATCH 26/58] Format CPP code using CLANG_FORMAT
---
src/cpp/BinarySearch.cpp | 71 +++---
src/cpp/BinarySearchTree.cpp | 10 +-
src/cpp/BinaryTree.cpp | 198 +++++++--------
src/cpp/BubbleSort.cpp | 64 +++--
src/cpp/CalculatePi.cpp | 23 +-
src/cpp/ConnectedComponents.cpp | 61 +++--
src/cpp/CountingSort.cpp | 174 +++++++-------
src/cpp/Dijkstras_MinHeap.cpp | 121 +++++-----
src/cpp/DoublyLinkedList.cpp | 361 +++++++++++++---------------
src/cpp/DynamicQueue.cpp | 8 +-
src/cpp/DynamicStack.cpp | 4 +-
src/cpp/Exponentiation.cpp | 18 +-
src/cpp/ExponentiationRecursive.cpp | 18 +-
src/cpp/Factorial.cpp | 20 +-
src/cpp/FactorialRecursive.cpp | 19 +-
src/cpp/FibonacciIterative.cpp | 20 +-
src/cpp/FibonacciMemoization.cpp | 26 +-
src/cpp/FibonacciRecursive.cpp | 12 +-
src/cpp/FindDistinctSubsets.cpp | 62 +++--
src/cpp/FloydWarshall.cpp | 92 ++++---
src/cpp/GraphSearch.cpp | 196 +++++++--------
src/cpp/InsertionSort.cpp | 54 ++---
src/cpp/InterpolationSearch.cpp | 90 ++++---
src/cpp/LinearSearch.cpp | 41 ++--
src/cpp/LinearSearchRecursive.cpp | 2 +-
src/cpp/MaxRecursive.cpp | 43 ++--
src/cpp/MergeSort.cpp | 135 +++++------
src/cpp/MinMaxDC.cpp | 69 +++---
src/cpp/MinMaxIterative.cpp | 20 +-
src/cpp/Palindrome.cpp | 67 +++---
src/cpp/QuickSort.cpp | 85 +++----
src/cpp/RottenOranges.cpp | 117 ++++-----
src/cpp/SelectionSort.cpp | 66 +++--
src/cpp/SinglyLinkedList.cpp | 219 ++++++++---------
src/cpp/Stack.cpp | 90 +++----
src/cpp/TowerOfHanoi.cpp | 72 +++---
36 files changed, 1297 insertions(+), 1451 deletions(-)
diff --git a/src/cpp/BinarySearch.cpp b/src/cpp/BinarySearch.cpp
index dcc7e6fc..5e7d778c 100644
--- a/src/cpp/BinarySearch.cpp
+++ b/src/cpp/BinarySearch.cpp
@@ -3,52 +3,39 @@
using namespace std;
-int binarySearch(int value, vector &vec, int leftIndex, int rightIndex)
-{
- int mid = (leftIndex + rightIndex) / 2;
-
- if (leftIndex <= rightIndex)
- {
- if (value > vec[mid])
- {
- leftIndex = mid + 1;
- return binarySearch(value, vec, leftIndex, rightIndex);
- }
- else if (value < vec[mid])
- {
- rightIndex = mid - 1;
- return binarySearch(value, vec, leftIndex, rightIndex);
- }
- else
- {
- return mid;
- }
- }
- else
- {
- return -1;
+int binarySearch(int value, vector &vec, int leftIndex, int rightIndex) {
+ int mid = (leftIndex + rightIndex) / 2;
+
+ if (leftIndex <= rightIndex) {
+ if (value > vec[mid]) {
+ leftIndex = mid + 1;
+ return binarySearch(value, vec, leftIndex, rightIndex);
+ } else if (value < vec[mid]) {
+ rightIndex = mid - 1;
+ return binarySearch(value, vec, leftIndex, rightIndex);
+ } else {
+ return mid;
}
+ } else {
+ return -1;
+ }
}
-int main()
-{
- vector vec;
-
- for (int index = 1; index <= 50; index++)
- {
- vec.push_back(index);
- }
+int main() {
+ vector vec;
- int value = 45;
+ for (int index = 1; index <= 50; index++) {
+ vec.push_back(index);
+ }
- int index = binarySearch(value, vec, 0, vec.size());
+ int value = 45;
- if (index >= 0)
- {
- cout << "Value " << to_string(value) << " found at position " << to_string(index) << endl;
- }
- else
- {
- cout << "Could not find the value " << to_string(value) << endl;
- }
+ int index = binarySearch(value, vec, 0, vec.size());
+
+ if (index >= 0) {
+ cout << "Value " << to_string(value) << " found at position "
+ << to_string(index) << endl;
+ } else {
+ cout << "Could not find the value " << to_string(value) << endl;
+ }
}
\ No newline at end of file
diff --git a/src/cpp/BinarySearchTree.cpp b/src/cpp/BinarySearchTree.cpp
index ddc01eb4..9973dc0a 100644
--- a/src/cpp/BinarySearchTree.cpp
+++ b/src/cpp/BinarySearchTree.cpp
@@ -4,9 +4,9 @@
* Structure for a binary tree node
*/
struct Node {
- int data; ///< The integer data value stored in the node.
- Node *left; ///< Pointer to the left child node.
- Node *right; ///< Pointer to the right child node.
+ int data; ///< The integer data value stored in the node.
+ Node *left; ///< Pointer to the left child node.
+ Node *right; ///< Pointer to the right child node.
/**
* Constructor to create a new node with the given data.
@@ -17,7 +17,7 @@ struct Node {
};
class BinarySearchTree {
- public:
+public:
BinarySearchTree() : root(nullptr) {}
Node *find(int x) const { return _find(this->root, x); }
@@ -32,7 +32,7 @@ class BinarySearchTree {
void postorderTraversal() const { _printPostorder(this->root); }
- private:
+private:
Node *root;
/**
diff --git a/src/cpp/BinaryTree.cpp b/src/cpp/BinaryTree.cpp
index 7a37cd63..3f77440a 100644
--- a/src/cpp/BinaryTree.cpp
+++ b/src/cpp/BinaryTree.cpp
@@ -3,124 +3,108 @@
using namespace std;
// Create a class for the BinaryTree
-class BinaryTree
-{
- // Create a struct for the TreeNode
- struct TreeNode
- {
- // Variables for the TreeNode
- int data;
- TreeNode* left;
- TreeNode* right;
-
- // Constructor for the TreeNode
- TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
- };
-
- // Private Variables and Functions
+class BinaryTree {
+ // Create a struct for the TreeNode
+ struct TreeNode {
+ // Variables for the TreeNode
+ int data;
+ TreeNode *left;
+ TreeNode *right;
+
+ // Constructor for the TreeNode
+ TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
+ };
+
+ // Private Variables and Functions
private:
- TreeNode* root;
-
- //Insert Function
- TreeNode* insert(TreeNode* root, int value)
- {
- if (root == nullptr)
- return new TreeNode(value);
-
- if (value < root->data)
- root->left = insert(root->left, value);
- else
- root->right = insert(root->right, value);
-
- return root;
- }
-
- // Print Inorder Function
- void printInorder(TreeNode* head)
- {
- if (head != nullptr)
- {
- printInorder(head->left);
- cout << head->data << " ";
- printInorder(head->right);
- }
+ TreeNode *root;
+
+ // Insert Function
+ TreeNode *insert(TreeNode *root, int value) {
+ if (root == nullptr)
+ return new TreeNode(value);
+
+ if (value < root->data)
+ root->left = insert(root->left, value);
+ else
+ root->right = insert(root->right, value);
+
+ return root;
+ }
+
+ // Print Inorder Function
+ void printInorder(TreeNode *head) {
+ if (head != nullptr) {
+ printInorder(head->left);
+ cout << head->data << " ";
+ printInorder(head->right);
}
-
- // Print Preorder Function
- void printPreorder(TreeNode* head)
- {
- if (head != nullptr)
- {
- cout << head->data << " ";
- printPreorder(head->left);
- printPreorder(head->right);
- }
+ }
+
+ // Print Preorder Function
+ void printPreorder(TreeNode *head) {
+ if (head != nullptr) {
+ cout << head->data << " ";
+ printPreorder(head->left);
+ printPreorder(head->right);
}
-
- // Print Postorder Function
- void printPostorder(TreeNode* head)
- {
- if (head != nullptr)
- {
- printPostorder(head->left);
- printPostorder(head->right);
- cout << head->data << " ";
- }
+ }
+
+ // Print Postorder Function
+ void printPostorder(TreeNode *head) {
+ if (head != nullptr) {
+ printPostorder(head->left);
+ printPostorder(head->right);
+ cout << head->data << " ";
}
+ }
- // Public Functions
+ // Public Functions
public:
- // Constructor
- BinaryTree() : root(nullptr) {}
-
- // Insert Function
- void insert(int value)
- {
- root = insert(root, value);
- }
-
- // Print Inorder Function
- void printInorder()
- {
- printInorder(root);
- cout << endl;
- }
-
- // Print Preorder Function
- void printPreorder()
- {
- printPreorder(root);
- cout << endl;
- }
-
- // Print Postorder Function
- void printPostorder()
- {
- printPostorder(root);
- cout << endl;
- }
+ // Constructor
+ BinaryTree() : root(nullptr) {}
+
+ // Insert Function
+ void insert(int value) { root = insert(root, value); }
+
+ // Print Inorder Function
+ void printInorder() {
+ printInorder(root);
+ cout << endl;
+ }
+
+ // Print Preorder Function
+ void printPreorder() {
+ printPreorder(root);
+ cout << endl;
+ }
+
+ // Print Postorder Function
+ void printPostorder() {
+ printPostorder(root);
+ cout << endl;
+ }
};
-int main()
-{
- // Create tree
- BinaryTree binaryTree;
+int main() {
+ // Create tree
+ BinaryTree binaryTree;
- binaryTree.insert(10);
- binaryTree.insert(6);
- binaryTree.insert(15);
- binaryTree.insert(3);
- binaryTree.insert(8);
- binaryTree.insert(20);
+ binaryTree.insert(10);
+ binaryTree.insert(6);
+ binaryTree.insert(15);
+ binaryTree.insert(3);
+ binaryTree.insert(8);
+ binaryTree.insert(20);
- cout << "InOrder: ";
- binaryTree.printInorder();
+ cout << "InOrder: ";
+ binaryTree.printInorder();
- cout << "PreOrder: ";
- binaryTree.printPreorder();
+ cout << "PreOrder: ";
+ binaryTree.printPreorder();
- cout << "PostOrder: ";
- binaryTree.printPostorder();
+ cout << "PostOrder: ";
+ binaryTree.printPostorder();
- return 0;
+ return 0;
}
diff --git a/src/cpp/BubbleSort.cpp b/src/cpp/BubbleSort.cpp
index 80614b00..5d4dafaa 100644
--- a/src/cpp/BubbleSort.cpp
+++ b/src/cpp/BubbleSort.cpp
@@ -3,45 +3,37 @@
using namespace std;
-vector bubbleSort(vector vector)
-{
- for (uint32_t end = vector.size()-1; end > 0; --end)
- {
- for (uint32_t index = 0; index < end; ++index)
- {
- if (vector[index] > vector[index+1])
- {
- int temp = vector[index];
- vector[index] = vector[index+1];
- vector[index+1] = temp;
- }
- }
+vector bubbleSort(vector vector) {
+ for (uint32_t end = vector.size() - 1; end > 0; --end) {
+ for (uint32_t index = 0; index < end; ++index) {
+ if (vector[index] > vector[index + 1]) {
+ int temp = vector[index];
+ vector[index] = vector[index + 1];
+ vector[index + 1] = temp;
+ }
}
- return vector;
+ }
+ return vector;
}
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- if (i +1 == vector.size())
- cout << vector[i];
- else
- cout << vector[i] << ", ";
- }
- cout << "\n";
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ if (i + 1 == vector.size())
+ cout << vector[i];
+ else
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- cout << "Initial Vector: ";
- showVector(vector);
- vector = bubbleSort(vector);
- cout << "Sorted Vector: ";
- showVector(vector);
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ cout << "Initial Vector: ";
+ showVector(vector);
+ vector = bubbleSort(vector);
+ cout << "Sorted Vector: ";
+ showVector(vector);
}
diff --git a/src/cpp/CalculatePi.cpp b/src/cpp/CalculatePi.cpp
index bbdb28db..25f92878 100644
--- a/src/cpp/CalculatePi.cpp
+++ b/src/cpp/CalculatePi.cpp
@@ -5,19 +5,16 @@ float pi = 0.0;
float denominator = 1.0;
float operation = 1.0;
-float pi_calculator(int terms)
-{
- for (int i = 0; i < terms; i++)
- {
- pi += operation * (4.0 / denominator);
- denominator += 2.0;
- operation *= -1.0;
- }
- return pi;
+float pi_calculator(int terms) {
+ for (int i = 0; i < terms; i++) {
+ pi += operation * (4.0 / denominator);
+ denominator += 2.0;
+ operation *= -1.0;
+ }
+ return pi;
}
-int main()
-{
- float result = pi_calculator(100000);
- cout << result;
+int main() {
+ float result = pi_calculator(100000);
+ cout << result;
}
diff --git a/src/cpp/ConnectedComponents.cpp b/src/cpp/ConnectedComponents.cpp
index ac565f58..050222e3 100644
--- a/src/cpp/ConnectedComponents.cpp
+++ b/src/cpp/ConnectedComponents.cpp
@@ -8,46 +8,39 @@ std::vector visited(VERTICES, false); // Array to track visited vertices
int components = 0;
// Adjacency matrix representing the graph
-int matrix[VERTICES][VERTICES] = {{0, INF, 1, INF, INF, INF},
- {INF, 0, INF, 1, 1, INF},
- {1, INF, 0, INF, INF, INF},
- {INF, 1, INF, 0, 1, 1},
- {INF, 1, INF, 1, 0, 1},
- {INF, INF, INF, 1, 1, 0}};
+int matrix[VERTICES][VERTICES] = {
+ {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF},
+ {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1},
+ {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}};
// Recursive method to find connected components using adjacency matrix
-void findConnectedComponents(int current)
-{
- for (int i = 0; i < VERTICES; i++)
- {
- if (!visited[i] && matrix[current][i] == 1)
- {
- visited[i] = true;
- components++;
- std::cout << "(" << i << ")-";
- findConnectedComponents(i);
- }
+void findConnectedComponents(int current) {
+ for (int i = 0; i < VERTICES; i++) {
+ if (!visited[i] && matrix[current][i] == 1) {
+ visited[i] = true;
+ components++;
+ std::cout << "(" << i << ")-";
+ findConnectedComponents(i);
}
+ }
}
-int main()
-{
- // Initialize all vertices as unvisited
- for (int i = 0; i < VERTICES; i++)
- visited[i] = false;
+int main() {
+ // Initialize all vertices as unvisited
+ for (int i = 0; i < VERTICES; i++)
+ visited[i] = false;
- // For each vertex, if it is unvisited, start a DFS and count components
- for (int i = 0; i < VERTICES; i++)
- {
- if (!visited[i])
- {
- components = 0;
- visited[i] = true;
- std::cout << "Starting at vertex (" << i << ")-";
- findConnectedComponents(i);
- std::cout << "\nNumber of connected components starting from vertex " << i << ": " << components << "\n\n";
- }
+ // For each vertex, if it is unvisited, start a DFS and count components
+ for (int i = 0; i < VERTICES; i++) {
+ if (!visited[i]) {
+ components = 0;
+ visited[i] = true;
+ std::cout << "Starting at vertex (" << i << ")-";
+ findConnectedComponents(i);
+ std::cout << "\nNumber of connected components starting from vertex " << i
+ << ": " << components << "\n\n";
}
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/CountingSort.cpp b/src/cpp/CountingSort.cpp
index 400b6a54..1a6733fa 100644
--- a/src/cpp/CountingSort.cpp
+++ b/src/cpp/CountingSort.cpp
@@ -1,107 +1,105 @@
+#include
#include
#include
-#include
using namespace std;
-vector counting_sort(vector& nums) {
-
-
- // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- // max = 9
- // The vector contains numbers between [0 .. max]
- auto max = *max_element(nums.begin(), nums.end());
-
-
- // Creates a vector with max + 1 positions to count occurrences of each element
- // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in the vector nums
- // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
- vector counting(max+1);
-
-
- // Counts occurrences of each element
- // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- //
- // 0 1 2 3 4 5 6 7 8 9
- // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1}
- //
- for(auto& i : nums) {
- counting[i]++;
- }
-
-
- // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
- // It will be used to determine the positions of the elements in the ordered vector
- for (size_t i = 1; i < counting.size(); i++) {
-
- counting[i] += counting[i-1];
- }
-
- vector sorted(nums.size());
-
- /*
-
- The next loop places the numbers in their proper positions in the ordered vector
- i = iterates through the elements of nums
- counting[i] -1 is the position that element i must assume in the ordered vector
-
- The first 3 steps would be:
-
- nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
- counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
-
- Step 1:
- i = 5
- counting[i] => counting[5] => 9
- sorted[9 - 1] => sorted[8] = i => sorted[8] = 5
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
-
- Step 2:
- i = 0
- counting[i] => counting[0] => 2
- sorted[2 - 1] => sorted[1] = i => sorted[1] = 0
- sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
-
- Step 3:
- i = 1
- counting[i] => counting[1] => 3
- sorted[3 - 1] => sorted[2] = i => sorted[2] = 1
- sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0}
- */
- for(auto& i : nums) {
- sorted[ counting[i]-1 ] = i;
- counting[i]--;
- }
-
- return sorted;
+vector counting_sort(vector &nums) {
+
+ // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ // max = 9
+ // The vector contains numbers between [0 .. max]
+ auto max = *max_element(nums.begin(), nums.end());
+
+ // Creates a vector with max + 1 positions to count occurrences of each
+ // element
+ // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in
+ // the vector nums
+ // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+ vector counting(max + 1);
+
+ // Counts occurrences of each element
+ // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ //
+ // 0 1 2 3 4 5 6 7 8 9
+ // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1}
+ //
+ for (auto &i : nums) {
+ counting[i]++;
+ }
+
+ // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
+ // It will be used to determine the positions of the elements in the ordered
+ // vector
+ for (size_t i = 1; i < counting.size(); i++) {
+
+ counting[i] += counting[i - 1];
+ }
+
+ vector sorted(nums.size());
+
+ /*
+
+ The next loop places the numbers in their proper positions in the ordered
+ vector i = iterates through the elements of nums counting[i] -1 is the
+ position that element i must assume in the ordered vector
+
+ The first 3 steps would be:
+
+ nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4}
+ counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10}
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+
+ Step 1:
+ i = 5
+ counting[i] => counting[5] => 9
+ sorted[9 - 1] => sorted[8] = i => sorted[8] = 5
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
+
+ Step 2:
+ i = 0
+ counting[i] => counting[0] => 2
+ sorted[2 - 1] => sorted[1] = i => sorted[1] = 0
+ sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0}
+
+ Step 3:
+ i = 1
+ counting[i] => counting[1] => 3
+ sorted[3 - 1] => sorted[2] = i => sorted[2] = 1
+ sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0}
+ */
+ for (auto &i : nums) {
+ sorted[counting[i] - 1] = i;
+ counting[i]--;
+ }
+
+ return sorted;
}
void print_vector(vector vec) {
- cout << "[";
- for (size_t i = 0; i < vec.size(); i++) {
- if(i != vec.size()-1) {
- cout << vec[i] << ", ";
- }
- else {
- cout << vec[i];
- }
+ cout << "[";
+ for (size_t i = 0; i < vec.size(); i++) {
+ if (i != vec.size() - 1) {
+ cout << vec[i] << ", ";
+ } else {
+ cout << vec[i];
}
- cout << "]" << endl;
+ }
+ cout << "]" << endl;
}
int main() {
- vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4};
+ vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4};
- vector sorted = counting_sort(nums);
+ vector sorted = counting_sort(nums);
- cout << "Original vector = ";
- print_vector(nums);
+ cout << "Original vector = ";
+ print_vector(nums);
- cout << "Sorted vector = ";
- print_vector(sorted);
+ cout << "Sorted vector = ";
+ print_vector(sorted);
- return 0;
+ return 0;
}
diff --git a/src/cpp/Dijkstras_MinHeap.cpp b/src/cpp/Dijkstras_MinHeap.cpp
index 179db585..13ff75bb 100644
--- a/src/cpp/Dijkstras_MinHeap.cpp
+++ b/src/cpp/Dijkstras_MinHeap.cpp
@@ -2,10 +2,12 @@
* Dijkstras_MinHeap.cpp
*
* This file implements Dijkstra's algorithm using a min-heap (priority queue).
- * The algorithm finds the shortest paths from the source vertex to all other vertices in a weighted graph.
+ * The algorithm finds the shortest paths from the source vertex to all other
+ * vertices in a weighted graph.
*
* Functions:
- * - void dijkstra(const unordered_map>& graph, int start_vertex)
+ * - void dijkstra(const unordered_map>& graph, int
+ * start_vertex)
* - graph: An adjacency list representation of the graph.
* - key: vertex
* - value: unordered_map of connected vertices and their edge weights
@@ -13,88 +15,87 @@
*
* Example Usage:
* Uncomment the main function to run a sample test case.
- * The sample graph used in the main function is represented as an adjacency list.
+ * The sample graph used in the main function is represented as an adjacency
+ * list.
*/
#include
-#include
+#include
#include
#include
-#include
+#include
using namespace std;
// A structure to represent a node in the priority queue
struct Node {
- int vertex;
- int distance;
- bool operator>(const Node& other) const {
- return distance > other.distance;
- }
+ int vertex;
+ int distance;
+ bool operator>(const Node &other) const { return distance > other.distance; }
};
-void dijkstra(const unordered_map>& graph, int start_vertex) {
- // Initialize distances and predecessors
- unordered_map dist;
- unordered_map pred;
- for (const auto& pair : graph) {
- dist[pair.first] = numeric_limits::max();
- pred[pair.first] = -1;
- }
- dist[start_vertex] = 0;
+void dijkstra(const unordered_map> &graph,
+ int start_vertex) {
+ // Initialize distances and predecessors
+ unordered_map dist;
+ unordered_map pred;
+ for (const auto &pair : graph) {
+ dist[pair.first] = numeric_limits::max();
+ pred[pair.first] = -1;
+ }
+ dist[start_vertex] = 0;
- // Priority queue to store vertices and their distances
- priority_queue, greater> priority_queue;
- priority_queue.push({ start_vertex, 0 });
+ // Priority queue to store vertices and their distances
+ priority_queue, greater> priority_queue;
+ priority_queue.push({start_vertex, 0});
- while (!priority_queue.empty()) {
- Node current = priority_queue.top();
- priority_queue.pop();
+ while (!priority_queue.empty()) {
+ Node current = priority_queue.top();
+ priority_queue.pop();
- // If this distance is not updated, continue
- if (current.distance > dist[current.vertex]) {
- continue;
- }
+ // If this distance is not updated, continue
+ if (current.distance > dist[current.vertex]) {
+ continue;
+ }
- // Visit each neighbor of the current vertex
- for (const auto& neighbor_pair : graph.at(current.vertex)) {
- int neighbor = neighbor_pair.first;
- int weight = neighbor_pair.second;
- int distance = current.distance + weight;
+ // Visit each neighbor of the current vertex
+ for (const auto &neighbor_pair : graph.at(current.vertex)) {
+ int neighbor = neighbor_pair.first;
+ int weight = neighbor_pair.second;
+ int distance = current.distance + weight;
- // If a shorter path to the neighbor is found
- if (distance < dist[neighbor]) {
- dist[neighbor] = distance;
- pred[neighbor] = current.vertex;
- priority_queue.push({ neighbor, distance });
- }
- }
+ // If a shorter path to the neighbor is found
+ if (distance < dist[neighbor]) {
+ dist[neighbor] = distance;
+ pred[neighbor] = current.vertex;
+ priority_queue.push({neighbor, distance});
+ }
}
+ }
- // Print distances and predecessors
- cout << "Distances: \n";
- for (const auto& pair : dist) {
- cout << "Vertex " << pair.first << ": " << pair.second << endl;
- }
- cout << "\nPredecessors: \n";
- for (const auto& pair : pred) {
- cout << "Vertex " << pair.first << ": " << pair.second << endl;
- }
+ // Print distances and predecessors
+ cout << "Distances: \n";
+ for (const auto &pair : dist) {
+ cout << "Vertex " << pair.first << ": " << pair.second << endl;
+ }
+ cout << "\nPredecessors: \n";
+ for (const auto &pair : pred) {
+ cout << "Vertex " << pair.first << ": " << pair.second << endl;
+ }
}
// Uncomment the following main function to run a sample test case
int main() {
- // Example graph represented as an adjacency list
- unordered_map> graph = {
- {0, {{1, 1}, {2, 4}}},
- {1, {{0, 1}, {2, 2}, {3, 5}}},
- {2, {{0, 4}, {1, 2}, {3, 1}}},
- {3, {{1, 5}, {2, 1}}}
- };
+ // Example graph represented as an adjacency list
+ unordered_map> graph = {
+ {0, {{1, 1}, {2, 4}}},
+ {1, {{0, 1}, {2, 2}, {3, 5}}},
+ {2, {{0, 4}, {1, 2}, {3, 1}}},
+ {3, {{1, 5}, {2, 1}}}};
- // Running Dijkstra's algorithm from vertex 0
- dijkstra(graph, 0);
+ // Running Dijkstra's algorithm from vertex 0
+ dijkstra(graph, 0);
- return 0;
+ return 0;
}
diff --git a/src/cpp/DoublyLinkedList.cpp b/src/cpp/DoublyLinkedList.cpp
index f75e2b9b..15dc333f 100644
--- a/src/cpp/DoublyLinkedList.cpp
+++ b/src/cpp/DoublyLinkedList.cpp
@@ -1,223 +1,190 @@
#include
-class Node
-{
+class Node {
private:
- int value;
+ int value;
public:
- Node *next{nullptr};
- Node *previous{nullptr};
+ Node *next{nullptr};
+ Node *previous{nullptr};
- // Node constructor
- Node(int value)
- {
- this->value = value;
- }
+ // Node constructor
+ Node(int value) { this->value = value; }
- int getValue() { return this->value; };
+ int getValue() { return this->value; };
};
-class DoublyLinkedList
-{
+class DoublyLinkedList {
private:
- Node *first{nullptr};
-
- // Receives the node reference and make the pointers around stop pointing to
- void remove_pointers_to(Node *&node)
- {
- if (node->next)
- {
- node->next->previous = node->previous;
- }
- if (node->previous)
- {
- node->previous->next = node->next;
- }
- else
- {
- this->first = node->next;
- }
+ Node *first{nullptr};
+
+ // Receives the node reference and make the pointers around stop pointing to
+ void remove_pointers_to(Node *&node) {
+ if (node->next) {
+ node->next->previous = node->previous;
+ }
+ if (node->previous) {
+ node->previous->next = node->next;
+ } else {
+ this->first = node->next;
}
+ }
public:
- DoublyLinkedList() {}
-
- void push_front(int value)
- {
- // Initialize a pointier to a new node with received value
- Node *node = new Node(value);
- // Node points to the first
- node->next = this->first;
-
- // If there is a first node, make him point to new node
- if (this->first)
- {
- this->first->previous = node;
- }
-
- // Node becomes the first
- this->first = node;
- }
-
- // Checks if there is a first node
- bool isEmpty()
- {
- if (!this->first)
- {
- return true;
- }
- return false;
- }
-
- void push_back(int value)
- {
- Node *node = new Node(value);
- Node *selectedNode = this->first;
-
- if (this->isEmpty())
- {
- this->first = node;
- return;
- }
-
- Node *aux{nullptr};
- while (selectedNode)
- {
- aux = selectedNode;
- selectedNode = selectedNode->next;
- }
-
- node->previous = aux;
- aux->next = node;
- };
-
- void remove(int value)
- {
- // Throw exception to empty List
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- // Initialize a pointier to first element
- Node *node = this->first;
-
- // Go through the list until find the value or the end
- while ((node) && (node->getValue() != value))
- {
- node = node->next;
- }
- // Throw exception if didn't find the value
- if (!node)
- {
- throw std::logic_error("Value must be in the list!");
- }
-
- // Remove all pointier to the value if exists
- this->remove_pointers_to(node);
-
- // Delete node
- delete (node);
- }
-
- // Removes the k-th element, where k it's an ordinal number
- void remove_ordinary(int position)
- {
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- if (position < 1)
- {
- throw std::logic_error("Invalid position!");
- }
-
- Node *selectedNode = this->first;
- int aux = 1;
-
- while ((selectedNode) && (aux != position))
- {
- selectedNode = selectedNode->next;
- aux++;
- }
-
- if (!selectedNode)
- {
- throw std::logic_error("Index out of bound!");
- }
-
- this->remove_pointers_to(selectedNode);
-
- delete (selectedNode);
- }
-
- std::pair find(int value)
- {
- // Throw exception to empty List
- if (this->isEmpty())
- {
- throw std::logic_error("List is empty, nothing to be removed!");
- }
-
- // Initialize a pointier to first element
- Node *node = this->first;
-
- // Go through the list until find the value or the end
- while ((node) && (node->getValue() != value))
- {
- node = node->next;
- }
-
- if (!node)
- {
- return {false, nullptr};
- }
- return {true, node};
- }
-
- void print()
- {
- Node *selectedNode = this->first;
- std::cout << "[ ";
- while (selectedNode)
- {
- std::cout << selectedNode->getValue() << " ";
- selectedNode = selectedNode->next;
- }
- std::cout << "]" << std::endl;
+ DoublyLinkedList() {}
+
+ void push_front(int value) {
+ // Initialize a pointier to a new node with received value
+ Node *node = new Node(value);
+ // Node points to the first
+ node->next = this->first;
+
+ // If there is a first node, make him point to new node
+ if (this->first) {
+ this->first->previous = node;
+ }
+
+ // Node becomes the first
+ this->first = node;
+ }
+
+ // Checks if there is a first node
+ bool isEmpty() {
+ if (!this->first) {
+ return true;
+ }
+ return false;
+ }
+
+ void push_back(int value) {
+ Node *node = new Node(value);
+ Node *selectedNode = this->first;
+
+ if (this->isEmpty()) {
+ this->first = node;
+ return;
+ }
+
+ Node *aux{nullptr};
+ while (selectedNode) {
+ aux = selectedNode;
+ selectedNode = selectedNode->next;
+ }
+
+ node->previous = aux;
+ aux->next = node;
+ };
+
+ void remove(int value) {
+ // Throw exception to empty List
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ // Initialize a pointier to first element
+ Node *node = this->first;
+
+ // Go through the list until find the value or the end
+ while ((node) && (node->getValue() != value)) {
+ node = node->next;
+ }
+ // Throw exception if didn't find the value
+ if (!node) {
+ throw std::logic_error("Value must be in the list!");
+ }
+
+ // Remove all pointier to the value if exists
+ this->remove_pointers_to(node);
+
+ // Delete node
+ delete (node);
+ }
+
+ // Removes the k-th element, where k it's an ordinal number
+ void remove_ordinary(int position) {
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ if (position < 1) {
+ throw std::logic_error("Invalid position!");
+ }
+
+ Node *selectedNode = this->first;
+ int aux = 1;
+
+ while ((selectedNode) && (aux != position)) {
+ selectedNode = selectedNode->next;
+ aux++;
+ }
+
+ if (!selectedNode) {
+ throw std::logic_error("Index out of bound!");
+ }
+
+ this->remove_pointers_to(selectedNode);
+
+ delete (selectedNode);
+ }
+
+ std::pair find(int value) {
+ // Throw exception to empty List
+ if (this->isEmpty()) {
+ throw std::logic_error("List is empty, nothing to be removed!");
+ }
+
+ // Initialize a pointier to first element
+ Node *node = this->first;
+
+ // Go through the list until find the value or the end
+ while ((node) && (node->getValue() != value)) {
+ node = node->next;
+ }
+
+ if (!node) {
+ return {false, nullptr};
+ }
+ return {true, node};
+ }
+
+ void print() {
+ Node *selectedNode = this->first;
+ std::cout << "[ ";
+ while (selectedNode) {
+ std::cout << selectedNode->getValue() << " ";
+ selectedNode = selectedNode->next;
}
+ std::cout << "]" << std::endl;
+ }
};
-int main()
-{
- DoublyLinkedList *doubly_linked_list = new DoublyLinkedList();
+int main() {
+ DoublyLinkedList *doubly_linked_list = new DoublyLinkedList();
- std::cout << "Push_front(20, 30, 40):" << std::endl;
- doubly_linked_list->push_front(20);
- doubly_linked_list->push_front(30);
- doubly_linked_list->push_front(40);
+ std::cout << "Push_front(20, 30, 40):" << std::endl;
+ doubly_linked_list->push_front(20);
+ doubly_linked_list->push_front(30);
+ doubly_linked_list->push_front(40);
- doubly_linked_list->print();
+ doubly_linked_list->print();
- std::cout << "Remove second!" << std::endl;
+ std::cout << "Remove second!" << std::endl;
- doubly_linked_list->remove_ordinary(2);
+ doubly_linked_list->remove_ordinary(2);
- doubly_linked_list->print();
+ doubly_linked_list->print();
- std::cout << "Remove(20, 40)!" << std::endl;
- doubly_linked_list->remove(20);
- doubly_linked_list->remove(40);
+ std::cout << "Remove(20, 40)!" << std::endl;
+ doubly_linked_list->remove(20);
+ doubly_linked_list->remove(40);
- std::cout << "List is empty: ";
- doubly_linked_list->print();
+ std::cout << "List is empty: ";
+ doubly_linked_list->print();
- std::cout << "Push_back(512, 123, 412)!" << std::endl;
- doubly_linked_list->push_back(512);
- doubly_linked_list->push_back(123);
- doubly_linked_list->push_back(412);
+ std::cout << "Push_back(512, 123, 412)!" << std::endl;
+ doubly_linked_list->push_back(512);
+ doubly_linked_list->push_back(123);
+ doubly_linked_list->push_back(412);
- doubly_linked_list->print();
+ doubly_linked_list->print();
}
diff --git a/src/cpp/DynamicQueue.cpp b/src/cpp/DynamicQueue.cpp
index b0ad8c58..55da0122 100644
--- a/src/cpp/DynamicQueue.cpp
+++ b/src/cpp/DynamicQueue.cpp
@@ -9,11 +9,11 @@ struct Node {
};
class DynamicQueue {
- private:
+private:
Node *_begin;
Node *_end;
- public:
+public:
DynamicQueue() : _begin(nullptr), _end(nullptr) {}
~DynamicQueue() {
@@ -83,11 +83,11 @@ int main(void) {
queue.enqueue(5);
queue.enqueue(1231);
queue.enqueue(515);
- queue.print(); // 42 5 1231 515
+ queue.print(); // 42 5 1231 515
// Use 'delete' keyword to make the code leak-free
queue.dequeue();
queue.dequeue();
- queue.print(); // 1231 515
+ queue.print(); // 1231 515
return 0;
}
diff --git a/src/cpp/DynamicStack.cpp b/src/cpp/DynamicStack.cpp
index 0be4e546..08e11178 100644
--- a/src/cpp/DynamicStack.cpp
+++ b/src/cpp/DynamicStack.cpp
@@ -23,9 +23,7 @@ class Stack {
head = newNode;
}
- bool isEmpty() {
- return head == nullptr;
- }
+ bool isEmpty() { return head == nullptr; }
int pop() {
int value = emptyStack;
diff --git a/src/cpp/Exponentiation.cpp b/src/cpp/Exponentiation.cpp
index b5f07bc4..1e01d9ba 100644
--- a/src/cpp/Exponentiation.cpp
+++ b/src/cpp/Exponentiation.cpp
@@ -1,20 +1,18 @@
#include
-
int main() {
- long long int n, exp;
+ long long int n, exp;
- std::cin >> n >> exp;
+ std::cin >> n >> exp;
- long long int result = 1;
+ long long int result = 1;
- for (long long int i = 0; i < exp; i++) {
- result *= n;
- }
+ for (long long int i = 0; i < exp; i++) {
+ result *= n;
+ }
- std::cout << result << std::endl;
-
+ std::cout << result << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/ExponentiationRecursive.cpp b/src/cpp/ExponentiationRecursive.cpp
index 5b2f1c42..a8fd83fb 100644
--- a/src/cpp/ExponentiationRecursive.cpp
+++ b/src/cpp/ExponentiationRecursive.cpp
@@ -2,22 +2,20 @@
long long int exp(int n, int pow) {
- if(pow == 0)
- return 1;
+ if (pow == 0)
+ return 1;
- return n * exp(n, pow-1);
+ return n * exp(n, pow - 1);
}
-
int main() {
- long long int n, pow;
+ long long int n, pow;
- std::cin >> n >> pow;
+ std::cin >> n >> pow;
- n = exp(n, pow);
- std::cout << n << std::endl;
-
+ n = exp(n, pow);
+ std::cout << n << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/Factorial.cpp b/src/cpp/Factorial.cpp
index e6eaa18c..4c082b3c 100644
--- a/src/cpp/Factorial.cpp
+++ b/src/cpp/Factorial.cpp
@@ -2,21 +2,21 @@
int factorial(int n) {
- int fact = 1;
- for (size_t i = 1; i <= n; i++) {
- fact = i*fact;
- }
+ int fact = 1;
+ for (size_t i = 1; i <= n; i++) {
+ fact = i * fact;
+ }
- return fact;
+ return fact;
}
int main() {
- int nums[] = {0, 1, 2, 3, 4, 5};
+ int nums[] = {0, 1, 2, 3, 4, 5};
- for(auto i : nums) {
- std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl;
- }
+ for (auto i : nums) {
+ std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl;
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FactorialRecursive.cpp b/src/cpp/FactorialRecursive.cpp
index e222a2e4..2d584c65 100644
--- a/src/cpp/FactorialRecursive.cpp
+++ b/src/cpp/FactorialRecursive.cpp
@@ -2,21 +2,20 @@
int factorial(int n) {
- if(n == 0)
- return 1;
-
- else
- return n * (factorial(n-1));
+ if (n == 0)
+ return 1;
+ else
+ return n * (factorial(n - 1));
}
int main() {
- int nums[] = {0, 1, 2, 3, 4, 5};
+ int nums[] = {0, 1, 2, 3, 4, 5};
- for(auto i : nums) {
- std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl;
- }
+ for (auto i : nums) {
+ std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl;
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FibonacciIterative.cpp b/src/cpp/FibonacciIterative.cpp
index 5fbab951..3f5e04f8 100644
--- a/src/cpp/FibonacciIterative.cpp
+++ b/src/cpp/FibonacciIterative.cpp
@@ -3,16 +3,14 @@
using namespace std;
int fibonacci(int n) {
- int last = 0;
- int curr = 1;
- for (int index = 0; index < n; ++index) {
- int temp = curr;
- curr += last;
- last = temp;
- }
- return last;
+ int last = 0;
+ int curr = 1;
+ for (int index = 0; index < n; ++index) {
+ int temp = curr;
+ curr += last;
+ last = temp;
+ }
+ return last;
}
-int main() {
- cout << fibonacci(12) << endl;
-}
+int main() { cout << fibonacci(12) << endl; }
diff --git a/src/cpp/FibonacciMemoization.cpp b/src/cpp/FibonacciMemoization.cpp
index 9b8a6e91..0d133f65 100644
--- a/src/cpp/FibonacciMemoization.cpp
+++ b/src/cpp/FibonacciMemoization.cpp
@@ -6,23 +6,23 @@ using namespace std;
vector memo;
int fibonacci(int n) {
- if (n <= 1) {
- return n;
- }
- if (memo[n] != -1) {
- return memo[n];
- }
-
- memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
+ if (n <= 1) {
+ return n;
+ }
+ if (memo[n] != -1) {
return memo[n];
+ }
+
+ memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
+ return memo[n];
}
int main() {
- int test_nbr = 12;
+ int test_nbr = 12;
- // Initialize the memoization table with -1 (uncomputed)
- memo.assign(test_nbr + 1, -1);
+ // Initialize the memoization table with -1 (uncomputed)
+ memo.assign(test_nbr + 1, -1);
- cout << "memoization: " << fibonacci(test_nbr) << endl;
- return 0;
+ cout << "memoization: " << fibonacci(test_nbr) << endl;
+ return 0;
}
diff --git a/src/cpp/FibonacciRecursive.cpp b/src/cpp/FibonacciRecursive.cpp
index b740c642..703ad130 100644
--- a/src/cpp/FibonacciRecursive.cpp
+++ b/src/cpp/FibonacciRecursive.cpp
@@ -3,12 +3,10 @@
using namespace std;
int fibonacci(int n) {
- if (n <= 1) {
- return n;
- }
- return fibonacci(n-1) + fibonacci(n-2);
+ if (n <= 1) {
+ return n;
+ }
+ return fibonacci(n - 1) + fibonacci(n - 2);
}
-int main() {
- cout << fibonacci(12) << endl;
-}
+int main() { cout << fibonacci(12) << endl; }
diff --git a/src/cpp/FindDistinctSubsets.cpp b/src/cpp/FindDistinctSubsets.cpp
index 48699329..c0af7813 100644
--- a/src/cpp/FindDistinctSubsets.cpp
+++ b/src/cpp/FindDistinctSubsets.cpp
@@ -7,7 +7,8 @@ Problem Statement:
Given an integer array nums of unique elements, return all possible
subsets (the power set).
-The solution set must not contain duplicate subsets. Return the solution in any order.
+The solution set must not contain duplicate subsets. Return the solution in any
+order.
*/
// Using Bit Manipulation
@@ -19,44 +20,39 @@ The solution set must not contain duplicate subsets. Return the solution in any
// where 1 means that element is present in the subset
// Time: O(n * 2ⁿ)
// Space: O(1)
-vector> subsets(vector &nums)
-{
- int n = nums.size();
- int total = 1 << n; // 2ⁿ
- vector> ans(total);
-
- // Traverse all subsets
- for (int i = 0; i < total; i++) // 2ⁿ
+vector> subsets(vector &nums) {
+ int n = nums.size();
+ int total = 1 << n; // 2ⁿ
+ vector> ans(total);
+
+ // Traverse all subsets
+ for (int i = 0; i < total; i++) // 2ⁿ
+ {
+ // Traverse elements of nums
+ for (int j = 0; j < n; j++) // n
{
- // Traverse elements of nums
- for (int j = 0; j < n; j++) // n
- {
- // Check if jth bit is set in i
- if ((1 << j) & i)
- {
- ans[i].push_back(nums[j]);
- }
- }
+ // Check if jth bit is set in i
+ if ((1 << j) & i) {
+ ans[i].push_back(nums[j]);
+ }
}
+ }
- return ans;
+ return ans;
}
-int main()
-{
- vector nums = {1, 2, 3};
- vector> ans = subsets(nums);
+int main() {
+ vector nums = {1, 2, 3};
+ vector> ans = subsets(nums);
- cout << "Subsets are: \n";
- for (auto v : ans)
- {
- cout << "[ ";
- for (auto i : v)
- {
- cout << i << " ";
- }
- cout << "]\n";
+ cout << "Subsets are: \n";
+ for (auto v : ans) {
+ cout << "[ ";
+ for (auto i : v) {
+ cout << i << " ";
}
+ cout << "]\n";
+ }
- return 0;
+ return 0;
}
diff --git a/src/cpp/FloydWarshall.cpp b/src/cpp/FloydWarshall.cpp
index 0609d7fa..3a6e53d2 100644
--- a/src/cpp/FloydWarshall.cpp
+++ b/src/cpp/FloydWarshall.cpp
@@ -3,69 +3,65 @@
using namespace std;
// Function to display the matrix
-void showMatrix(const vector> &matrix, int numVertices)
-{
- for (int i = 0; i < numVertices; i++)
- {
- for (int j = 0; j < numVertices; j++)
- {
- if (matrix[i][j] < 10) // For better alignment
- cout << " ";
- cout << matrix[i][j] << " ";
- }
- cout << endl;
+void showMatrix(const vector> &matrix, int numVertices) {
+ for (int i = 0; i < numVertices; i++) {
+ for (int j = 0; j < numVertices; j++) {
+ if (matrix[i][j] < 10) // For better alignment
+ cout << " ";
+ cout << matrix[i][j] << " ";
}
cout << endl;
+ }
+ cout << endl;
}
// Floyd-Warshall algorithm
-void floydWarshall(vector> &matrix, int n)
-{
- for (int k = 0; k < n; k++) // Intermediary vertex
+void floydWarshall(vector> &matrix, int n) {
+ for (int k = 0; k < n; k++) // Intermediary vertex
+ {
+ for (int i = 0; i < n; i++) // Origin vertex
{
- for (int i = 0; i < n; i++) // Origin vertex
+ for (int j = 0; j < n; j++) // Destination vertex
+ {
+ if (matrix[i][k] != LONG_MAX && // i -> k exists
+ matrix[k][j] != LONG_MAX && // k -> j exists
+ matrix[i][j] >
+ matrix[i][k] + matrix[k][j]) // i -> j is shorter via k
{
- for (int j = 0; j < n; j++) // Destination vertex
- {
- if (matrix[i][k] != LONG_MAX && // i -> k exists
- matrix[k][j] != LONG_MAX && // k -> j exists
- matrix[i][j] > matrix[i][k] + matrix[k][j]) // i -> j is shorter via k
- {
- matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j
- }
- }
+ matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j
}
+ }
}
+ }
}
-int main()
-{
- int numVertices = 5;
+int main() {
+ int numVertices = 5;
- // Initialize matrix with given values
- vector> matrix = {
- {0, 2, 10, 5, 7},
- {2, 0, 3, 3, 1},
- {10, 3, 0, 1, 2},
- {5, 3, 1, 0, LONG_MAX},
- {7, 1, 2, 2, 0}};
+ // Initialize matrix with given values
+ vector> matrix = {{0, 2, 10, 5, 7},
+ {2, 0, 3, 3, 1},
+ {10, 3, 0, 1, 2},
+ {5, 3, 1, 0, LONG_MAX},
+ {7, 1, 2, 2, 0}};
- // Display the original matrix
- cout << "Original matrix:" << endl;
- showMatrix(matrix, numVertices);
+ // Display the original matrix
+ cout << "Original matrix:" << endl;
+ showMatrix(matrix, numVertices);
- // Apply Floyd-Warshall algorithm
- floydWarshall(matrix, numVertices);
+ // Apply Floyd-Warshall algorithm
+ floydWarshall(matrix, numVertices);
- // Display the updated matrix
- cout << "Updated matrix:" << endl;
- showMatrix(matrix, numVertices);
+ // Display the updated matrix
+ cout << "Updated matrix:" << endl;
+ showMatrix(matrix, numVertices);
- // Show all shortest paths in 3 columns: source, destination, shortest distance
- cout << "Source\tDestination\tShortest Distance" << endl;
- for (int i = 0; i < numVertices; i++)
- for (int j = 0; j < numVertices; j++)
- cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl;
+ // Show all shortest paths in 3 columns: source, destination, shortest
+ // distance
+ cout << "Source\tDestination\tShortest Distance" << endl;
+ for (int i = 0; i < numVertices; i++)
+ for (int j = 0; j < numVertices; j++)
+ cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/GraphSearch.cpp b/src/cpp/GraphSearch.cpp
index 4f9d9622..aa2aea1c 100644
--- a/src/cpp/GraphSearch.cpp
+++ b/src/cpp/GraphSearch.cpp
@@ -1,135 +1,121 @@
#include
-#include
#include
+#include
#define MAX_VERTICES 6 // Maximum number of vertices in the graph
// Structure that defines each Vertex of the Graph
-struct Vertex
-{
- char id;
- std::vector neighbors; // List of neighbors
- bool visited;
+struct Vertex {
+ char id;
+ std::vector neighbors; // List of neighbors
+ bool visited;
- Vertex(char id) : id(id), visited(false) {}
+ Vertex(char id) : id(id), visited(false) {}
};
// Creates a vertex and returns it
-Vertex *createVertex(char id)
-{
- return new Vertex(id);
-}
+Vertex *createVertex(char id) { return new Vertex(id); }
// Links two vertices (makes them neighbors)
-void linkVertices(Vertex *v1, Vertex *v2)
-{
- v1->neighbors.push_back(v2); // Add v2 as a neighbor of v1
- v2->neighbors.push_back(v1); // Add v1 as a neighbor of v2
+void linkVertices(Vertex *v1, Vertex *v2) {
+ v1->neighbors.push_back(v2); // Add v2 as a neighbor of v1
+ v2->neighbors.push_back(v1); // Add v1 as a neighbor of v2
}
/*
* Depth First Search (DFS)
* Recursively visits neighbors of the starting vertex
*/
-int depthFirstSearch(Vertex *start, Vertex *destination, int steps)
-{
- start->visited = true; // Mark the current vertex as visited
- if (start == destination)
- return steps; // If found, return the distance
-
- for (Vertex *neighbor : start->neighbors)
- { // Visit all neighbors
- if (!neighbor->visited)
- { // If neighbor hasn't been visited
- int result = depthFirstSearch(neighbor, destination, steps + 1);
- if (result != -1)
- return result; // If destination found, return result
- }
+int depthFirstSearch(Vertex *start, Vertex *destination, int steps) {
+ start->visited = true; // Mark the current vertex as visited
+ if (start == destination)
+ return steps; // If found, return the distance
+
+ for (Vertex *neighbor : start->neighbors) { // Visit all neighbors
+ if (!neighbor->visited) { // If neighbor hasn't been visited
+ int result = depthFirstSearch(neighbor, destination, steps + 1);
+ if (result != -1)
+ return result; // If destination found, return result
}
- return -1; // Destination not found
+ }
+ return -1; // Destination not found
}
/*
* Breadth First Search (BFS)
* Uses a queue to traverse level by level
*/
-int breadthFirstSearch(Vertex *start, Vertex *destination)
-{
- std::queue q;
- q.push(start); // Enqueue starting vertex
- start->visited = true;
-
- int steps = 0;
-
- while (!q.empty())
- {
- int qSize = q.size(); // Current queue size (level size)
-
- // Process all vertices at the current level
- for (int i = 0; i < qSize; i++)
- {
- Vertex *current = q.front();
- q.pop();
-
- if (current == destination)
- return steps; // If destination found, return steps
-
- // Enqueue all unvisited neighbors
- for (Vertex *neighbor : current->neighbors)
- {
- if (!neighbor->visited)
- {
- neighbor->visited = true;
- q.push(neighbor);
- }
- }
+int breadthFirstSearch(Vertex *start, Vertex *destination) {
+ std::queue q;
+ q.push(start); // Enqueue starting vertex
+ start->visited = true;
+
+ int steps = 0;
+
+ while (!q.empty()) {
+ int qSize = q.size(); // Current queue size (level size)
+
+ // Process all vertices at the current level
+ for (int i = 0; i < qSize; i++) {
+ Vertex *current = q.front();
+ q.pop();
+
+ if (current == destination)
+ return steps; // If destination found, return steps
+
+ // Enqueue all unvisited neighbors
+ for (Vertex *neighbor : current->neighbors) {
+ if (!neighbor->visited) {
+ neighbor->visited = true;
+ q.push(neighbor);
}
- steps++; // Increment the level
+ }
}
- return -1; // Destination not found
+ steps++; // Increment the level
+ }
+ return -1; // Destination not found
}
-int main()
-{
- // Create vertices
- Vertex *A = createVertex('A');
- Vertex *B = createVertex('B');
- Vertex *C = createVertex('C');
- Vertex *D = createVertex('D');
- Vertex *E = createVertex('E');
- Vertex *F = createVertex('F');
-
- // Link vertices as per the graph structure
- linkVertices(A, B);
- linkVertices(A, C);
- linkVertices(B, D);
- linkVertices(C, D);
- linkVertices(B, E);
- linkVertices(D, E);
- linkVertices(E, F);
- linkVertices(D, F);
-
- // Perform Depth First Search
- int result = depthFirstSearch(A, F, 0);
- if (result != -1)
- std::cout << "DFS - Found. Distance: " << result << std::endl;
- else
- std::cout << "DFS - Not Found." << std::endl;
-
- // Reset visited status for all vertices
- A->visited = false;
- B->visited = false;
- C->visited = false;
- D->visited = false;
- E->visited = false;
- F->visited = false;
-
- // Perform Breadth First Search
- result = breadthFirstSearch(A, F);
- if (result != -1)
- std::cout << "BFS - Found. Distance: " << result << std::endl;
- else
- std::cout << "BFS - Not Found." << std::endl;
-
- return 0;
+int main() {
+ // Create vertices
+ Vertex *A = createVertex('A');
+ Vertex *B = createVertex('B');
+ Vertex *C = createVertex('C');
+ Vertex *D = createVertex('D');
+ Vertex *E = createVertex('E');
+ Vertex *F = createVertex('F');
+
+ // Link vertices as per the graph structure
+ linkVertices(A, B);
+ linkVertices(A, C);
+ linkVertices(B, D);
+ linkVertices(C, D);
+ linkVertices(B, E);
+ linkVertices(D, E);
+ linkVertices(E, F);
+ linkVertices(D, F);
+
+ // Perform Depth First Search
+ int result = depthFirstSearch(A, F, 0);
+ if (result != -1)
+ std::cout << "DFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "DFS - Not Found." << std::endl;
+
+ // Reset visited status for all vertices
+ A->visited = false;
+ B->visited = false;
+ C->visited = false;
+ D->visited = false;
+ E->visited = false;
+ F->visited = false;
+
+ // Perform Breadth First Search
+ result = breadthFirstSearch(A, F);
+ if (result != -1)
+ std::cout << "BFS - Found. Distance: " << result << std::endl;
+ else
+ std::cout << "BFS - Not Found." << std::endl;
+
+ return 0;
}
diff --git a/src/cpp/InsertionSort.cpp b/src/cpp/InsertionSort.cpp
index 566d659c..72a80c1a 100644
--- a/src/cpp/InsertionSort.cpp
+++ b/src/cpp/InsertionSort.cpp
@@ -5,38 +5,32 @@ using namespace std;
void insertionSort(vector &vector) {
- for (uint32_t index = 1; index < vector.size(); index++)
- {
- int key = vector[index];
- int i = index - 1;
-
- while (i >= 0 && vector[i] > key)
- {
- vector[i+1] = vector[i];
- i--;
- }
-
- vector[i+1] = key;
- }
-}
+ for (uint32_t index = 1; index < vector.size(); index++) {
+ int key = vector[index];
+ int i = index - 1;
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
+ while (i >= 0 && vector[i] > key) {
+ vector[i + 1] = vector[i];
+ i--;
}
- cout << "\n";
+
+ vector[i + 1] = key;
+ }
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- insertionSort(vector);
- showVector(vector);
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
+}
+
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ insertionSort(vector);
+ showVector(vector);
}
diff --git a/src/cpp/InterpolationSearch.cpp b/src/cpp/InterpolationSearch.cpp
index ae046db2..3026ffe7 100644
--- a/src/cpp/InterpolationSearch.cpp
+++ b/src/cpp/InterpolationSearch.cpp
@@ -1,65 +1,63 @@
-//Time Complexity: O(log(logn))
+// Time Complexity: O(log(logn))
-#include
-#include
+#include
+#include
using namespace std;
// If x is present in arr[0..n-1], then returns
// index of it, else returns -1.
-long long int interpolation_search(int arr[],int n,int x)
-{
- int low=0,high=n-1;
+long long int interpolation_search(int arr[], int n, int x) {
+ int low = 0, high = n - 1;
- //Beacuse the array is sorted, element has to be present in range
- //made by corner i.e low and high
+ // Beacuse the array is sorted, element has to be present in range
+ // made by corner i.e low and high
- while ((low<=high) and (x>=arr[low]) and (x<=arr[high]))
- {
- // Now we will enquire the position keeping in mind the uniform distribution in mind
- int pos=low+(((double)(high-low)/(arr[high]-arr[low]))*(x-arr[low]));
+ while ((low <= high) and (x >= arr[low]) and (x <= arr[high])) {
+ // Now we will enquire the position keeping in mind the uniform distribution
+ // in mind
+ int pos = low + (((double)(high - low) / (arr[high] - arr[low])) *
+ (x - arr[low]));
- // If x is larger, x is in upper part
- if (arr[pos]x)
- high=pos-1;
+ // If x is smaller, x is in lower part
+ else if (arr[pos] > x)
+ high = pos - 1;
- // Target found
- else
- return pos;
- }
- return -1;
+ // Target found
+ else
+ return pos;
+ }
+ return -1;
}
-int main()
-{
- int n;
- cout<<"Please enter the number of elements in array\n";
- cin>>n;
- int arr[n];
+int main() {
+ int n;
+ cout << "Please enter the number of elements in array\n";
+ cin >> n;
+ int arr[n];
- cout<<"Please enter "<>arr[i];
- }
+ cout << "Please enter " << n << " numbers for arrays\n";
+ for (int i = 0; i < n; i++) {
+ cin >> arr[i];
+ }
- // For Interpolation search we need to sort the array
- sort(arr,arr+n);
+ // For Interpolation search we need to sort the array
+ sort(arr, arr + n);
- cout<<"Enter the number you want to search\n";
- int x;// Target number
- cin>>x;
+ cout << "Enter the number you want to search\n";
+ int x; // Target number
+ cin >> x;
- int index=interpolation_search(arr, n, x);
+ int index = interpolation_search(arr, n, x);
- // If element was found
- if (index != -1)
- cout<<"Element found at index "< &nums, int target) {
- for (size_t i = 0; i < nums.size(); i++) {
-
- if(nums[i] == target)
- return i;
- }
-
- return -1;
+ for (size_t i = 0; i < nums.size(); i++) {
+
+ if (nums[i] == target)
+ return i;
+ }
+
+ return -1;
}
int main() {
- vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999};
- int target;
-
- cout << "Enter the number you would like to search in the vector: ";
- cin >> target;
- cout << "\n";
+ vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999};
+ int target;
+
+ cout << "Enter the number you would like to search in the vector: ";
+ cin >> target;
+ cout << "\n";
- int pos = linear_search(nums, target);
+ int pos = linear_search(nums, target);
- if(pos > -1) {
- cout << "Number found in the vector in the position: " << pos << endl;
- }
- else {
- cout << "Number not found in the vector." << endl;
- }
+ if (pos > -1) {
+ cout << "Number found in the vector in the position: " << pos << endl;
+ } else {
+ cout << "Number not found in the vector." << endl;
+ }
- return 0;
+ return 0;
}
\ No newline at end of file
diff --git a/src/cpp/LinearSearchRecursive.cpp b/src/cpp/LinearSearchRecursive.cpp
index 0d2c9281..6c0cfbce 100644
--- a/src/cpp/LinearSearchRecursive.cpp
+++ b/src/cpp/LinearSearchRecursive.cpp
@@ -6,7 +6,7 @@ int linearSearchRecursive(int arr[], int n, int index, int target) {
if (index >= n) {
return -1;
}
-
+
if (arr[index] == target) {
return index;
}
diff --git a/src/cpp/MaxRecursive.cpp b/src/cpp/MaxRecursive.cpp
index 4a55b915..19bc79f9 100644
--- a/src/cpp/MaxRecursive.cpp
+++ b/src/cpp/MaxRecursive.cpp
@@ -1,37 +1,36 @@
#include
#include
-
int max_recursive(std::vector nums, int n) {
- if(n == 1)
- return nums[0];
- else{
- int aux = max_recursive(nums, n-1);
-
- if(aux > nums[n-1])
- return aux;
-
- return nums[n-1];
- }
+ if (n == 1)
+ return nums[0];
+ else {
+ int aux = max_recursive(nums, n - 1);
+
+ if (aux > nums[n - 1])
+ return aux;
+
+ return nums[n - 1];
+ }
}
int main() {
- std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10};
+ std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10};
+
+ std::cout << "nums = {";
+ for (auto &i : nums) {
- std::cout << "nums = {";
- for(auto& i : nums) {
+ std::cout << i;
- std::cout << i;
-
- if(&i != &nums.back()) {
- std::cout << ",";
- }
+ if (&i != &nums.back()) {
+ std::cout << ",";
}
- std::cout << "}" << std::endl;
+ }
+ std::cout << "}" << std::endl;
- std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl;
+ std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MergeSort.cpp b/src/cpp/MergeSort.cpp
index 17a4c82f..84b0241e 100644
--- a/src/cpp/MergeSort.cpp
+++ b/src/cpp/MergeSort.cpp
@@ -12,55 +12,52 @@
* @param right The right index of the second sub-array
*/
-void merge(std::vector& arr, int left, int mid, int right) {
-
- int n1 = mid - left + 1; // size of the first sub-array.
- int n2 = right - mid; // size of the second sub-array.
-
- // create temporary arrays to hold the data
- std::vector leftSubarray(n1);
- std::vector rightSubarray(n2);
-
- // copy data to temporary arrays leftSubarray[] and rightSubarray[]
- for (int i = 0; i < n1; i++) {
- leftSubarray[i] = arr[left + i];
- }
- for (int j = 0; j < n2; j++) {
- rightSubarray[j] = arr[mid + 1 + j];
- }
-
- // merge the two sub-arrays back into the original array arr[]
- int i = 0, j = 0, k = left;
-
- while (i < n1 && j < n2) {
- if (leftSubarray[i] <= rightSubarray[j]) {
- arr[k] = leftSubarray[i];
- i++;
- }
- else {
- arr[k] = rightSubarray[j];
- j++;
- }
- k++;
- }
-
- // copy the remaining elements of leftSubarray[], if any
- while (i < n1) {
- arr[k] = leftSubarray[i];
- i++;
- k++;
- }
-
- // copy the remaining elements of rightSubarray[], if any
- while (j < n2) {
- arr[k] = rightSubarray[j];
- j++;
- k++;
+void merge(std::vector &arr, int left, int mid, int right) {
+
+ int n1 = mid - left + 1; // size of the first sub-array.
+ int n2 = right - mid; // size of the second sub-array.
+
+ // create temporary arrays to hold the data
+ std::vector leftSubarray(n1);
+ std::vector rightSubarray(n2);
+
+ // copy data to temporary arrays leftSubarray[] and rightSubarray[]
+ for (int i = 0; i < n1; i++) {
+ leftSubarray[i] = arr[left + i];
+ }
+ for (int j = 0; j < n2; j++) {
+ rightSubarray[j] = arr[mid + 1 + j];
+ }
+
+ // merge the two sub-arrays back into the original array arr[]
+ int i = 0, j = 0, k = left;
+
+ while (i < n1 && j < n2) {
+ if (leftSubarray[i] <= rightSubarray[j]) {
+ arr[k] = leftSubarray[i];
+ i++;
+ } else {
+ arr[k] = rightSubarray[j];
+ j++;
}
+ k++;
+ }
+
+ // copy the remaining elements of leftSubarray[], if any
+ while (i < n1) {
+ arr[k] = leftSubarray[i];
+ i++;
+ k++;
+ }
+
+ // copy the remaining elements of rightSubarray[], if any
+ while (j < n2) {
+ arr[k] = rightSubarray[j];
+ j++;
+ k++;
+ }
}
-
-
/**
* Merge Sort algorithm
*
@@ -69,39 +66,39 @@ void merge(std::vector& arr, int left, int mid, int right) {
* @param right The right index of the sub-array to be sorted
*/
-void mergeSort(std::vector& arr, int left, int right) {
- if (left < right) {
+void mergeSort(std::vector &arr, int left, int right) {
+ if (left < right) {
- int mid = left + (right - left) / 2; // calculate the middle index
+ int mid = left + (right - left) / 2; // calculate the middle index
- // sort the first and second halves
- mergeSort(arr, left, mid);
- mergeSort(arr, mid + 1, right);
+ // sort the first and second halves
+ mergeSort(arr, left, mid);
+ mergeSort(arr, mid + 1, right);
- // merge the sorted halves
- merge(arr, left, mid, right);
- }
+ // merge the sorted halves
+ merge(arr, left, mid, right);
+ }
}
int main() {
- std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11};
+ std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11};
- int arrSize = arr.size();
+ int arrSize = arr.size();
- std::cout << "Original array: ";
- for (int num : arr) {
- std::cout << num << " ";
- }
- std::cout << std::endl;
+ std::cout << "Original array: ";
+ for (int num : arr) {
+ std::cout << num << " ";
+ }
+ std::cout << std::endl;
- mergeSort(arr, 0, arrSize - 1);
+ mergeSort(arr, 0, arrSize - 1);
- std::cout << "Sorted array: ";
- for (int num : arr) {
- std::cout << num << " ";
- }
- std::cout << std::endl;
+ std::cout << "Sorted array: ";
+ for (int num : arr) {
+ std::cout << num << " ";
+ }
+ std::cout << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MinMaxDC.cpp b/src/cpp/MinMaxDC.cpp
index 2f4d6d3c..cdffb794 100644
--- a/src/cpp/MinMaxDC.cpp
+++ b/src/cpp/MinMaxDC.cpp
@@ -11,49 +11,50 @@
* @param max Reference to store the maximum element
*/
-void MinAndMax(const std::vector& arr, int left, int right, int& min, int& max) {
-
- // if there is only one element in the subarray, it is both the minimum and maximum
- if (left == right) {
- min = max = arr[left];
- return;
+void MinAndMax(const std::vector &arr, int left, int right, int &min,
+ int &max) {
+
+ // if there is only one element in the subarray, it is both the minimum and
+ // maximum
+ if (left == right) {
+ min = max = arr[left];
+ return;
+ }
+
+ // if there are two elements, compare and set min and max
+ if (right - left == 1) {
+ if (arr[left] < arr[right]) {
+ min = arr[left];
+ max = arr[right];
+ } else {
+ min = arr[right];
+ max = arr[left];
}
+ return;
+ }
- // if there are two elements, compare and set min and max
- if (right - left == 1) {
- if (arr[left] < arr[right]) {
- min = arr[left];
- max = arr[right];
- }
- else {
- min = arr[right];
- max = arr[left];
- }
- return;
- }
-
- // calculate the middle index of the sub-array
- int mid = (left + right) / 2;
- int leftMin, leftMax, rightMin, rightMax;
+ // calculate the middle index of the sub-array
+ int mid = (left + right) / 2;
+ int leftMin, leftMax, rightMin, rightMax;
- // recursively find min and max in the left and right sub-arrays
- MinAndMax(arr, left, mid, leftMin, leftMax);
- MinAndMax(arr, mid + 1, right, rightMin, rightMax);
+ // recursively find min and max in the left and right sub-arrays
+ MinAndMax(arr, left, mid, leftMin, leftMax);
+ MinAndMax(arr, mid + 1, right, rightMin, rightMax);
- // update the minimum and maximum values
- min = std::min(leftMin, rightMin);
- max = std::max(leftMax, rightMax);
+ // update the minimum and maximum values
+ min = std::min(leftMin, rightMin);
+ max = std::max(leftMax, rightMax);
}
int main() {
- std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24};
- int min, max;
+ std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24};
+ int min, max;
- MinAndMax(arr, 0, arr.size() - 1, min, max);
+ MinAndMax(arr, 0, arr.size() - 1, min, max);
- std::cout << "Minimum element: " << min << std::endl;
- std::cout << "Maximum element: " << max << std::endl;
+ std::cout << "Minimum element: " << min << std::endl;
+ std::cout << "Maximum element: " << max << std::endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/MinMaxIterative.cpp b/src/cpp/MinMaxIterative.cpp
index 65d0e5d0..ea48d7ca 100644
--- a/src/cpp/MinMaxIterative.cpp
+++ b/src/cpp/MinMaxIterative.cpp
@@ -4,17 +4,19 @@ using namespace std;
int main() {
- int arr[] = {1, 5, -20, 6, 15};
+ int arr[] = {1, 5, -20, 6, 15};
- int min = arr[0];
- int max = arr[0];
+ int min = arr[0];
+ int max = arr[0];
- for(auto& i : arr) {
- if(i < min) min = i;
- else if(i > max) max = i;
- }
+ for (auto &i : arr) {
+ if (i < min)
+ min = i;
+ else if (i > max)
+ max = i;
+ }
- cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl;
+ cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl;
- return 0;
+ return 0;
}
diff --git a/src/cpp/Palindrome.cpp b/src/cpp/Palindrome.cpp
index 7dafc0b6..c8dd36c6 100644
--- a/src/cpp/Palindrome.cpp
+++ b/src/cpp/Palindrome.cpp
@@ -1,7 +1,9 @@
/*
isPalindrome Algorithm in C++
-A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
+A phrase is a palindrome if, after converting all uppercase letters into
+lowercase letters and removing all non-alphanumeric characters, it reads the
+same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
*/
@@ -12,43 +14,42 @@ Given a string s, return true if it is a palindrome, or false otherwise.
using namespace std;
bool isPalindrome(string s) {
- // Step 1: Convert all characters to lowercase
- for (char& c : s) {
- c = std::tolower(c);
+ // Step 1: Convert all characters to lowercase
+ for (char &c : s) {
+ c = std::tolower(c);
+ }
+
+ // Step 2: Remove non-alphanumeric characters
+ std::string alphanumericStr;
+ for (char c : s) {
+ if (std::isalnum(c)) {
+ alphanumericStr.push_back(c);
}
+ }
- // Step 2: Remove non-alphanumeric characters
- std::string alphanumericStr;
- for (char c : s) {
- if (std::isalnum(c)) {
- alphanumericStr.push_back(c);
- }
- }
-
- // Step 3: Check if the resulting string is a palindrome
- int left = 0;
- int right = alphanumericStr.length() - 1;
+ // Step 3: Check if the resulting string is a palindrome
+ int left = 0;
+ int right = alphanumericStr.length() - 1;
- while (left < right) {
- if (alphanumericStr[left] != alphanumericStr[right]) {
- return false;
- }
- left++;
- right--;
+ while (left < right) {
+ if (alphanumericStr[left] != alphanumericStr[right]) {
+ return false;
}
- return true;
+ left++;
+ right--;
+ }
+ return true;
}
int main() {
- std::string input;
- std::cout << "Enter a string: ";
- std::getline (std::cin, input);
-
- if (isPalindrome(input)) {
- std::cout << "The string is a palindrome." << std::endl;
- }
- else {
- std::cout << "The string is not a palindrome." << std::endl;
- }
- return 0;
+ std::string input;
+ std::cout << "Enter a string: ";
+ std::getline(std::cin, input);
+
+ if (isPalindrome(input)) {
+ std::cout << "The string is a palindrome." << std::endl;
+ } else {
+ std::cout << "The string is not a palindrome." << std::endl;
+ }
+ return 0;
}
diff --git a/src/cpp/QuickSort.cpp b/src/cpp/QuickSort.cpp
index 75daf1a0..ee9d726b 100644
--- a/src/cpp/QuickSort.cpp
+++ b/src/cpp/QuickSort.cpp
@@ -3,63 +3,50 @@
using namespace std;
-int partition(vector &vector, int start, int end)
-{
- int pivot = vector[end];
- int index = start;
-
- for (int i = start; i < end; i++)
- {
- if (vector[i] < pivot)
- {
- int temp = vector[i];
- vector[i] = vector[index];
- vector[index] = temp;
- index++;
- }
+int partition(vector &vector, int start, int end) {
+ int pivot = vector[end];
+ int index = start;
+
+ for (int i = start; i < end; i++) {
+ if (vector[i] < pivot) {
+ int temp = vector[i];
+ vector[i] = vector[index];
+ vector[index] = temp;
+ index++;
}
+ }
- if (pivot <= vector[index])
- {
- vector[end] = vector[index];
- vector[index] = pivot;
- }
+ if (pivot <= vector[index]) {
+ vector[end] = vector[index];
+ vector[index] = pivot;
+ }
- return index;
+ return index;
}
-void quickSort(vector &vector, int start, int end)
-{
- if (start < end)
- {
- int pivot = partition(vector, start, end);
- quickSort(vector, start, pivot-1);
- quickSort(vector, pivot+1, end);
- }
+void quickSort(vector &vector, int start, int end) {
+ if (start < end) {
+ int pivot = partition(vector, start, end);
+ quickSort(vector, start, pivot - 1);
+ quickSort(vector, pivot + 1, end);
+ }
}
-void quickSort(vector &vector)
-{
- quickSort(vector, 0, vector.size()-1);
-}
+void quickSort(vector &vector) { quickSort(vector, 0, vector.size() - 1); }
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
- }
- cout << "\n";
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- quickSort(vector);
- showVector(vector);
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ quickSort(vector);
+ showVector(vector);
}
diff --git a/src/cpp/RottenOranges.cpp b/src/cpp/RottenOranges.cpp
index 4c639476..0ce17c90 100644
--- a/src/cpp/RottenOranges.cpp
+++ b/src/cpp/RottenOranges.cpp
@@ -19,85 +19,74 @@ If it's not possible, return -1.
// Approach: BFS
-bool isValid(int nx, int ny, int m, int n)
-{
- return (0 <= nx && nx < m) &&
- (0 <= ny && ny < n);
+bool isValid(int nx, int ny, int m, int n) {
+ return (0 <= nx && nx < m) && (0 <= ny && ny < n);
}
// Time: O(mn) x 4
// Space: O(mn)
-int orangesRotting(vector> &grid)
-{
- int m = grid.size();
- int n = grid[0].size();
+int orangesRotting(vector> &grid) {
+ int m = grid.size();
+ int n = grid[0].size();
+
+ int total = 0; // fresh + rotten oranges
+ int count = 0; // rotten oranges
+ int mins = 0; // minutes elapsed
+
+ queue> rotten; // {i, j}: position of rotten orange
+
+ // Count the fresh & rotten oranges, push rotten oranges into queue
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (grid[i][j] != 0) // Rotten or Fresh orange
+ total++;
+ if (grid[i][j] == 2) // Rotten
+ rotten.push({i, j}); // Push position of rotten orange
+ }
+ }
- int total = 0; // fresh + rotten oranges
- int count = 0; // rotten oranges
- int mins = 0; // minutes elapsed
+ int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis)
+ int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis)
- queue> rotten; // {i, j}: position of rotten orange
+ while (!rotten.empty()) {
+ int size = rotten.size(); // rotten oranges in current minute
+ count += size; // add to total rotten oranges
- // Count the fresh & rotten oranges, push rotten oranges into queue
- for (int i = 0; i < m; i++)
+ while (size--) // Each rotten orange in current minute
{
- for (int j = 0; j < n; j++)
- {
- if (grid[i][j] != 0) // Rotten or Fresh orange
- total++;
- if (grid[i][j] == 2) // Rotten
- rotten.push({i, j}); // Push position of rotten orange
+ // Pop the front rotten orange
+ int x = rotten.front().first;
+ int y = rotten.front().second;
+ rotten.pop();
+
+ // Check for fresh oranges in 4-directions
+ for (int i = 0; i < 4; i++) {
+ // New coordinates
+ int nx = x + dx[i];
+ int ny = y + dy[i];
+
+ // Valid, fresh orange
+ if (isValid(nx, ny, m, n) && grid[nx][ny] == 1) {
+ grid[nx][ny] = 2; // make it rotten
+ rotten.push({nx, ny}); // push it into queue
}
+ }
}
- int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis)
- int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis)
-
- while (!rotten.empty())
- {
- int size = rotten.size(); // rotten oranges in current minute
- count += size; // add to total rotten oranges
-
- while (size--) // Each rotten orange in current minute
- {
- // Pop the front rotten orange
- int x = rotten.front().first;
- int y = rotten.front().second;
- rotten.pop();
-
- // Check for fresh oranges in 4-directions
- for (int i = 0; i < 4; i++)
- {
- // New coordinates
- int nx = x + dx[i];
- int ny = y + dy[i];
-
- // Valid, fresh orange
- if (isValid(nx, ny, m, n) && grid[nx][ny] == 1)
- {
- grid[nx][ny] = 2; // make it rotten
- rotten.push({nx, ny}); // push it into queue
- }
- }
- }
-
- if (!rotten.empty()) // if there are more rotten oranges
- mins++;
- }
+ if (!rotten.empty()) // if there are more rotten oranges
+ mins++;
+ }
- if (total != count) // fresh oranges left
- return -1;
+ if (total != count) // fresh oranges left
+ return -1;
- return mins;
+ return mins;
}
-int main()
-{
- vector> grid = {{2, 1, 1},
- {1, 1, 0},
- {0, 1, 1}};
+int main() {
+ vector> grid = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
- cout << orangesRotting(grid) << endl; // 4
+ cout << orangesRotting(grid) << endl; // 4
- return 0;
+ return 0;
}
diff --git a/src/cpp/SelectionSort.cpp b/src/cpp/SelectionSort.cpp
index a84b33f4..abffa69c 100644
--- a/src/cpp/SelectionSort.cpp
+++ b/src/cpp/SelectionSort.cpp
@@ -3,46 +3,38 @@
using namespace std;
-void selectionSort(vector &vector)
-{
- for (uint32_t index = 0; index < vector.size()-1; index++)
- {
- uint32_t min = index;
-
- for (uint32_t tempIndex = index+1; tempIndex < vector.size(); ++tempIndex)
- {
- if( vector[tempIndex] < vector[min] )
- {
- min = tempIndex;
- }
- }
-
- if( min != index )
- {
- int temp = vector[index];
- vector[index] = vector[min];
- vector[min] = temp;
- }
+void selectionSort(vector &vector) {
+ for (uint32_t index = 0; index < vector.size() - 1; index++) {
+ uint32_t min = index;
+
+ for (uint32_t tempIndex = index + 1; tempIndex < vector.size();
+ ++tempIndex) {
+ if (vector[tempIndex] < vector[min]) {
+ min = tempIndex;
+ }
}
-}
-void showVector(vector vector)
-{
- for (uint32_t i = 0; i < vector.size(); ++i)
- {
- cout << vector[i] << ", ";
+ if (min != index) {
+ int temp = vector[index];
+ vector[index] = vector[min];
+ vector[min] = temp;
}
- cout << "\n";
+ }
}
-int main()
-{
- vector vector;
- for (uint32_t i = 0; i < 10; ++i)
- {
- vector.push_back(rand() % 100);
- }
- showVector(vector);
- selectionSort(vector);
- showVector(vector);
+void showVector(vector vector) {
+ for (uint32_t i = 0; i < vector.size(); ++i) {
+ cout << vector[i] << ", ";
+ }
+ cout << "\n";
+}
+
+int main() {
+ vector vector;
+ for (uint32_t i = 0; i < 10; ++i) {
+ vector.push_back(rand() % 100);
+ }
+ showVector(vector);
+ selectionSort(vector);
+ showVector(vector);
}
\ No newline at end of file
diff --git a/src/cpp/SinglyLinkedList.cpp b/src/cpp/SinglyLinkedList.cpp
index 3b35c20f..ac5fbc0b 100644
--- a/src/cpp/SinglyLinkedList.cpp
+++ b/src/cpp/SinglyLinkedList.cpp
@@ -2,172 +2,173 @@
using namespace std;
-struct Node{
+struct Node {
- int val;
- Node* next;
+ int val;
+ Node *next;
- Node(int val) : val(val), next(nullptr) {}
- Node(int val, Node *next) : val(val), next(next) {}
+ Node(int val) : val(val), next(nullptr) {}
+ Node(int val, Node *next) : val(val), next(next) {}
};
void print_list(Node *head) {
- auto aux = head;
+ auto aux = head;
- cout << '[';
- while(aux) {
+ cout << '[';
+ while (aux) {
- cout << aux->val;
+ cout << aux->val;
- if(aux->next) {
- cout << ", ";
- }
-
- aux = aux->next;
+ if (aux->next) {
+ cout << ", ";
}
- cout << ']' << endl;
+
+ aux = aux->next;
+ }
+ cout << ']' << endl;
}
void push_back(Node **head, int val) {
+ Node *newNode = new Node(val);
- Node *newNode = new Node(val);
-
- if(*head == nullptr) {
- *head = newNode;
- }
-
- else {
+ if (*head == nullptr) {
+ *head = newNode;
+ }
- auto aux = *head;
+ else {
- while(aux->next) {
- aux = aux->next;
- }
+ auto aux = *head;
- aux->next = newNode;
+ while (aux->next) {
+ aux = aux->next;
}
+
+ aux->next = newNode;
+ }
}
void push_front(Node **head, int val) {
- Node *newNode = new Node(val, *head);
+ Node *newNode = new Node(val, *head);
- *head = newNode;
+ *head = newNode;
}
void insert_in_position(Node **head, int val, int pos) {
- if(pos == 0) {
- push_front(head, val);
- return;
- }
+ if (pos == 0) {
+ push_front(head, val);
+ return;
+ }
- Node* newNode = new Node(val);
+ Node *newNode = new Node(val);
- auto prev = *head;
- auto curr = *head;
+ auto prev = *head;
+ auto curr = *head;
- while(curr->next && pos) {
- prev = curr;
- curr = curr->next;
- pos--;
- }
+ while (curr->next && pos) {
+ prev = curr;
+ curr = curr->next;
+ pos--;
+ }
- prev->next = newNode;
- newNode->next = curr;
+ prev->next = newNode;
+ newNode->next = curr;
}
void pop_back(Node **head) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- auto prev = *head;
- auto curr = prev->next;
+ auto prev = *head;
+ auto curr = prev->next;
- while(curr->next) {
- prev = prev->next;
- curr = curr->next;
- }
+ while (curr->next) {
+ prev = prev->next;
+ curr = curr->next;
+ }
- prev->next = nullptr;
+ prev->next = nullptr;
- delete(curr);
+ delete (curr);
}
void pop_front(Node **head) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- auto aux = *head;
+ auto aux = *head;
- *head = aux->next;
+ *head = aux->next;
- delete(aux);
+ delete (aux);
}
void remove_from_position(Node **head, int pos) {
- if(*head == nullptr) {
- return;
- }
+ if (*head == nullptr) {
+ return;
+ }
- if(pos == 0) {
- pop_front(head);
- return;
- }
+ if (pos == 0) {
+ pop_front(head);
+ return;
+ }
- auto prev = *head;
- auto curr = *head;
+ auto prev = *head;
+ auto curr = *head;
- while(curr->next && pos) {
- prev = curr;
- curr = curr->next;
- pos--;
- }
+ while (curr->next && pos) {
+ prev = curr;
+ curr = curr->next;
+ pos--;
+ }
- if(pos == 0) {
- prev->next = curr->next;
- delete(curr);
- }
+ if (pos == 0) {
+ prev->next = curr->next;
+ delete (curr);
+ }
}
int main() {
- Node *head = nullptr;
-
- cout << "Inserting the elements at the end [1, 2, 3]:" << endl;
- push_back(&head, 1);
- push_back(&head, 2);
- push_back(&head, 3);
- print_list(head);
-
- cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl;
- push_front(&head, 0);
- push_front(&head, -1);
- push_front(&head, -2);
- print_list(head);
-
- cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] respectively:" << endl;
- insert_in_position(&head, 997, 3);
- insert_in_position(&head, 998, 4);
- insert_in_position(&head, 999, 5);
- print_list(head);
-
- cout << "Removing last element:" << endl;
- pop_back(&head);
- print_list(head);
-
- cout << "Removing first element:" << endl;
- pop_front(&head);
- print_list(head);
-
- cout << "Removing element in position 2:" << endl;
- remove_from_position(&head, 2);
- print_list(head);
+ Node *head = nullptr;
+
+ cout << "Inserting the elements at the end [1, 2, 3]:" << endl;
+ push_back(&head, 1);
+ push_back(&head, 2);
+ push_back(&head, 3);
+ print_list(head);
+
+ cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl;
+ push_front(&head, 0);
+ push_front(&head, -1);
+ push_front(&head, -2);
+ print_list(head);
+
+ cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] "
+ "respectively:"
+ << endl;
+ insert_in_position(&head, 997, 3);
+ insert_in_position(&head, 998, 4);
+ insert_in_position(&head, 999, 5);
+ print_list(head);
+
+ cout << "Removing last element:" << endl;
+ pop_back(&head);
+ print_list(head);
+
+ cout << "Removing first element:" << endl;
+ pop_front(&head);
+ print_list(head);
+
+ cout << "Removing element in position 2:" << endl;
+ remove_from_position(&head, 2);
+ print_list(head);
}
diff --git a/src/cpp/Stack.cpp b/src/cpp/Stack.cpp
index c123b497..a22ed118 100644
--- a/src/cpp/Stack.cpp
+++ b/src/cpp/Stack.cpp
@@ -6,64 +6,64 @@
// Stack: Last In - First Out (LIFO)
class Stack {
- private:
- int array[MAX];
- int index = 0;
-
- public:
- Stack(){}
+private:
+ int array[MAX];
+ int index = 0;
- void push(int element) {
- if (this->index >= MAX) {
- throw std::logic_error("Stack is full!");
- }
- this->array[index] = element;
- index++;
+public:
+ Stack() {}
+
+ void push(int element) {
+ if (this->index >= MAX) {
+ throw std::logic_error("Stack is full!");
}
+ this->array[index] = element;
+ index++;
+ }
- bool isEmpty() {
- if (!this->index) {
- return true;
- }
- return false;
+ bool isEmpty() {
+ if (!this->index) {
+ return true;
}
+ return false;
+ }
- int pop() {
- if (this->isEmpty()) {
- throw std::logic_error("Stack is empty!");
- }
- index--;
- int value = this->array[this->index];
- this->array[this->index] = 0;
- return value;
+ int pop() {
+ if (this->isEmpty()) {
+ throw std::logic_error("Stack is empty!");
}
+ index--;
+ int value = this->array[this->index];
+ this->array[this->index] = 0;
+ return value;
+ }
- void print() {
- std::cout << "[ ";
- for (int i = 0; i < this->index; i++) {
- std::cout << this->array[i] << " ";
- }
- std::cout << "]" << std::endl;
+ void print() {
+ std::cout << "[ ";
+ for (int i = 0; i < this->index; i++) {
+ std::cout << this->array[i] << " ";
}
+ std::cout << "]" << std::endl;
+ }
};
int main() {
- // Create a pointier to a new Stack instance
- Stack* stack = new Stack();
+ // Create a pointier to a new Stack instance
+ Stack *stack = new Stack();
- std::cout << "Push(1, 2, 4)" << std::endl;
- stack->push(1);
- stack->push(2);
- stack->push(4);
- stack->print();
+ std::cout << "Push(1, 2, 4)" << std::endl;
+ stack->push(1);
+ stack->push(2);
+ stack->push(4);
+ stack->print();
- std::cout << "Pop()" << std::endl;
- stack->pop();
- stack->print();
+ std::cout << "Pop()" << std::endl;
+ stack->pop();
+ stack->print();
- stack->pop();
- stack->pop();
+ stack->pop();
+ stack->pop();
- std::cout << "Empty Stack" << std::endl;
- stack->print();
+ std::cout << "Empty Stack" << std::endl;
+ stack->print();
}
diff --git a/src/cpp/TowerOfHanoi.cpp b/src/cpp/TowerOfHanoi.cpp
index 34f71fbe..d44e0bd0 100644
--- a/src/cpp/TowerOfHanoi.cpp
+++ b/src/cpp/TowerOfHanoi.cpp
@@ -2,67 +2,67 @@
Recursive Towers of Hanoi Solution
Problem Description: (from wikipedia)
- The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters,
- which can slide onto any rod.
+ The Tower of Hanoi is a mathematical game or puzzle consisting of three rods
+ and a number of disks of various diameters, which can slide onto any rod.
- The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top,
- thus approximating a conical shape.
+ The puzzle begins with the disks stacked on one rod in order of decreasing
+ size, the smallest at the top, thus approximating a conical shape.
- The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:
+ The objective of the puzzle is to move the entire stack to the last rod,
+ obeying the following rules:
Only one disk may be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
+ Each move consists of taking the upper disk from one of the stacks and
+ placing it on top of another stack or on an empty rod.
No disk may be placed on top of a disk that is smaller than it.
With 3 disks, the puzzle can be solved in 7 moves.
- The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks.
+ The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n
+ − 1, where n is the number of disks.
*/
#include
using std::cout;
-size_t solve_tower(int n, char first, char second, char third)
-{
+size_t solve_tower(int n, char first, char second, char third) {
- // recursive base case
- if (n == 1)
- {
- cout << "Move disk 1 from " << first << " to " << third << "\n";
- return 1;
- }
+ // recursive base case
+ if (n == 1) {
+ cout << "Move disk 1 from " << first << " to " << third << "\n";
+ return 1;
+ }
- // move n-1 disks from first to other using second as a placeholder
- size_t num_moves = solve_tower(n - 1, first, third, second);
+ // move n-1 disks from first to other using second as a placeholder
+ size_t num_moves = solve_tower(n - 1, first, third, second);
- // move the nth disk from first to second
- cout << "Move disk " << n << " from " << first << " to " << third << "\n";
+ // move the nth disk from first to second
+ cout << "Move disk " << n << " from " << first << " to " << third << "\n";
- // move the n-1 disks from third to second using first as an placeholder
- num_moves += solve_tower(n - 1, second, first, third);
+ // move the n-1 disks from third to second using first as an placeholder
+ num_moves += solve_tower(n - 1, second, first, third);
- // return the total moves plus 1
- return num_moves + 1;
+ // return the total moves plus 1
+ return num_moves + 1;
}
-int main()
-{
+int main() {
- // names of rods
- char a = 'A';
- char b = 'B';
- char c = 'C';
+ // names of rods
+ char a = 'A';
+ char b = 'B';
+ char c = 'C';
- // number of disks to move in puzzle
- size_t num_disk = 3;
+ // number of disks to move in puzzle
+ size_t num_disk = 3;
- // find the total number of moves needed to solve
- size_t num_moves = solve_tower(num_disk, a, b, c);
+ // find the total number of moves needed to solve
+ size_t num_moves = solve_tower(num_disk, a, b, c);
- // output result
- cout << "Total moves needed to solve: " << num_moves;
- return 0;
+ // output result
+ cout << "Total moves needed to solve: " << num_moves;
+ return 0;
}
From bffd390eaaa3d1d832675dd621cdbcbe825769e4 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 10:01:53 -0300
Subject: [PATCH 27/58] Format markdown files
---
.github/pull_request_template.md | 2 ++
CODE_OF_CONDUCT.md | 24 ++++++++++--------------
2 files changed, 12 insertions(+), 14 deletions(-)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 41b20b84..aa427f83 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,4 +1,5 @@
Before opening a Pull Request, please read the following items:
+
1. Make sure you have read the [CONTRIBUTING](../CONTRIBUTING.md) guidelines
2. Make sure no other PR is implementing the same change
3. Make sure the Continuous Integration workflows (Github Actions) are all passing
@@ -7,4 +8,5 @@ Before opening a Pull Request, please read the following items:
# Description
+
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index da32d376..224c0402 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,4 +1,3 @@
-
# Code of Conduct
## Our Pledge
@@ -18,23 +17,23 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our
community include:
-* Demonstrating empathy and kindness toward other people
-* Being respectful of differing opinions, viewpoints, and experiences
-* Giving and gracefully accepting constructive feedback
-* Accepting responsibility and apologizing to those affected by our mistakes,
+- Demonstrating empathy and kindness toward other people
+- Being respectful of differing opinions, viewpoints, and experiences
+- Giving and gracefully accepting constructive feedback
+- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
-* Focusing on what is best not just for us as individuals, but for the overall
+- Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
-* The use of sexualized language or imagery, and sexual attention or advances of
+- The use of sexualized language or imagery, and sexual attention or advances of
any kind
-* Trolling, insulting or derogatory comments, and personal or political attacks
-* Public or private harassment
-* Publishing others' private information, such as a physical or email address,
+- Trolling, insulting or derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or email address,
without their explicit permission
-* Other conduct which could reasonably be considered inappropriate in a
+- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
@@ -74,6 +73,3 @@ version 2.1, available at
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
-[Mozilla CoC]: https://github.com/mozilla/diversity
-[FAQ]: https://www.contributor-covenant.org/faq
-[translations]: https://www.contributor-covenant.org/translations
From e756157ca58b7f24d7166e5888475de34f69941c Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 10:02:05 -0300
Subject: [PATCH 28/58] Format C file with CLANG_FORMAT
---
src/c/GraphSearch.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/c/GraphSearch.c b/src/c/GraphSearch.c
index e6643f29..7679dce2 100644
--- a/src/c/GraphSearch.c
+++ b/src/c/GraphSearch.c
@@ -109,7 +109,7 @@ int buscaEmLargura(VERTICE inicio, VERTICE destino) {
int tamFila = 1; // Variável que controla o tamanho da fila
VERTICE
- FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
+ FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados
for (int i = 0; i < MAX_VERTICES;
i++) { // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro
FILA[i] = NULL;
From 9bba015e4e3e18e1f2900144cf6812dfeedd3543 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 10:02:12 -0300
Subject: [PATCH 29/58] Format Python files
---
src/python/dynamic_stack.py | 2 +-
src/python/fibonacci_iterative.py | 1 -
src/python/lz77.py | 1 -
3 files changed, 1 insertion(+), 3 deletions(-)
diff --git a/src/python/dynamic_stack.py b/src/python/dynamic_stack.py
index e6743984..129b73a8 100644
--- a/src/python/dynamic_stack.py
+++ b/src/python/dynamic_stack.py
@@ -41,7 +41,7 @@ def show(self) -> None:
def main() -> None:
dynamic_stack = DynamicStack()
- print(f"Push(1,2,4):")
+ print("Push(1,2,4):")
dynamic_stack.push(1)
dynamic_stack.push(2)
dynamic_stack.push(4)
diff --git a/src/python/fibonacci_iterative.py b/src/python/fibonacci_iterative.py
index f394c049..a7ad7dc9 100755
--- a/src/python/fibonacci_iterative.py
+++ b/src/python/fibonacci_iterative.py
@@ -5,7 +5,6 @@
execution of algorithms in seconds
"""
-import functools
import time
diff --git a/src/python/lz77.py b/src/python/lz77.py
index 249444f4..fba93b12 100644
--- a/src/python/lz77.py
+++ b/src/python/lz77.py
@@ -1,4 +1,3 @@
-import io
import sys
From acb5a102a567e86463c8abe4a6d0419b22b4e112 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 11:42:17 -0300
Subject: [PATCH 30/58] Add new validations to lint-checker
---
.github/workflows/lint-checker.yml | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 817c08f3..9f81c630 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,13 +14,16 @@ jobs:
uses: github/super-linter@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- VALIDATE_SCALAFMT: true
VALIDATE_GO: true
+ VALIDATE_RUBY: true
+ VALIDATE_KOTLIN: true
+ VALIDATE_MARKDOWN: true
+ VALIDATE_SCALAFMT: true
VALIDATE_RUST_2021: true
VALIDATE_RUST_CLIPPY: true
- VALIDATE_KOTLIN: true
- VALIDATE_RUBY: true
- VALIDATE_JAVASCRIPT_ES: true
- VALIDATE_GOOGLE_JAVA_FORMAT: true
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
+ VALIDATE_CLANG_FORMAT: true
+ VALIDATE_JAVASCRIPT_ES: true
+ VALIDATE_MARKDOWN_PRETTIER: true
+ VALIDATE_GOOGLE_JAVA_FORMAT: true
From be83817aaea06dd13a819bc641a7b4c2a2a16a79 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 11:50:56 -0300
Subject: [PATCH 31/58] Try to fix markdown issue
---
.github/pull_request_template.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index aa427f83..ac0cdccb 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,3 +1,5 @@
+# Instructions
+
Before opening a Pull Request, please read the following items:
1. Make sure you have read the [CONTRIBUTING](../CONTRIBUTING.md) guidelines
From 745a034030feb994bd2b2ad0801b8691a47c0f07 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 11:54:57 -0300
Subject: [PATCH 32/58] Change lint-checker validations
---
.github/workflows/lint-checker.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 9f81c630..9f6fa3dc 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -15,6 +15,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VALIDATE_GO: true
+ VALIDATE_CPP: true
VALIDATE_RUBY: true
VALIDATE_KOTLIN: true
VALIDATE_MARKDOWN: true
@@ -23,7 +24,6 @@ jobs:
VALIDATE_RUST_CLIPPY: true
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
- VALIDATE_CLANG_FORMAT: true
VALIDATE_JAVASCRIPT_ES: true
VALIDATE_MARKDOWN_PRETTIER: true
VALIDATE_GOOGLE_JAVA_FORMAT: true
From 053b68b2ffdd7e25554b65093853fe99fcaa98b7 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 12:02:51 -0300
Subject: [PATCH 33/58] Try to fix markdown issue
---
.github/pull_request_template.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index ac0cdccb..6f222a44 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -9,6 +9,6 @@ Before opening a Pull Request, please read the following items:
-# Description
+## Description
From 8ee2cc1a85faa2f3059a197007bdc49c5eb1d42c Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 12:03:13 -0300
Subject: [PATCH 34/58] Remove VALIDATE_CPP
---
.github/workflows/lint-checker.yml | 1 -
1 file changed, 1 deletion(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 9f6fa3dc..aedb02a6 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -15,7 +15,6 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VALIDATE_GO: true
- VALIDATE_CPP: true
VALIDATE_RUBY: true
VALIDATE_KOTLIN: true
VALIDATE_MARKDOWN: true
From ea3aa364def667030dd5268319e904f6d9cc62b8 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 16:32:39 -0300
Subject: [PATCH 35/58] Add VALIDATE_PYTHON_RUFF
---
.github/workflows/lint-checker.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index aedb02a6..052a19e5 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -21,6 +21,7 @@ jobs:
VALIDATE_SCALAFMT: true
VALIDATE_RUST_2021: true
VALIDATE_RUST_CLIPPY: true
+ VALIDATE_PYTHON_RUFF: true
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
VALIDATE_JAVASCRIPT_ES: true
From 0bcc8cffa68710266f5cc0acb3e3fcbf2896bf34 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 16:36:27 -0300
Subject: [PATCH 36/58] Bump super-linter to v7.1.0
---
.github/workflows/lint-checker.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index aedb02a6..8996b8ea 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -11,7 +11,7 @@ jobs:
with:
fetch-depth: 0
- name: Check Code
- uses: github/super-linter@v5
+ uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VALIDATE_GO: true
From 69e161f4280d4c7d0e5df9e7e103d4fb8f59aef8 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 16:41:31 -0300
Subject: [PATCH 37/58] Fix linear_search_recursive.py
---
src/python/linear_search_recursive.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/python/linear_search_recursive.py b/src/python/linear_search_recursive.py
index f164b299..01efd74b 100644
--- a/src/python/linear_search_recursive.py
+++ b/src/python/linear_search_recursive.py
@@ -1,4 +1,3 @@
-""" Implementaçao do algoritmo de busca sequencial com recursão """
"""Implementation of the sequential search algorithm with recursion."""
From e674cb1b655449ed58c33baaf818bce1422dfa28 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 16:46:12 -0300
Subject: [PATCH 38/58] Create .markdown-lint.yml
---
.markdown-lint.yml | 1 +
1 file changed, 1 insertion(+)
create mode 100644 .markdown-lint.yml
diff --git a/.markdown-lint.yml b/.markdown-lint.yml
new file mode 100644
index 00000000..0cf1ceb1
--- /dev/null
+++ b/.markdown-lint.yml
@@ -0,0 +1 @@
+MD045: false
From e5ced45283c06f111d6a4f5241d329e6172468e9 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Wed, 23 Oct 2024 16:51:47 -0300
Subject: [PATCH 39/58] Try to fix markdown-lint
---
.github/workflows/lint-checker.yml | 1 +
.markdown-lint.yml | 1 -
.markdownlint.json | 3 +++
3 files changed, 4 insertions(+), 1 deletion(-)
delete mode 100644 .markdown-lint.yml
create mode 100644 .markdownlint.json
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 8996b8ea..b5f97c56 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,6 +14,7 @@ jobs:
uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ MARKDOWN_CONFIG_FILE: ".markdownlint.json"
VALIDATE_GO: true
VALIDATE_RUBY: true
VALIDATE_KOTLIN: true
diff --git a/.markdown-lint.yml b/.markdown-lint.yml
deleted file mode 100644
index 0cf1ceb1..00000000
--- a/.markdown-lint.yml
+++ /dev/null
@@ -1 +0,0 @@
-MD045: false
diff --git a/.markdownlint.json b/.markdownlint.json
new file mode 100644
index 00000000..ea3a2bef
--- /dev/null
+++ b/.markdownlint.json
@@ -0,0 +1,3 @@
+{
+ "MD045": false
+}
From ef6dd337bee7ff27edd6fd0dfbe738016d844519 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Thu, 24 Oct 2024 17:39:45 -0300
Subject: [PATCH 40/58] Create Palindrome.scala
---
README.md | 4 ++--
src/scala/Palindrome.scala | 15 +++++++++++++++
2 files changed, 17 insertions(+), 2 deletions(-)
create mode 100644 src/scala/Palindrome.scala
diff --git a/README.md b/README.md
index 976fb00e..15fbb6ec 100644
--- a/README.md
+++ b/README.md
@@ -4468,8 +4468,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/scala/Palindrome.scala b/src/scala/Palindrome.scala
new file mode 100644
index 00000000..b8b80bb3
--- /dev/null
+++ b/src/scala/Palindrome.scala
@@ -0,0 +1,15 @@
+def isPalindrome(content: String): Boolean = {
+ val sanitizedContent: String = content.replaceAll("\\W", "").toLowerCase
+ sanitizedContent == sanitizedContent.reverse
+}
+
+object Main extends App {
+ val data: Seq[String] = Seq(
+ "",
+ "a",
+ "abba",
+ "No lemon, no melon",
+ "Was it a palindrome?"
+ )
+ data.foreach(x => println(s"'$x' is a palindrome? ${isPalindrome(x)}"))
+}
From 6ea295ae50c53d98a9b799d7c28aeffcdffccb84 Mon Sep 17 00:00:00 2001
From: Paul Sasieta Arana
Date: Fri, 25 Oct 2024 14:16:11 +0200
Subject: [PATCH 41/58] Exponentitaion (iterative): Scala implementation
---
README.md | 4 ++--
src/scala/Exponentiation.scala | 9 +++++++++
2 files changed, 11 insertions(+), 2 deletions(-)
create mode 100644 src/scala/Exponentiation.scala
diff --git a/README.md b/README.md
index 15fbb6ec..e780c7e6 100644
--- a/README.md
+++ b/README.md
@@ -402,8 +402,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
new file mode 100644
index 00000000..4279dd34
--- /dev/null
+++ b/src/scala/Exponentiation.scala
@@ -0,0 +1,9 @@
+def exponentiation(base: Int, exponent: Int): Int = {
+ (1 to exponent)
+ .map(_ => base)
+ .reduce(_ * _)
+}
+
+object Main extends App {
+ println("5 ^ 3 = " + exponentiation(5, 3));
+}
\ No newline at end of file
From e77878655b776266561ede9dc0c35b1814ecc782 Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Fri, 25 Oct 2024 15:40:16 -0300
Subject: [PATCH 42/58] Update linear_search_recursive.py
---
src/python/linear_search_recursive.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/python/linear_search_recursive.py b/src/python/linear_search_recursive.py
index f164b299..01efd74b 100644
--- a/src/python/linear_search_recursive.py
+++ b/src/python/linear_search_recursive.py
@@ -1,4 +1,3 @@
-""" Implementaçao do algoritmo de busca sequencial com recursão """
"""Implementation of the sequential search algorithm with recursion."""
From 0d5847af9622f59191a4b574dc8b8398ddb3f42d Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 15:56:06 -0300
Subject: [PATCH 43/58] Fix YAML and JSON
---
.github/workflows/link-checker.yml | 12 ++++++------
.github/workflows/lint-checker.yml | 6 +++++-
.markdownlint.json | 2 +-
3 files changed, 12 insertions(+), 8 deletions(-)
diff --git a/.github/workflows/link-checker.yml b/.github/workflows/link-checker.yml
index 12b2e093..624386be 100644
--- a/.github/workflows/link-checker.yml
+++ b/.github/workflows/link-checker.yml
@@ -6,9 +6,9 @@ jobs:
link-checker:
runs-on: ubuntu-latest
steps:
- - name: Checkout Code
- uses: actions/checkout@main
- - name: Check Links
- uses: lycheeverse/lychee-action@v1.7.0
- with:
- fail: true
+ - name: Checkout Code
+ uses: actions/checkout@main
+ - name: Check Links
+ uses: lycheeverse/lychee-action@v1.7.0
+ with:
+ fail: true
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 59e7574f..8d3731f1 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,9 +14,11 @@ jobs:
uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- MARKDOWN_CONFIG_FILE: ".markdownlint.json"
+ MARKDOWN_CONFIG_FILE: .markdownlint.json
VALIDATE_GO: true
VALIDATE_RUBY: true
+ VALIDATE_JSON: true
+ VALIDATE_YAML: true
VALIDATE_KOTLIN: true
VALIDATE_MARKDOWN: true
VALIDATE_SCALAFMT: true
@@ -26,5 +28,7 @@ jobs:
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
VALIDATE_JAVASCRIPT_ES: true
+ VALIDATE_JSON_PRETTIER: true
+ VALIDATE_YAML_PRETTIER: true
VALIDATE_MARKDOWN_PRETTIER: true
VALIDATE_GOOGLE_JAVA_FORMAT: true
diff --git a/.markdownlint.json b/.markdownlint.json
index ea3a2bef..6f94dbc4 100644
--- a/.markdownlint.json
+++ b/.markdownlint.json
@@ -1,3 +1,3 @@
{
- "MD045": false
+ "MD045": false
}
From 9bd2b7530fa98f573b749515774199afdbba2004 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:01:09 -0300
Subject: [PATCH 44/58] Remove MARKDOWN_CONFIG_FILE
---
.github/workflows/lint-checker.yml | 1 -
1 file changed, 1 deletion(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 8d3731f1..e1b0d8cd 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,7 +14,6 @@ jobs:
uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- MARKDOWN_CONFIG_FILE: .markdownlint.json
VALIDATE_GO: true
VALIDATE_RUBY: true
VALIDATE_JSON: true
From 5ee9304bc8046ae6cf9b33b32c51fca94b6be262 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:22:52 -0300
Subject: [PATCH 45/58] Remove unused configs and create linters folder
---
.github/linters/.golangci.yml | 4 ++++
.markdownlint.json | 3 ---
.ruby-lint.yml | 14 --------------
3 files changed, 4 insertions(+), 17 deletions(-)
create mode 100644 .github/linters/.golangci.yml
delete mode 100644 .markdownlint.json
delete mode 100644 .ruby-lint.yml
diff --git a/.github/linters/.golangci.yml b/.github/linters/.golangci.yml
new file mode 100644
index 00000000..a8eddf87
--- /dev/null
+++ b/.github/linters/.golangci.yml
@@ -0,0 +1,4 @@
+linters:
+ enable:
+ - gofmt
+ - goimports
diff --git a/.markdownlint.json b/.markdownlint.json
deleted file mode 100644
index 6f94dbc4..00000000
--- a/.markdownlint.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "MD045": false
-}
diff --git a/.ruby-lint.yml b/.ruby-lint.yml
deleted file mode 100644
index 97a36c94..00000000
--- a/.ruby-lint.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-Metrics/AbcSize:
- Enabled: false
-
-Style/MixinUsage:
- Enabled: false
-
-Metrics/MethodLength:
- Enabled: false
-
-Style/CombinableLoops:
- Enabled: false
-
-Metrics/CyclomaticComplexity:
- Enabled: false
From f61e63a2d866f58be18f81f2fb938423fa03ee9c Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:39:18 -0300
Subject: [PATCH 46/58] Fix Kotlin files
---
src/kotlin/ExponentiationRecursive.kt | 10 ++++++----
src/kotlin/FibonacciRecursive.kt | 7 +++----
src/kotlin/MergeSort.kt | 5 ++++-
3 files changed, 13 insertions(+), 9 deletions(-)
diff --git a/src/kotlin/ExponentiationRecursive.kt b/src/kotlin/ExponentiationRecursive.kt
index bb6039a5..95b21122 100644
--- a/src/kotlin/ExponentiationRecursive.kt
+++ b/src/kotlin/ExponentiationRecursive.kt
@@ -9,13 +9,15 @@
*
* @return will return the *base* number raised by the *exponent*. The function returns a value of type *Long*.
*/
-fun exponentiationRecursive(base: Int, exponent: Int): Long {
- return if (exponent === 0) {
+fun exponentiationRecursive(
+ base: Int,
+ exponent: Int,
+): Long =
+ if (exponent === 0) {
1
- }; else {
+ } else {
base * exponentiationRecursive(base, exponent - 1)
}
-}
fun main() {
println(exponentiationRecursive(2, 3))
diff --git a/src/kotlin/FibonacciRecursive.kt b/src/kotlin/FibonacciRecursive.kt
index 7dc666d7..7874e0b5 100644
--- a/src/kotlin/FibonacciRecursive.kt
+++ b/src/kotlin/FibonacciRecursive.kt
@@ -8,13 +8,12 @@
*
* @return will return a logical condition if *number* is less than or equal to 1, returns 1 otherwise, the sum of itself using the concept of *recursion* to execute this sum.
*/
-fun fibonacci(number: Int): Int {
- return if (number <= 1) {
+fun fibonacci(number: Int): Int =
+ if (number <= 1) {
1
- }; else {
+ } else {
fibonacci(number - 1) + fibonacci(number - 2)
}
-}
fun main() {
println(fibonacci(5))
diff --git a/src/kotlin/MergeSort.kt b/src/kotlin/MergeSort.kt
index dd874bae..93ce92b7 100644
--- a/src/kotlin/MergeSort.kt
+++ b/src/kotlin/MergeSort.kt
@@ -10,7 +10,10 @@ fun mergeSort(arr: IntArray): IntArray {
return merge(mergeSort(left), mergeSort(right))
}
-fun merge(left: IntArray, right: IntArray): IntArray {
+fun merge(
+ left: IntArray,
+ right: IntArray,
+): IntArray {
var result = IntArray(left.size + right.size)
var leftIndex = 0
var rightIndex = 0
From 0f7937ff330fa221ee7b31263b113d1c52872fd4 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:43:43 -0300
Subject: [PATCH 47/58] Create .markdown-lint.yml
---
.github/linters/.markdown-lint.yml | 1 +
1 file changed, 1 insertion(+)
create mode 100644 .github/linters/.markdown-lint.yml
diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml
new file mode 100644
index 00000000..0cf1ceb1
--- /dev/null
+++ b/.github/linters/.markdown-lint.yml
@@ -0,0 +1 @@
+MD045: false
From 56328c0242446e23ca6f0ddff15cb2f24f4cc152 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:47:58 -0300
Subject: [PATCH 48/58] Fix markdown lint
---
.github/linters/.markdown-lint.yml | 1 -
.github/linters/.markdownlint.json | 3 +++
.github/workflows/lint-checker.yml | 1 +
3 files changed, 4 insertions(+), 1 deletion(-)
delete mode 100644 .github/linters/.markdown-lint.yml
create mode 100644 .github/linters/.markdownlint.json
diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml
deleted file mode 100644
index 0cf1ceb1..00000000
--- a/.github/linters/.markdown-lint.yml
+++ /dev/null
@@ -1 +0,0 @@
-MD045: false
diff --git a/.github/linters/.markdownlint.json b/.github/linters/.markdownlint.json
new file mode 100644
index 00000000..6f94dbc4
--- /dev/null
+++ b/.github/linters/.markdownlint.json
@@ -0,0 +1,3 @@
+{
+ "MD045": false
+}
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index e1b0d8cd..8d3731f1 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,6 +14,7 @@ jobs:
uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ MARKDOWN_CONFIG_FILE: .markdownlint.json
VALIDATE_GO: true
VALIDATE_RUBY: true
VALIDATE_JSON: true
From 626ecfeff07f6e50c4445e141e52f16f9c657869 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:53:42 -0300
Subject: [PATCH 49/58] Fix markdown lint
---
.github/linters/.markdown-lint.yml | 3 +++
.github/linters/.markdownlint.json | 3 ---
.github/workflows/lint-checker.yml | 1 -
3 files changed, 3 insertions(+), 4 deletions(-)
create mode 100644 .github/linters/.markdown-lint.yml
delete mode 100644 .github/linters/.markdownlint.json
diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml
new file mode 100644
index 00000000..efb36386
--- /dev/null
+++ b/.github/linters/.markdown-lint.yml
@@ -0,0 +1,3 @@
+MD013: false
+MD045: false
+MD033: false
diff --git a/.github/linters/.markdownlint.json b/.github/linters/.markdownlint.json
deleted file mode 100644
index 6f94dbc4..00000000
--- a/.github/linters/.markdownlint.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "MD045": false
-}
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 8d3731f1..e1b0d8cd 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -14,7 +14,6 @@ jobs:
uses: super-linter/super-linter@v7.1.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- MARKDOWN_CONFIG_FILE: .markdownlint.json
VALIDATE_GO: true
VALIDATE_RUBY: true
VALIDATE_JSON: true
From a6ffbfd9953070bd7c757fc948bbfaa1d83ef2a7 Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 16:56:21 -0300
Subject: [PATCH 50/58] Update checkout
---
.github/workflows/lint-checker.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index e1b0d8cd..953ee90e 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check Code
From e34ebfa8cd25933159aa6c8fbf133699f973b38e Mon Sep 17 00:00:00 2001
From: Kelvin Prado
Date: Fri, 25 Oct 2024 17:05:29 -0300
Subject: [PATCH 51/58] Add VALIDATE_CLANG_FORMAT
---
.github/workflows/lint-checker.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml
index 953ee90e..5a30fe47 100644
--- a/.github/workflows/lint-checker.yml
+++ b/.github/workflows/lint-checker.yml
@@ -26,6 +26,7 @@ jobs:
VALIDATE_PYTHON_RUFF: true
VALIDATE_PYTHON_BLACK: true
VALIDATE_PYTHON_ISORT: true
+ VALIDATE_CLANG_FORMAT: true
VALIDATE_JAVASCRIPT_ES: true
VALIDATE_JSON_PRETTIER: true
VALIDATE_YAML_PRETTIER: true
From fdb358ecd32f5a2f981c7f1a5194e9e7b396cebb Mon Sep 17 00:00:00 2001
From: Paul Sasieta Arana
Date: Mon, 28 Oct 2024 07:09:20 +0100
Subject: [PATCH 52/58] Linting fixed
---
src/scala/Exponentiation.scala | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
index 4279dd34..84ecdae4 100644
--- a/src/scala/Exponentiation.scala
+++ b/src/scala/Exponentiation.scala
@@ -1,9 +1,9 @@
def exponentiation(base: Int, exponent: Int): Int = {
- (1 to exponent)
- .map(_ => base)
- .reduce(_ * _)
+ (1 to exponent)
+ .map(_ => base)
+ .reduce(_ * _)
}
object Main extends App {
- println("5 ^ 3 = " + exponentiation(5, 3));
+ println("5 ^ 3 = " + exponentiation(5, 3));
}
\ No newline at end of file
From 75b842d96d4c0f57744554b5d5eb2467070fd6ac Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Mon, 28 Oct 2024 21:10:35 -0300
Subject: [PATCH 53/58] Update src/scala/Exponentiation.scala
---
src/scala/Exponentiation.scala | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
index 84ecdae4..54062c11 100644
--- a/src/scala/Exponentiation.scala
+++ b/src/scala/Exponentiation.scala
@@ -1,7 +1,7 @@
def exponentiation(base: Int, exponent: Int): Int = {
(1 to exponent)
- .map(_ => base)
- .reduce(_ * _)
+ .map(_ => base)
+ .reduce(_ * _)
}
object Main extends App {
From 66f9f94cdc865470209b1bf11fcead8c51f36644 Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Mon, 28 Oct 2024 21:10:40 -0300
Subject: [PATCH 54/58] Update src/scala/Exponentiation.scala
---
src/scala/Exponentiation.scala | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
index 54062c11..12ca02db 100644
--- a/src/scala/Exponentiation.scala
+++ b/src/scala/Exponentiation.scala
@@ -5,5 +5,5 @@ def exponentiation(base: Int, exponent: Int): Int = {
}
object Main extends App {
- println("5 ^ 3 = " + exponentiation(5, 3));
+ println("5 ^ 3 = " + exponentiation(5, 3))
}
\ No newline at end of file
From 035bf033a57e20f407e88c851957b1563008f7ea Mon Sep 17 00:00:00 2001
From: "Kelvin S. do Prado"
Date: Mon, 28 Oct 2024 21:21:05 -0300
Subject: [PATCH 55/58] Remove trailing whitespace
---
src/scala/Exponentiation.scala | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala
index 12ca02db..0640a121 100644
--- a/src/scala/Exponentiation.scala
+++ b/src/scala/Exponentiation.scala
@@ -3,7 +3,7 @@ def exponentiation(base: Int, exponent: Int): Int = {
.map(_ => base)
.reduce(_ * _)
}
-
+
object Main extends App {
println("5 ^ 3 = " + exponentiation(5, 3))
-}
\ No newline at end of file
+}
From 1518fcf3d13206d95b6e7c8144d833600dd476df Mon Sep 17 00:00:00 2001
From: Paul Sasieta Arana
Date: Tue, 29 Oct 2024 12:39:05 +0100
Subject: [PATCH 56/58] Exponentitaion (recursive): Scala implementation
---
README.md | 4 ++--
src/scala/ExponentiationRecursive.scala | 11 +++++++++++
2 files changed, 13 insertions(+), 2 deletions(-)
create mode 100644 src/scala/ExponentiationRecursive.scala
diff --git a/README.md b/README.md
index e780c7e6..fc8ae51c 100644
--- a/README.md
+++ b/README.md
@@ -460,8 +460,8 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
-
+
+
|
diff --git a/src/scala/ExponentiationRecursive.scala b/src/scala/ExponentiationRecursive.scala
new file mode 100644
index 00000000..eab9234c
--- /dev/null
+++ b/src/scala/ExponentiationRecursive.scala
@@ -0,0 +1,11 @@
+import scala.annotation.tailrec
+
+@tailrec
+def exponentiationRecursive(base: Int, exponent: Int, accumulator: Int = 1): Int = exponent match {
+ case 0 => accumulator
+ case _ => exponentiationRecursive(base, exponent - 1, accumulator * base)
+}
+
+object Main extends App {
+ println("5 ^ 3 = " + exponentiationRecursive(5, 3))
+}
From 1815d67f16ab08da4799a474ec18bb5aa9c9c6ab Mon Sep 17 00:00:00 2001
From: Paul Sasieta Arana
Date: Tue, 29 Oct 2024 12:41:27 +0100
Subject: [PATCH 57/58] README typo
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index fc8ae51c..48882c8c 100644
--- a/README.md
+++ b/README.md
@@ -460,7 +460,7 @@ In order to achieve greater coverage and encourage more people to contribute to
|
-
+
|
From 5b17ea076179f25bf6a8c6edcc90c1832c534c39 Mon Sep 17 00:00:00 2001
From: Paul Sasieta Arana
Date: Tue, 29 Oct 2024 12:45:21 +0100
Subject: [PATCH 58/58] Linting fixed
---
src/scala/ExponentiationRecursive.scala | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/scala/ExponentiationRecursive.scala b/src/scala/ExponentiationRecursive.scala
index eab9234c..58f31682 100644
--- a/src/scala/ExponentiationRecursive.scala
+++ b/src/scala/ExponentiationRecursive.scala
@@ -1,7 +1,11 @@
import scala.annotation.tailrec
@tailrec
-def exponentiationRecursive(base: Int, exponent: Int, accumulator: Int = 1): Int = exponent match {
+def exponentiationRecursive(
+ base: Int,
+ exponent: Int,
+ accumulator: Int = 1
+): Int = exponent match {
case 0 => accumulator
case _ => exponentiationRecursive(base, exponent - 1, accumulator * base)
}