From e23085635c56f236f302d7c5306f6efe1d6ea273 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 19:05:12 +0200 Subject: [PATCH 01/22] Welsh Powell Algorithm + Test --- .../datastructures/graphs/Welsh_Powell.java | 110 ++++++++++++++++++ .../graphs/WelshPowellAlgorithmTest.java | 45 +++++++ 2 files changed, 155 insertions(+) create mode 100644 src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java create mode 100644 src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java new file mode 100644 index 000000000000..a4eaa9d6a81c --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -0,0 +1,110 @@ +package com.thealgorithms.datastructures.graphs; + +import java.util.LinkedList; +import java.util.Scanner; + +/* + The Welsh-Powell algorithm is a graph coloring algorithm + used for coloring a graph with the minimum number of colors. + */ +public class Welsh_Powell { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Input for the number of vertices in the graph + System.out.print("Enter the number of vertices: "); + int numVertices = scanner.nextInt(); + scanner.nextLine(); + // Initialize the graph with the given number of vertices + WPGraph graph = new WPGraph(numVertices); + + // Input for the number of edges + System.out.print("Enter the number of edges: "); + int numEdges = scanner.nextInt(); + scanner.nextLine(); + // Adding edges to the graph based on user input + for (int i = 0; i < numEdges; i++) { + System.out.print("Enter both vertices for edge " + (i + 1) + " (format: 'src dest'): "); + String[] vertices = scanner.nextLine().split(" "); + int src = Integer.parseInt(vertices[0]); + int dest = Integer.parseInt(vertices[1]); + + graph.addEdge(src, dest); + } + + // Apply Welsh Powell coloring algorithm + int colors[] = graph.welshPowellColoring(); + + // Output the color of each vertex + for (int i = 0; i < numVertices; i++) { + System.out.println("Vertex " + (i + 1) + " is colored with color " + colors[i]); + } + + // Closing the scanner + scanner.close(); + } + + + public static class WPGraph { + + private int numVer; // Number of vertices in the graph + public LinkedList[] adjLists; // Adjacency lists for the graph + + // Constructor to initialize the graph with a certain number of vertices + public WPGraph(int vertices) { + numVer = vertices; + adjLists = new LinkedList[vertices]; + + for (int i = 0; i < vertices; i++) { + adjLists[i] = new LinkedList<>(); + } + } + + // Method to add an edge to the graph (undirected) + public void addEdge(int src, int dest) { + // Check to prevent duplicate edges + if (!adjLists[src].contains(dest)) { + adjLists[src].add(dest); + adjLists[dest].add(src); // For undirected graphs, add the reverse edge as well + } + } + + // Method implementing Welsh Powell coloring algorithm + public int[] welshPowellColoring() { + int[] colors = new int[numVer]; // Array to store color of each vertex + for (int i = 0; i < numVer; i++) { + colors[i] = -1; // Initialize all vertices as uncolored + } + + // Creating a list of vertices sorted by descending degree + LinkedList sortedVertices = new LinkedList<>(); + for (int i = 0; i < numVer; i++) { + sortedVertices.add(i); + } + sortedVertices.sort((v1, v2) -> adjLists[v2].size() - adjLists[v1].size()); + + // Coloring vertices + for (int vertex : sortedVertices) { + if (colors[vertex] == -1) { + boolean[] usedColors = new boolean[numVer]; // Track used colors + for (int neighbor : adjLists[vertex]) { + if (colors[neighbor] != -1) { + usedColors[colors[neighbor]] = true; // Mark neighbor's color as used + } + } + + // Assign the first unused color + for (int color = 0; color < numVer; color++) { + if (!usedColors[color]) { + colors[vertex] = color; + break; + } + } + } + } + + return colors; // Return the array of colors for each vertex + } + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java new file mode 100644 index 000000000000..04f042b730d6 --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -0,0 +1,45 @@ +package com.thealgorithms.datastructures.graphs; + +import com.thealgorithms.datastructures.graphs.Welsh_Powell.WPGraph; +public class WelshPowellAlgorithmTest { + + public static void main(String[] args) { + // Δημιουργία του γράφου για το test.test + int numVertices = 6; // Αριθμός κορυφών + WPGraph graph = new WPGraph(numVertices); + + // Προσθήκη ακμών + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(2, 4); + graph.addEdge(3, 4); + graph.addEdge(3, 5); + graph.addEdge(4, 5); + + // Εκτέλεση του Welsh Powell Coloring + int[] colors = graph.welshPowellColoring(); + + // Έλεγχος των αποτελεσμάτων + boolean testPassed = true; + for (int i = 0; i < numVertices; i++) { + for (int neighbor : graph.adjLists[i]) { + if (colors[i] == colors[neighbor]) { + testPassed = false; + break; + } + } + if (!testPassed) { + break; + } + } + + // Εκτύπωση αποτελεσμάτων + if (testPassed) { + System.out.println("Test Passed."); + } else { + System.out.println("Test Failed."); + } + } +} From 080904bd4ed80931fb19bb2836e5231bcb010fa5 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 19:10:18 +0200 Subject: [PATCH 02/22] Welsh Powell Algorithm+Test second commit to fit pull request --- .../thealgorithms/datastructures/graphs/Welsh_Powell.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index a4eaa9d6a81c..a4a3d4f463c8 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -4,8 +4,9 @@ import java.util.Scanner; /* - The Welsh-Powell algorithm is a graph coloring algorithm - used for coloring a graph with the minimum number of colors. + * The Welsh-Powell algorithm is a graph coloring algorithm + * used for coloring a graph with the minimum number of colors. + * https://en.wikipedia.org/wiki/Graph_coloring */ public class Welsh_Powell { From 47b77fd7163fdfdb192ff0e054d22fc5dcdbcae5 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 19:11:31 +0200 Subject: [PATCH 03/22] Welsh Powell Algorithm+Test second commit to fit pull request --- .../com/thealgorithms/datastructures/graphs/Welsh_Powell.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index a4a3d4f463c8..74fd9e2a379e 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -42,7 +42,6 @@ public static void main(String[] args) { System.out.println("Vertex " + (i + 1) + " is colored with color " + colors[i]); } - // Closing the scanner scanner.close(); } From 60e2d10dbaa6ab0ec0b62d7f03e3e71d2c56dc08 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 19:22:08 +0200 Subject: [PATCH 04/22] 3rd commit --- .../graphs/WelshPowellAlgorithmTest.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 04f042b730d6..cd3207526ee0 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -4,11 +4,11 @@ public class WelshPowellAlgorithmTest { public static void main(String[] args) { - // Δημιουργία του γράφου για το test.test - int numVertices = 6; // Αριθμός κορυφών + // Creating the graph for the test case + int numVertices = 6; // Number of vertices WPGraph graph = new WPGraph(numVertices); - // Προσθήκη ακμών + // Adding the edges graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); @@ -18,10 +18,10 @@ public static void main(String[] args) { graph.addEdge(3, 5); graph.addEdge(4, 5); - // Εκτέλεση του Welsh Powell Coloring + // Executing the method int[] colors = graph.welshPowellColoring(); - // Έλεγχος των αποτελεσμάτων + // Checking the results boolean testPassed = true; for (int i = 0; i < numVertices; i++) { for (int neighbor : graph.adjLists[i]) { @@ -35,7 +35,6 @@ public static void main(String[] args) { } } - // Εκτύπωση αποτελεσμάτων if (testPassed) { System.out.println("Test Passed."); } else { From 5868035a6b2c37d7ac858d2e9c7a7b61304d902e Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 19:54:39 +0200 Subject: [PATCH 05/22] 4th commit --- .../com/thealgorithms/datastructures/graphs/Welsh_Powell.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index 74fd9e2a379e..1c45912d492c 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -45,7 +45,6 @@ public static void main(String[] args) { scanner.close(); } - public static class WPGraph { private int numVer; // Number of vertices in the graph From 30c4cdc166ac5e4f486701749777de491c634fa9 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 20:39:01 +0200 Subject: [PATCH 06/22] 5th attempt --- .../com/thealgorithms/datastructures/graphs/Welsh_Powell.java | 1 + .../datastructures/graphs/WelshPowellAlgorithmTest.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index 1c45912d492c..e36b33334ca7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -107,3 +107,4 @@ public int[] welshPowellColoring() { } } } + diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index cd3207526ee0..84ce422a6bc4 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -42,3 +42,4 @@ public static void main(String[] args) { } } } + From 6200b82aa8cac561a1fa1813f8df35292617ee2e Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 20:41:49 +0200 Subject: [PATCH 07/22] 6th attempt --- .../com/thealgorithms/datastructures/graphs/Welsh_Powell.java | 2 +- .../datastructures/graphs/WelshPowellAlgorithmTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index e36b33334ca7..f7a8ef8c1a00 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -106,5 +106,5 @@ public int[] welshPowellColoring() { return colors; // Return the array of colors for each vertex } } -} +} diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 84ce422a6bc4..c4f551f918b9 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -41,5 +41,5 @@ public static void main(String[] args) { System.out.println("Test Failed."); } } -} +} From 037fc3a65d7fff3995b6a02a490454fe3b68f20f Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 20:46:15 +0200 Subject: [PATCH 08/22] 7th attempt --- .../datastructures/graphs/Welsh_Powell.java | 1 - .../graphs/WelshPowellAlgorithmTest.java | 59 +++++++++---------- 2 files changed, 29 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index f7a8ef8c1a00..1c45912d492c 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -106,5 +106,4 @@ public int[] welshPowellColoring() { return colors; // Return the array of colors for each vertex } } - } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index c4f551f918b9..2c9f81b84903 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -3,43 +3,42 @@ import com.thealgorithms.datastructures.graphs.Welsh_Powell.WPGraph; public class WelshPowellAlgorithmTest { - public static void main(String[] args) { - // Creating the graph for the test case - int numVertices = 6; // Number of vertices - WPGraph graph = new WPGraph(numVertices); + public static void main(String[] args) { + // Creating the graph for the test case + int numVertices = 6; // Number of vertices + WPGraph graph = new WPGraph(numVertices); - // Adding the edges - graph.addEdge(0, 1); - graph.addEdge(0, 2); - graph.addEdge(1, 3); - graph.addEdge(2, 3); - graph.addEdge(2, 4); - graph.addEdge(3, 4); - graph.addEdge(3, 5); - graph.addEdge(4, 5); + // Adding the edges + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(2, 4); + graph.addEdge(3, 4); + graph.addEdge(3, 5); + graph.addEdge(4, 5); - // Executing the method - int[] colors = graph.welshPowellColoring(); + // Executing the method + int[] colors = graph.welshPowellColoring(); - // Checking the results - boolean testPassed = true; - for (int i = 0; i < numVertices; i++) { - for (int neighbor : graph.adjLists[i]) { - if (colors[i] == colors[neighbor]) { - testPassed = false; - break; - } - } - if (!testPassed) { + // Checking the results + boolean testPassed = true; + for (int i = 0; i < numVertices; i++) { + for (int neighbor : graph.adjLists[i]) { + if (colors[i] == colors[neighbor]) { + testPassed = false; break; } } - - if (testPassed) { - System.out.println("Test Passed."); - } else { - System.out.println("Test Failed."); + if (!testPassed) { + break; } } + if (testPassed) { + System.out.println("Test Passed."); + } else { + System.out.println("Test Failed."); + } + } } From da6d43aee898f9df561cc163037c3461a526cd3e Mon Sep 17 00:00:00 2001 From: straf10 <115450409+straf10@users.noreply.github.com> Date: Wed, 31 Jan 2024 20:47:54 +0200 Subject: [PATCH 09/22] Update src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> --- .../com/thealgorithms/datastructures/graphs/Welsh_Powell.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java index 1c45912d492c..eade570c4634 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java @@ -8,7 +8,7 @@ * used for coloring a graph with the minimum number of colors. * https://en.wikipedia.org/wiki/Graph_coloring */ -public class Welsh_Powell { +public class WelshPowell { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); From 7328b1bed9ac4b65cef5dc56c536240686f925ad Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Wed, 31 Jan 2024 20:49:51 +0200 Subject: [PATCH 10/22] 8th attempt --- .../graphs/{Welsh_Powell.java => WelshPowell.java} | 2 +- .../datastructures/graphs/WelshPowellAlgorithmTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/main/java/com/thealgorithms/datastructures/graphs/{Welsh_Powell.java => WelshPowell.java} (99%) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java similarity index 99% rename from src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java rename to src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 1c45912d492c..eade570c4634 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Welsh_Powell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -8,7 +8,7 @@ * used for coloring a graph with the minimum number of colors. * https://en.wikipedia.org/wiki/Graph_coloring */ -public class Welsh_Powell { +public class WelshPowell { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 2c9f81b84903..f2f2dd443d2c 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,6 +1,6 @@ package com.thealgorithms.datastructures.graphs; -import com.thealgorithms.datastructures.graphs.Welsh_Powell.WPGraph; +import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; public class WelshPowellAlgorithmTest { public static void main(String[] args) { From c1ae53a602aef8da9c79d79387baec18d61308f2 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Thu, 1 Feb 2024 01:01:35 +0200 Subject: [PATCH 11/22] 9th commit(removed main and changed the test class) --- .../datastructures/graphs/WelshPowell.java | 36 ------------ .../graphs/WelshPowellAlgorithmTest.java | 58 ++++++++++--------- 2 files changed, 31 insertions(+), 63 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index eade570c4634..a18965f82d71 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -1,7 +1,6 @@ package com.thealgorithms.datastructures.graphs; import java.util.LinkedList; -import java.util.Scanner; /* * The Welsh-Powell algorithm is a graph coloring algorithm @@ -10,41 +9,6 @@ */ public class WelshPowell { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - - // Input for the number of vertices in the graph - System.out.print("Enter the number of vertices: "); - int numVertices = scanner.nextInt(); - scanner.nextLine(); - // Initialize the graph with the given number of vertices - WPGraph graph = new WPGraph(numVertices); - - // Input for the number of edges - System.out.print("Enter the number of edges: "); - int numEdges = scanner.nextInt(); - scanner.nextLine(); - // Adding edges to the graph based on user input - for (int i = 0; i < numEdges; i++) { - System.out.print("Enter both vertices for edge " + (i + 1) + " (format: 'src dest'): "); - String[] vertices = scanner.nextLine().split(" "); - int src = Integer.parseInt(vertices[0]); - int dest = Integer.parseInt(vertices[1]); - - graph.addEdge(src, dest); - } - - // Apply Welsh Powell coloring algorithm - int colors[] = graph.welshPowellColoring(); - - // Output the color of each vertex - for (int i = 0; i < numVertices; i++) { - System.out.println("Vertex " + (i + 1) + " is colored with color " + colors[i]); - } - - scanner.close(); - } - public static class WPGraph { private int numVer; // Number of vertices in the graph diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index f2f2dd443d2c..34ed805dd095 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,44 +1,48 @@ package com.thealgorithms.datastructures.graphs; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; -public class WelshPowellAlgorithmTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) { - // Creating the graph for the test case - int numVertices = 6; // Number of vertices - WPGraph graph = new WPGraph(numVertices); +class WelshPowellAlgorithmTest { - // Adding the edges + @Test + void testSimpleGraph() { + WPGraph graph = new WPGraph(4); graph.addEdge(0, 1); - graph.addEdge(0, 2); - graph.addEdge(1, 3); + graph.addEdge(1, 2); graph.addEdge(2, 3); - graph.addEdge(2, 4); - graph.addEdge(3, 4); - graph.addEdge(3, 5); - graph.addEdge(4, 5); + int[] colors = graph.welshPowellColoring(); + assertEquals(true, isValidColoring(graph, colors)); + } - // Executing the method + @Test + void testDisconnectedGraph() { + WPGraph graph = new WPGraph(3); + // Disconnected graph, no edges int[] colors = graph.welshPowellColoring(); + assertEquals(true, isValidColoring(graph, colors)); + } - // Checking the results - boolean testPassed = true; - for (int i = 0; i < numVertices; i++) { + @Test + void testCompleteGraph() { + WPGraph graph = new WPGraph(3); + graph.addEdge(0, 1); + graph.addEdge(1, 2); + graph.addEdge(2, 0); + int[] colors = graph.welshPowellColoring(); + assertEquals(true, isValidColoring(graph, colors)); + } + + private boolean isValidColoring(WPGraph graph, int[] colors) { + for (int i = 0; i < graph.adjLists.length; i++) { for (int neighbor : graph.adjLists[i]) { if (colors[i] == colors[neighbor]) { - testPassed = false; - break; + return false; } } - if (!testPassed) { - break; - } - } - - if (testPassed) { - System.out.println("Test Passed."); - } else { - System.out.println("Test Failed."); } + return true; } } From a7f3fcdcf3669c4205ec65f5626b7b885993e289 Mon Sep 17 00:00:00 2001 From: straf10 <115450409+straf10@users.noreply.github.com> Date: Fri, 2 Feb 2024 18:19:35 +0200 Subject: [PATCH 12/22] Update src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> --- .../com/thealgorithms/datastructures/graphs/WelshPowell.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index a18965f82d71..d53aa3717baf 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -25,7 +25,7 @@ public WPGraph(int vertices) { } // Method to add an edge to the graph (undirected) - public void addEdge(int src, int dest) { + public void addEdge(int nodeA, int nodeB) { // Check to prevent duplicate edges if (!adjLists[src].contains(dest)) { adjLists[src].add(dest); From f59fb89596e898e1b1975a97e946afd90b011767 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Sun, 4 Feb 2024 14:49:08 +0200 Subject: [PATCH 13/22] implemented Hashset, changed name to src,dst to nodeA,B added some methods in order for the test class to work --- .../datastructures/graphs/WelshPowell.java | 113 +++++++++++------- .../graphs/WelshPowellAlgorithmTest.java | 38 +++--- 2 files changed, 90 insertions(+), 61 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index a18965f82d71..8fdc4c8c43de 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -1,5 +1,6 @@ package com.thealgorithms.datastructures.graphs; +import java.util.HashSet; import java.util.LinkedList; /* @@ -7,67 +8,95 @@ * used for coloring a graph with the minimum number of colors. * https://en.wikipedia.org/wiki/Graph_coloring */ + public class WelshPowell { public static class WPGraph { - private int numVer; // Number of vertices in the graph - public LinkedList[] adjLists; // Adjacency lists for the graph + private HashSet[] adjLists; // Adjacency lists for the graph using HashSet - // Constructor to initialize the graph with a certain number of vertices public WPGraph(int vertices) { numVer = vertices; - adjLists = new LinkedList[vertices]; - + adjLists = new HashSet[vertices]; for (int i = 0; i < vertices; i++) { - adjLists[i] = new LinkedList<>(); + adjLists[i] = new HashSet<>(); } } - // Method to add an edge to the graph (undirected) - public void addEdge(int src, int dest) { - // Check to prevent duplicate edges - if (!adjLists[src].contains(dest)) { - adjLists[src].add(dest); - adjLists[dest].add(src); // For undirected graphs, add the reverse edge as well - } + public void addEdge(int nodeA, int nodeB) { + adjLists[nodeA].add(nodeB); + adjLists[nodeB].add(nodeA); } - // Method implementing Welsh Powell coloring algorithm - public int[] welshPowellColoring() { - int[] colors = new int[numVer]; // Array to store color of each vertex - for (int i = 0; i < numVer; i++) { - colors[i] = -1; // Initialize all vertices as uncolored - } + public HashSet getAdjList(int vertex) { + return adjLists[vertex]; + } - // Creating a list of vertices sorted by descending degree - LinkedList sortedVertices = new LinkedList<>(); - for (int i = 0; i < numVer; i++) { - sortedVertices.add(i); - } - sortedVertices.sort((v1, v2) -> adjLists[v2].size() - adjLists[v1].size()); - - // Coloring vertices - for (int vertex : sortedVertices) { - if (colors[vertex] == -1) { - boolean[] usedColors = new boolean[numVer]; // Track used colors - for (int neighbor : adjLists[vertex]) { - if (colors[neighbor] != -1) { - usedColors[colors[neighbor]] = true; // Mark neighbor's color as used - } + public int getNumVertices() { + return numVer; + } + + // Helper method to check if an edge exists (used for testing) + boolean isEdgePresent(int v1, int v2) { + return adjLists[v1].contains(v2); + } + + } + + public static int[] welshPowellColoring(WPGraph graph) { + int numVer = graph.getNumVertices(); + int[] colors = new int[numVer]; + for (int i = 0; i < numVer; i++) { + colors[i] = -1; // Initialize all vertices as uncolored + } + + LinkedList sortedVertices = new LinkedList<>(); + for (int i = 0; i < numVer; i++) { + sortedVertices.add(i); + } + sortedVertices.sort((v1, v2) -> graph.getAdjList(v2).size() - graph.getAdjList(v1).size()); + + for (int vertex : sortedVertices) { + if (colors[vertex] == -1) { + boolean[] usedColors = new boolean[numVer]; // Track used colors + for (int neighbor : graph.getAdjList(vertex)) { + if (colors[neighbor] != -1) { + usedColors[colors[neighbor]] = true; // Mark neighbor's color as used } + } - // Assign the first unused color - for (int color = 0; color < numVer; color++) { - if (!usedColors[color]) { - colors[vertex] = color; - break; - } + // Assign the first unused color + for (int color = 0; color < numVer; color++) { + if (!usedColors[color]) { + colors[vertex] = color; + break; } } } - - return colors; // Return the array of colors for each vertex } + + return colors; // Return the array of colors for each vertex + } + + // Public static method to get the adjacency list of a vertex + public static HashSet getAdjList(WPGraph graph, int vertex) { + return graph.getAdjList(vertex); + } + + // Public static methods for testing purpose + public static WPGraph createGraph(int vertices) { + return new WPGraph(vertices); + } + + public static void addEdge(WPGraph graph, int nodeA, int nodeB) { + graph.addEdge(nodeA, nodeB); + } + + public static boolean isEdgePresent(WPGraph graph, int v1, int v2) { + return graph.isEdgePresent(v1, v2); + } + + public static int getNumVertices(WPGraph graph) { + return graph.getNumVertices(); } } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 34ed805dd095..ff13de51e307 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,44 +1,44 @@ package com.thealgorithms.datastructures.graphs; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; - import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; -import org.junit.jupiter.api.Test; + class WelshPowellAlgorithmTest { @Test void testSimpleGraph() { - WPGraph graph = new WPGraph(4); - graph.addEdge(0, 1); - graph.addEdge(1, 2); - graph.addEdge(2, 3); - int[] colors = graph.welshPowellColoring(); + WPGraph graph = WelshPowell.createGraph(4); + WelshPowell.addEdge(graph, 0, 1); + WelshPowell.addEdge(graph, 1, 2); + WelshPowell.addEdge(graph, 2, 3); + int[] colors = WelshPowell.welshPowellColoring(graph); assertEquals(true, isValidColoring(graph, colors)); } @Test void testDisconnectedGraph() { - WPGraph graph = new WPGraph(3); - // Disconnected graph, no edges - int[] colors = graph.welshPowellColoring(); + WPGraph graph = WelshPowell.createGraph(3); + int[] colors = WelshPowell.welshPowellColoring(graph); assertEquals(true, isValidColoring(graph, colors)); } @Test void testCompleteGraph() { - WPGraph graph = new WPGraph(3); - graph.addEdge(0, 1); - graph.addEdge(1, 2); - graph.addEdge(2, 0); - int[] colors = graph.welshPowellColoring(); + WPGraph graph = WelshPowell.createGraph(3); + WelshPowell.addEdge(graph, 0, 1); + WelshPowell.addEdge(graph, 1, 2); + WelshPowell.addEdge(graph, 2, 0); + int[] colors = WelshPowell.welshPowellColoring(graph); assertEquals(true, isValidColoring(graph, colors)); } - private boolean isValidColoring(WPGraph graph, int[] colors) { - for (int i = 0; i < graph.adjLists.length; i++) { - for (int neighbor : graph.adjLists[i]) { - if (colors[i] == colors[neighbor]) { + private boolean isValidColoring(WelshPowell.WPGraph graph, int[] colors) { + int numVertices = WelshPowell.getNumVertices(graph); + for (int i = 0; i < numVertices; i++) { + for (int neighbor : WelshPowell.getAdjList(graph, i)) { + if (i != neighbor && colors[i] == colors[neighbor]) { return false; } } From 68cefa15395da3d3df88b7b383b3c6d084697bea Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Sun, 4 Feb 2024 14:54:13 +0200 Subject: [PATCH 14/22] clang format --- .../com/thealgorithms/datastructures/graphs/WelshPowell.java | 1 - .../datastructures/graphs/WelshPowellAlgorithmTest.java | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 8fdc4c8c43de..9a672d496f40 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -40,7 +40,6 @@ public int getNumVertices() { boolean isEdgePresent(int v1, int v2) { return adjLists[v1].contains(v2); } - } public static int[] welshPowellColoring(WPGraph graph) { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index ff13de51e307..b2a3590264b1 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.datastructures.graphs; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; +import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; +import org.junit.jupiter.api.Test; class WelshPowellAlgorithmTest { From ba19ccbb711ff7208f3fa47eede5507a94879428 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Mon, 5 Feb 2024 00:12:36 +0200 Subject: [PATCH 15/22] added 4 new methods to improve the code, test class still unchanged but works. (working on it :) ) --- .../datastructures/graphs/WelshPowell.java | 79 ++++++++----------- .../graphs/WelshPowellAlgorithmTest.java | 21 +++-- 2 files changed, 42 insertions(+), 58 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 9a672d496f40..fc8e6b06200d 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -1,7 +1,9 @@ package com.thealgorithms.datastructures.graphs; +import java.util.Arrays; +import java.util.Comparator; import java.util.HashSet; -import java.util.LinkedList; +import java.util.stream.IntStream; /* * The Welsh-Powell algorithm is a graph coloring algorithm @@ -12,18 +14,18 @@ public class WelshPowell { public static class WPGraph { - private int numVer; // Number of vertices in the graph + private final int numVer; // Number of vertices in the graph private HashSet[] adjLists; // Adjacency lists for the graph using HashSet public WPGraph(int vertices) { numVer = vertices; adjLists = new HashSet[vertices]; - for (int i = 0; i < vertices; i++) { - adjLists[i] = new HashSet<>(); - } + Arrays.setAll(adjLists, i -> new HashSet<>()); } public void addEdge(int nodeA, int nodeB) { + assert (0 <= nodeA && nodeA < numVer); + assert (0 <= nodeB && nodeB < numVer); adjLists[nodeA].add(nodeB); adjLists[nodeB].add(nodeA); } @@ -35,51 +37,42 @@ public HashSet getAdjList(int vertex) { public int getNumVertices() { return numVer; } - - // Helper method to check if an edge exists (used for testing) - boolean isEdgePresent(int v1, int v2) { - return adjLists[v1].contains(v2); - } } public static int[] welshPowellColoring(WPGraph graph) { int numVer = graph.getNumVertices(); - int[] colors = new int[numVer]; - for (int i = 0; i < numVer; i++) { - colors[i] = -1; // Initialize all vertices as uncolored - } - - LinkedList sortedVertices = new LinkedList<>(); - for (int i = 0; i < numVer; i++) { - sortedVertices.add(i); - } - sortedVertices.sort((v1, v2) -> graph.getAdjList(v2).size() - graph.getAdjList(v1).size()); + int[] colors = initializeColors(numVer); // Use helper method to initialize color array + Integer[] sortedVertices = getSortedNodes(graph, numVer); // Use helper method to get sorted vertices for (int vertex : sortedVertices) { - if (colors[vertex] == -1) { - boolean[] usedColors = new boolean[numVer]; // Track used colors - for (int neighbor : graph.getAdjList(vertex)) { - if (colors[neighbor] != -1) { - usedColors[colors[neighbor]] = true; // Mark neighbor's color as used - } - } - - // Assign the first unused color - for (int color = 0; color < numVer; color++) { - if (!usedColors[color]) { - colors[vertex] = color; - break; - } - } + if (colors[vertex] != -1) { + continue; } + boolean[] usedColors = computeUsedColors(graph, vertex, colors, numVer); // Use helper method to compute used colors + colors[vertex] = firstUnusedColor(usedColors, numVer); // Use helper method to find first unused color } - return colors; // Return the array of colors for each vertex + return colors; + } + + private static int[] initializeColors(int numVer) { + int[] colors = new int[numVer]; + Arrays.fill(colors, -1); + return colors; + } + + private static Integer[] getSortedNodes(WPGraph graph, int numVer) { + return IntStream.range(0, numVer).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjList(v).size())).toArray(Integer[] ::new); + } + + private static boolean[] computeUsedColors(WPGraph graph, int vertex, int[] colors, int numVer) { + boolean[] usedColors = new boolean[numVer]; + graph.getAdjList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); + return usedColors; } - // Public static method to get the adjacency list of a vertex - public static HashSet getAdjList(WPGraph graph, int vertex) { - return graph.getAdjList(vertex); + private static int firstUnusedColor(boolean[] usedColors, int numVer) { + return IntStream.range(0, numVer).filter(color -> !usedColors[color]).findFirst().getAsInt(); } // Public static methods for testing purpose @@ -90,12 +83,4 @@ public static WPGraph createGraph(int vertices) { public static void addEdge(WPGraph graph, int nodeA, int nodeB) { graph.addEdge(nodeA, nodeB); } - - public static boolean isEdgePresent(WPGraph graph, int v1, int v2) { - return graph.isEdgePresent(v1, v2); - } - - public static int getNumVertices(WPGraph graph) { - return graph.getNumVertices(); - } } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index b2a3590264b1..3219f20da267 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,44 +1,43 @@ package com.thealgorithms.datastructures.graphs; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; import org.junit.jupiter.api.Test; class WelshPowellAlgorithmTest { @Test void testSimpleGraph() { - WPGraph graph = WelshPowell.createGraph(4); + WelshPowell.WPGraph graph = WelshPowell.createGraph(4); WelshPowell.addEdge(graph, 0, 1); WelshPowell.addEdge(graph, 1, 2); WelshPowell.addEdge(graph, 2, 3); int[] colors = WelshPowell.welshPowellColoring(graph); - assertEquals(true, isValidColoring(graph, colors)); + assertTrue(isValidColoring(graph, colors)); } @Test void testDisconnectedGraph() { - WPGraph graph = WelshPowell.createGraph(3); + WelshPowell.WPGraph graph = WelshPowell.createGraph(3); int[] colors = WelshPowell.welshPowellColoring(graph); - assertEquals(true, isValidColoring(graph, colors)); + assertTrue(isValidColoring(graph, colors)); } @Test void testCompleteGraph() { - WPGraph graph = WelshPowell.createGraph(3); + WelshPowell.WPGraph graph = WelshPowell.createGraph(3); WelshPowell.addEdge(graph, 0, 1); WelshPowell.addEdge(graph, 1, 2); WelshPowell.addEdge(graph, 2, 0); int[] colors = WelshPowell.welshPowellColoring(graph); - assertEquals(true, isValidColoring(graph, colors)); + assertTrue(isValidColoring(graph, colors)); } private boolean isValidColoring(WelshPowell.WPGraph graph, int[] colors) { - int numVertices = WelshPowell.getNumVertices(graph); + int numVertices = graph.getNumVertices(); for (int i = 0; i < numVertices; i++) { - for (int neighbor : WelshPowell.getAdjList(graph, i)) { - if (i != neighbor && colors[i] == colors[neighbor]) { + for (int neighbor : graph.getAdjList(i)) { + if (colors[i] == colors[neighbor]) { return false; } } From 207bb9fdc55a2cc45e6dd4d7dd2f9e19c6bea840 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Mon, 5 Feb 2024 16:30:42 +0200 Subject: [PATCH 16/22] implemented the new changes. Test class probably needs more work --- .../datastructures/graphs/WelshPowell.java | 55 +++++++++---------- .../graphs/WelshPowellAlgorithmTest.java | 23 ++++---- 2 files changed, 36 insertions(+), 42 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index fc8e6b06200d..5220adeba5cb 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -13,45 +13,47 @@ public class WelshPowell { - public static class WPGraph { - private final int numVer; // Number of vertices in the graph - private HashSet[] adjLists; // Adjacency lists for the graph using HashSet + static class WPGraph { + private int numVer; // Number of vertices in the graph + private HashSet[] adjLists; // Adjacency lists for the graph - public WPGraph(int vertices) { + private WPGraph(int vertices) { numVer = vertices; adjLists = new HashSet[vertices]; Arrays.setAll(adjLists, i -> new HashSet<>()); } - public void addEdge(int nodeA, int nodeB) { - assert (0 <= nodeA && nodeA < numVer); - assert (0 <= nodeB && nodeB < numVer); + private void addEdge(int nodeA, int nodeB) { adjLists[nodeA].add(nodeB); adjLists[nodeB].add(nodeA); } - public HashSet getAdjList(int vertex) { + HashSet getAdjList(int vertex) { return adjLists[vertex]; } - public int getNumVertices() { + int getNumVertices() { return numVer; } } - public static int[] welshPowellColoring(WPGraph graph) { - int numVer = graph.getNumVertices(); - int[] colors = initializeColors(numVer); // Use helper method to initialize color array - Integer[] sortedVertices = getSortedNodes(graph, numVer); // Use helper method to get sorted vertices + public static WPGraph makeGraph(int numberOfVertices, int[][] listOfEdges) { + WPGraph graph = new WPGraph(numberOfVertices); + for (int[] edge : listOfEdges) { + graph.addEdge(edge[0], edge[1]); + } + return graph; + } + public static int[] welshPowellColoring(WPGraph graph) { + int[] colors = initializeColors(graph.getNumVertices()); + Integer[] sortedVertices = getSortedNodes(graph); for (int vertex : sortedVertices) { - if (colors[vertex] != -1) { - continue; + if (colors[vertex] == -1) { + boolean[] usedColors = computeUsedColors(graph, vertex, colors); + colors[vertex] = firstUnusedColor(usedColors); } - boolean[] usedColors = computeUsedColors(graph, vertex, colors, numVer); // Use helper method to compute used colors - colors[vertex] = firstUnusedColor(usedColors, numVer); // Use helper method to find first unused color } - return colors; } @@ -61,23 +63,18 @@ private static int[] initializeColors(int numVer) { return colors; } - private static Integer[] getSortedNodes(WPGraph graph, int numVer) { - return IntStream.range(0, numVer).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjList(v).size())).toArray(Integer[] ::new); + private static Integer[] getSortedNodes(WPGraph graph) { + return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjList(v).size())).toArray(Integer[] ::new); } - private static boolean[] computeUsedColors(WPGraph graph, int vertex, int[] colors, int numVer) { - boolean[] usedColors = new boolean[numVer]; + private static boolean[] computeUsedColors(WPGraph graph, int vertex, int[] colors) { + boolean[] usedColors = new boolean[graph.getNumVertices()]; graph.getAdjList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); return usedColors; } - private static int firstUnusedColor(boolean[] usedColors, int numVer) { - return IntStream.range(0, numVer).filter(color -> !usedColors[color]).findFirst().getAsInt(); - } - - // Public static methods for testing purpose - public static WPGraph createGraph(int vertices) { - return new WPGraph(vertices); + private static int firstUnusedColor(boolean[] usedColors) { + return IntStream.range(0, usedColors.length).filter(color -> !usedColors[color]).findFirst().getAsInt(); } public static void addEdge(WPGraph graph, int nodeA, int nodeB) { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 3219f20da267..302a9e08a212 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -2,46 +2,43 @@ import static org.junit.jupiter.api.Assertions.assertTrue; +import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; import org.junit.jupiter.api.Test; class WelshPowellAlgorithmTest { @Test void testSimpleGraph() { - WelshPowell.WPGraph graph = WelshPowell.createGraph(4); - WelshPowell.addEdge(graph, 0, 1); - WelshPowell.addEdge(graph, 1, 2); - WelshPowell.addEdge(graph, 2, 3); + int[][] edges = {{0, 1}, {1, 2}, {2, 3}}; + WPGraph graph = WelshPowell.makeGraph(4, edges); int[] colors = WelshPowell.welshPowellColoring(graph); assertTrue(isValidColoring(graph, colors)); } @Test void testDisconnectedGraph() { - WelshPowell.WPGraph graph = WelshPowell.createGraph(3); + WPGraph graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges int[] colors = WelshPowell.welshPowellColoring(graph); assertTrue(isValidColoring(graph, colors)); } @Test void testCompleteGraph() { - WelshPowell.WPGraph graph = WelshPowell.createGraph(3); - WelshPowell.addEdge(graph, 0, 1); - WelshPowell.addEdge(graph, 1, 2); - WelshPowell.addEdge(graph, 2, 0); + int[][] edges = {{0, 1}, {1, 2}, {2, 0}}; + WPGraph graph = WelshPowell.makeGraph(3, edges); int[] colors = WelshPowell.welshPowellColoring(graph); assertTrue(isValidColoring(graph, colors)); } - private boolean isValidColoring(WelshPowell.WPGraph graph, int[] colors) { + private boolean isValidColoring(WPGraph graph, int[] colors) { int numVertices = graph.getNumVertices(); for (int i = 0; i < numVertices; i++) { for (int neighbor : graph.getAdjList(i)) { - if (colors[i] == colors[neighbor]) { - return false; + if (i != neighbor && colors[i] == colors[neighbor]) { + return false; // Adjacent vertices have the same color } } } - return true; + return true; // No adjacent vertices share the same color } } From 01db1c3ed3f570417d888b2a46bf6e2185910ec5 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Tue, 6 Feb 2024 19:04:48 +0200 Subject: [PATCH 17/22] changed the addEdge method to disallow self loops(nodeA==nodeB), the makeGraph so the listofEdges haw exactly 2 elements, and add a more complex graph in the test class --- .../datastructures/graphs/WelshPowell.java | 60 ++++++++++++------- .../graphs/WelshPowellAlgorithmTest.java | 41 +++++++++---- 2 files changed, 67 insertions(+), 34 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 5220adeba5cb..c0f8b88537c9 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -11,41 +11,59 @@ * https://en.wikipedia.org/wiki/Graph_coloring */ -public class WelshPowell { +public final class WelshPowell { + private WelshPowell() { + } + + static class Graph { + private HashSet[] adjacencyLists; - static class WPGraph { - private int numVer; // Number of vertices in the graph - private HashSet[] adjLists; // Adjacency lists for the graph + private Graph(int vertices) { + if (vertices < 0) { + throw new IllegalArgumentException("Number of vertices cannot be negative"); + } - private WPGraph(int vertices) { - numVer = vertices; - adjLists = new HashSet[vertices]; - Arrays.setAll(adjLists, i -> new HashSet<>()); + adjacencyLists = new HashSet[vertices]; + Arrays.setAll(adjacencyLists, i -> new HashSet<>()); } private void addEdge(int nodeA, int nodeB) { - adjLists[nodeA].add(nodeB); - adjLists[nodeB].add(nodeA); + validateVertex(nodeA); + validateVertex(nodeB); + if (nodeA == nodeB) { + throw new IllegalArgumentException("Self-loops are not allowed"); + } + adjacencyLists[nodeA].add(nodeB); + adjacencyLists[nodeB].add(nodeA); + } + + private void validateVertex(int vertex) { + if (vertex < 0 || vertex >= getNumVertices()) { + throw new IllegalArgumentException("Vertex " + vertex + " is out of bounds"); + } } HashSet getAdjList(int vertex) { - return adjLists[vertex]; + return adjacencyLists[vertex]; } int getNumVertices() { - return numVer; + return adjacencyLists.length; } } - public static WPGraph makeGraph(int numberOfVertices, int[][] listOfEdges) { - WPGraph graph = new WPGraph(numberOfVertices); + public static Graph makeGraph(int numberOfVertices, int[][] listOfEdges) { + Graph graph = new Graph(numberOfVertices); for (int[] edge : listOfEdges) { + if (edge.length != 2) { + throw new IllegalArgumentException("Edge array must have exactly two elements"); + } graph.addEdge(edge[0], edge[1]); } return graph; } - public static int[] welshPowellColoring(WPGraph graph) { + public static int[] findColoring(Graph graph) { int[] colors = initializeColors(graph.getNumVertices()); Integer[] sortedVertices = getSortedNodes(graph); for (int vertex : sortedVertices) { @@ -57,17 +75,17 @@ public static int[] welshPowellColoring(WPGraph graph) { return colors; } - private static int[] initializeColors(int numVer) { - int[] colors = new int[numVer]; + private static int[] initializeColors(int numberOfVerticies) { + int[] colors = new int[numberOfVerticies]; Arrays.fill(colors, -1); return colors; } - private static Integer[] getSortedNodes(WPGraph graph) { + private static Integer[] getSortedNodes(final Graph graph) { return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjList(v).size())).toArray(Integer[] ::new); } - private static boolean[] computeUsedColors(WPGraph graph, int vertex, int[] colors) { + private static boolean[] computeUsedColors(final Graph graph, final int vertex, final int[] colors) { boolean[] usedColors = new boolean[graph.getNumVertices()]; graph.getAdjList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); return usedColors; @@ -76,8 +94,4 @@ private static boolean[] computeUsedColors(WPGraph graph, int vertex, int[] colo private static int firstUnusedColor(boolean[] usedColors) { return IntStream.range(0, usedColors.length).filter(color -> !usedColors[color]).findFirst().getAsInt(); } - - public static void addEdge(WPGraph graph, int nodeA, int nodeB) { - graph.addEdge(nodeA, nodeB); - } } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java index 302a9e08a212..894e34f29598 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java @@ -1,8 +1,10 @@ package com.thealgorithms.datastructures.graphs; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.thealgorithms.datastructures.graphs.WelshPowell.WPGraph; +import com.thealgorithms.datastructures.graphs.WelshPowell.Graph; +import java.util.Arrays; import org.junit.jupiter.api.Test; class WelshPowellAlgorithmTest { @@ -10,27 +12,40 @@ class WelshPowellAlgorithmTest { @Test void testSimpleGraph() { int[][] edges = {{0, 1}, {1, 2}, {2, 3}}; - WPGraph graph = WelshPowell.makeGraph(4, edges); - int[] colors = WelshPowell.welshPowellColoring(graph); - assertTrue(isValidColoring(graph, colors)); + Graph graph = WelshPowell.makeGraph(4, edges); + int[] colors = WelshPowell.findColoring(graph); + assertTrue(isColoringValid(graph, colors)); + assertEquals(2, countDistinctColors(colors)); } @Test void testDisconnectedGraph() { - WPGraph graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges - int[] colors = WelshPowell.welshPowellColoring(graph); - assertTrue(isValidColoring(graph, colors)); + Graph graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges + int[] colors = WelshPowell.findColoring(graph); + assertTrue(isColoringValid(graph, colors)); + assertEquals(1, countDistinctColors(colors)); } @Test void testCompleteGraph() { int[][] edges = {{0, 1}, {1, 2}, {2, 0}}; - WPGraph graph = WelshPowell.makeGraph(3, edges); - int[] colors = WelshPowell.welshPowellColoring(graph); - assertTrue(isValidColoring(graph, colors)); + Graph graph = WelshPowell.makeGraph(3, edges); + int[] colors = WelshPowell.findColoring(graph); + assertTrue(isColoringValid(graph, colors)); + assertEquals(3, countDistinctColors(colors)); } - private boolean isValidColoring(WPGraph graph, int[] colors) { + @Test + void testComplexGraph() { + int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {1, 3}}; + Graph graph = WelshPowell.makeGraph(5, edges); + int[] colors = WelshPowell.findColoring(graph); + assertTrue(isColoringValid(graph, colors)); + // The expected number of colors may vary depending on the graph structure + assertTrue(countDistinctColors(colors) >= 3); + } + + private boolean isColoringValid(Graph graph, int[] colors) { int numVertices = graph.getNumVertices(); for (int i = 0; i < numVertices; i++) { for (int neighbor : graph.getAdjList(i)) { @@ -41,4 +56,8 @@ private boolean isValidColoring(WPGraph graph, int[] colors) { } return true; // No adjacent vertices share the same color } + + private int countDistinctColors(int[] colors) { + return (int) Arrays.stream(colors).distinct().count(); + } } From a5e876f6ca6e157828b918a9440b12974c33e6d9 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Tue, 6 Feb 2024 21:11:13 +0200 Subject: [PATCH 18/22] added all the tests except one --- ...lgorithmTest.java => WelshPowellTest.java} | 42 ++++++++++++------- 1 file changed, 28 insertions(+), 14 deletions(-) rename src/test/java/com/thealgorithms/datastructures/graphs/{WelshPowellAlgorithmTest.java => WelshPowellTest.java} (51%) diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java similarity index 51% rename from src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java rename to src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java index 894e34f29598..30cc773e409f 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java @@ -1,18 +1,16 @@ package com.thealgorithms.datastructures.graphs; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.datastructures.graphs.WelshPowell.Graph; import java.util.Arrays; import org.junit.jupiter.api.Test; -class WelshPowellAlgorithmTest { +class WelshPowellTest { @Test void testSimpleGraph() { - int[][] edges = {{0, 1}, {1, 2}, {2, 3}}; - Graph graph = WelshPowell.makeGraph(4, edges); + final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(2, countDistinctColors(colors)); @@ -20,7 +18,7 @@ void testSimpleGraph() { @Test void testDisconnectedGraph() { - Graph graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges + final var graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(1, countDistinctColors(colors)); @@ -28,8 +26,7 @@ void testDisconnectedGraph() { @Test void testCompleteGraph() { - int[][] edges = {{0, 1}, {1, 2}, {2, 0}}; - Graph graph = WelshPowell.makeGraph(3, edges); + final var graph = WelshPowell.makeGraph(3, new int[][] {{0, 1}, {1, 2}, {2, 0}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); assertEquals(3, countDistinctColors(colors)); @@ -37,17 +34,34 @@ void testCompleteGraph() { @Test void testComplexGraph() { - int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {1, 3}}; - Graph graph = WelshPowell.makeGraph(5, edges); + final var graph = WelshPowell.makeGraph(5, new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {1, 3}}); int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); - // The expected number of colors may vary depending on the graph structure - assertTrue(countDistinctColors(colors) >= 3); + assertEquals(3, countDistinctColors(colors)); // Expect exactly 3 colors + } + + @Test + void testNegativeVertices() { + assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(-1, new int[][] {}); }, "Number of vertices cannot be negative"); + } + + @Test + void testSelfLoop() { + assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 0}}); }, "Self-loops are not allowed"); + } + + @Test + void testInvalidVertex() { + assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 3}}); }, "Vertex out of bounds"); + } + + @Test + void testInvalidEdgeArray() { + assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0}}); }, "Edge array must have exactly two elements"); } private boolean isColoringValid(Graph graph, int[] colors) { - int numVertices = graph.getNumVertices(); - for (int i = 0; i < numVertices; i++) { + for (int i = 0; i < graph.getNumVertices(); i++) { for (int neighbor : graph.getAdjList(i)) { if (i != neighbor && colors[i] == colors[neighbor]) { return false; // Adjacent vertices have the same color From c71082a5f019ba1e22b0df7dca9922e9acdefea2 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Tue, 6 Feb 2024 23:10:48 +0200 Subject: [PATCH 19/22] preColored test --- .../datastructures/graphs/WelshPowell.java | 34 ++++++++++++++++--- .../graphs/WelshPowellTest.java | 19 +++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index c0f8b88537c9..8f69b3154e02 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -63,18 +63,42 @@ public static Graph makeGraph(int numberOfVertices, int[][] listOfEdges) { return graph; } - public static int[] findColoring(Graph graph) { - int[] colors = initializeColors(graph.getNumVertices()); + public static int[] findColoring(Graph graph, int preColoredVertex, int preColor) { + int numVertices = graph.getNumVertices(); + int[] colors = initializeColors(numVertices); + + if (preColoredVertex >= 0 && preColoredVertex < numVertices && preColor >= 0) { + colors[preColoredVertex] = preColor; + } + Integer[] sortedVertices = getSortedNodes(graph); + for (int vertex : sortedVertices) { - if (colors[vertex] == -1) { - boolean[] usedColors = computeUsedColors(graph, vertex, colors); - colors[vertex] = firstUnusedColor(usedColors); + if (colors[vertex] != -1) { + continue; // Skip if already colored (including pre-colored) + } + + // Determine used colors among adjacent vertices + boolean[] usedColors = computeUsedColors(graph, vertex, colors); + + colors[vertex] = firstUnusedColor(usedColors); + } + + // Ensure every vertex is colored + for (int i = 0; i < numVertices; i++) { + if (colors[i] == -1) { + colors[i] = firstUnusedColor(new boolean[numVertices]); } } + return colors; } + // Overloaded method for normal use without pre-coloring + public static int[] findColoring(Graph graph) { + return findColoring(graph, -1, -1); + } + private static int[] initializeColors(int numberOfVerticies) { int[] colors = new int[numberOfVerticies]; Arrays.fill(colors, -1); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java index 30cc773e409f..4b042f387f38 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java @@ -60,6 +60,25 @@ void testInvalidEdgeArray() { assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0}}); }, "Edge array must have exactly two elements"); } + @Test + void testWithPreColoredVertex() { + final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); + // Simulate pre-coloring vertex 1 with color 0 + int[] colors = WelshPowell.findColoring(graph, 1, 0); + assertTrue(isColoringValid(graph, colors)); + + // Ensure that the pre-colored vertex retains its color + assertEquals(0, colors[1]); + + // Check if other vertices are colored correctly + assertTrue(countDistinctColors(colors) >= 2); + + // Additional check to ensure that all vertices are colored + for (int color : colors) { + assertTrue(color >= 0); + } + } + private boolean isColoringValid(Graph graph, int[] colors) { for (int i = 0; i < graph.getNumVertices(); i++) { for (int neighbor : graph.getAdjList(i)) { From 016b561f3ef7f7f5f341f642af07badf530bbb73 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Fri, 9 Feb 2024 11:26:10 +0200 Subject: [PATCH 20/22] reverted the findColoring --- .../datastructures/graphs/WelshPowell.java | 40 ++++++------------- .../graphs/WelshPowellTest.java | 2 +- 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 8f69b3154e02..95cc0bca6709 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -63,40 +63,26 @@ public static Graph makeGraph(int numberOfVertices, int[][] listOfEdges) { return graph; } - public static int[] findColoring(Graph graph, int preColoredVertex, int preColor) { - int numVertices = graph.getNumVertices(); - int[] colors = initializeColors(numVertices); - - if (preColoredVertex >= 0 && preColoredVertex < numVertices && preColor >= 0) { - colors[preColoredVertex] = preColor; - } - + public static int[] findColoring(Graph graph) { + int[] colors = initializeColors(graph.getNumVertices()); Integer[] sortedVertices = getSortedNodes(graph); - for (int vertex : sortedVertices) { - if (colors[vertex] != -1) { - continue; // Skip if already colored (including pre-colored) - } - - // Determine used colors among adjacent vertices - boolean[] usedColors = computeUsedColors(graph, vertex, colors); - - colors[vertex] = firstUnusedColor(usedColors); - } - - // Ensure every vertex is colored - for (int i = 0; i < numVertices; i++) { - if (colors[i] == -1) { - colors[i] = firstUnusedColor(new boolean[numVertices]); + if (colors[vertex] == -1) { + boolean[] usedColors = computeUsedColors(graph, vertex, colors); + final var newColor = firstUnusedColor(usedColors); + colors[vertex] = newColor; + Arrays.stream(sortedVertices).forEach(otherVertex -> { + if (colors[otherVertex] == -1 && !isAdjacentToColored(graph, otherVertex, colors)) { + colors[otherVertex] = newColor; + } + }); } } - return colors; } - // Overloaded method for normal use without pre-coloring - public static int[] findColoring(Graph graph) { - return findColoring(graph, -1, -1); + private static boolean isAdjacentToColored(Graph graph, int vertex, int[] colors) { + return graph.getAdjList(vertex).stream().anyMatch(otherVertex -> colors[otherVertex] != -1); } private static int[] initializeColors(int numberOfVerticies) { diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java index 4b042f387f38..4a79a910e7b4 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java @@ -64,7 +64,7 @@ void testInvalidEdgeArray() { void testWithPreColoredVertex() { final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); // Simulate pre-coloring vertex 1 with color 0 - int[] colors = WelshPowell.findColoring(graph, 1, 0); + int[] colors = WelshPowell.findColoring(graph); assertTrue(isColoringValid(graph, colors)); // Ensure that the pre-colored vertex retains its color From a55e7ebc876f97435bd14d8f71364a58844468c6 Mon Sep 17 00:00:00 2001 From: Nikos Strafiotis Date: Mon, 12 Feb 2024 20:13:57 +0200 Subject: [PATCH 21/22] added more complex test, blank color method --- .../datastructures/graphs/WelshPowell.java | 24 +++++---- .../graphs/WelshPowellTest.java | 50 +++++++++++++++---- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index 95cc0bca6709..f951ecc7e9b9 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -12,6 +12,8 @@ */ public final class WelshPowell { + private static final int BLANK_COLOR = -1; // Representing uncolored state + private WelshPowell() { } @@ -43,7 +45,7 @@ private void validateVertex(int vertex) { } } - HashSet getAdjList(int vertex) { + HashSet getAdjacencyList(int vertex) { return adjacencyLists[vertex]; } @@ -67,12 +69,12 @@ public static int[] findColoring(Graph graph) { int[] colors = initializeColors(graph.getNumVertices()); Integer[] sortedVertices = getSortedNodes(graph); for (int vertex : sortedVertices) { - if (colors[vertex] == -1) { + if (isBlank(colors[vertex])) { boolean[] usedColors = computeUsedColors(graph, vertex, colors); final var newColor = firstUnusedColor(usedColors); colors[vertex] = newColor; Arrays.stream(sortedVertices).forEach(otherVertex -> { - if (colors[otherVertex] == -1 && !isAdjacentToColored(graph, otherVertex, colors)) { + if (isBlank(colors[otherVertex]) && !isAdjacentToColored(graph, otherVertex, colors)) { colors[otherVertex] = newColor; } }); @@ -81,23 +83,27 @@ public static int[] findColoring(Graph graph) { return colors; } + private static boolean isBlank(int color) { + return color == BLANK_COLOR; + } + private static boolean isAdjacentToColored(Graph graph, int vertex, int[] colors) { - return graph.getAdjList(vertex).stream().anyMatch(otherVertex -> colors[otherVertex] != -1); + return graph.getAdjacencyList(vertex).stream().anyMatch(otherVertex -> colors[otherVertex] != -1); } - private static int[] initializeColors(int numberOfVerticies) { - int[] colors = new int[numberOfVerticies]; - Arrays.fill(colors, -1); + private static int[] initializeColors(int numberOfVertices) { + int[] colors = new int[numberOfVertices]; + Arrays.fill(colors, BLANK_COLOR); return colors; } private static Integer[] getSortedNodes(final Graph graph) { - return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjList(v).size())).toArray(Integer[] ::new); + return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjacencyList(v).size())).toArray(Integer[] ::new); } private static boolean[] computeUsedColors(final Graph graph, final int vertex, final int[] colors) { boolean[] usedColors = new boolean[graph.getNumVertices()]; - graph.getAdjList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); + graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); return usedColors; } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java index 4a79a910e7b4..b37657db5c05 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java @@ -1,6 +1,8 @@ package com.thealgorithms.datastructures.graphs; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.datastructures.graphs.WelshPowell.Graph; import java.util.Arrays; @@ -32,12 +34,33 @@ void testCompleteGraph() { assertEquals(3, countDistinctColors(colors)); } + // The following test originates from the following website : https://www.geeksforgeeks.org/welsh-powell-graph-colouring-algorithm/ @Test void testComplexGraph() { - final var graph = WelshPowell.makeGraph(5, new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {1, 3}}); + int[][] edges = { + {0, 7}, // A-H + {0, 1}, // A-B + {1, 3}, // B-D + {2, 3}, // C-D + {3, 8}, // D-I + {3, 10}, // D-K + {4, 10}, // E-K + {4, 5}, // E-F + {5, 6}, // F-G + {6, 10}, // G-K + {6, 7}, // G-H + {7, 8}, // H-I + {7, 9}, // H-J + {7, 10}, // H-K + {8, 9}, // I-J + {9, 10}, // J-K + }; + + final var graph = WelshPowell.makeGraph(11, edges); // 11 vertices from A (0) to K (10) int[] colors = WelshPowell.findColoring(graph); - assertTrue(isColoringValid(graph, colors)); - assertEquals(3, countDistinctColors(colors)); // Expect exactly 3 colors + + assertTrue(isColoringValid(graph, colors), "The coloring should be valid with no adjacent vertices sharing the same color."); + assertEquals(3, countDistinctColors(colors), "The chromatic number of the graph should be 3."); } @Test @@ -53,6 +76,7 @@ void testSelfLoop() { @Test void testInvalidVertex() { assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, 3}}); }, "Vertex out of bounds"); + assertThrows(IllegalArgumentException.class, () -> { WelshPowell.makeGraph(3, new int[][] {{0, -1}}); }, "Vertex out of bounds"); } @Test @@ -62,26 +86,30 @@ void testInvalidEdgeArray() { @Test void testWithPreColoredVertex() { + // Create a linear graph with 4 vertices and edges connecting them in sequence final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}}); - // Simulate pre-coloring vertex 1 with color 0 + + // Apply the Welsh-Powell coloring algorithm to the graph int[] colors = WelshPowell.findColoring(graph); - assertTrue(isColoringValid(graph, colors)); - // Ensure that the pre-colored vertex retains its color - assertEquals(0, colors[1]); + // Validate that the coloring is correct (no two adjacent vertices have the same color) + assertTrue(isColoringValid(graph, colors)); - // Check if other vertices are colored correctly + // Check if the algorithm has used at least 2 colors (expected for a linear graph) assertTrue(countDistinctColors(colors) >= 2); - // Additional check to ensure that all vertices are colored + // Verify that all vertices have been assigned a color for (int color : colors) { assertTrue(color >= 0); } } private boolean isColoringValid(Graph graph, int[] colors) { + if (Arrays.stream(colors).anyMatch(n -> n < 0)) { + return false; + } for (int i = 0; i < graph.getNumVertices(); i++) { - for (int neighbor : graph.getAdjList(i)) { + for (int neighbor : graph.getAdjacencyList(i)) { if (i != neighbor && colors[i] == colors[neighbor]) { return false; // Adjacent vertices have the same color } From 90288e7d21cdcb1eda4d02b1b9bdce36f0508117 Mon Sep 17 00:00:00 2001 From: vil02 Date: Mon, 12 Feb 2024 20:38:24 +0100 Subject: [PATCH 22/22] refactor: use `isBlank` --- .../com/thealgorithms/datastructures/graphs/WelshPowell.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java index f951ecc7e9b9..3b823f02388d 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java @@ -88,7 +88,7 @@ private static boolean isBlank(int color) { } private static boolean isAdjacentToColored(Graph graph, int vertex, int[] colors) { - return graph.getAdjacencyList(vertex).stream().anyMatch(otherVertex -> colors[otherVertex] != -1); + return graph.getAdjacencyList(vertex).stream().anyMatch(otherVertex -> !isBlank(colors[otherVertex])); } private static int[] initializeColors(int numberOfVertices) { @@ -103,7 +103,7 @@ private static Integer[] getSortedNodes(final Graph graph) { private static boolean[] computeUsedColors(final Graph graph, final int vertex, final int[] colors) { boolean[] usedColors = new boolean[graph.getNumVertices()]; - graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> color != -1).forEach(color -> usedColors[color] = true); + graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> !isBlank(color)).forEach(color -> usedColors[color] = true); return usedColors; }