Question: did i do the two classes correctly? 1 . inexactVC. This algorithm will find non - optimal vertex covers, but must run in polynomial time.

did i do the two classes correctly?
1. inexactVC. This algorithm will find non-optimal vertex covers, but must run in polynomial time. Your solution cannot be trivial (e.g., the set of all vertices is a trivial VC).
2. inexactIS. This algorithm will find non-optimal independent sets, but must run in
polynomial time. Your solution cannot be trivial (e.g., the set of no vertices is a trivial IS).
public class Graph {
// return (in polynomial time) an array containing the vertex numbers of a VC.
public static int[] inexactVC(Graph inputGraph){
int[][] graph = inputGraph.getGraph();
boolean[] coveredEdges = new boolean[graph.length];
List vertexCover = new ArrayList<>();
// Loop over all vertices
for (int i =0; i < graph.length; i++){
for (int neighbor : graph[i]){
if (!coveredEdges[i] && !coveredEdges[neighbor]){
vertexCover.add(i);
vertexCover.add(neighbor);
coveredEdges[i]= true;
coveredEdges[neighbor]= true;
break; // Move to the next vertex once an edge is covered
}
}
}
// Return the vertex cover as an array
return vertexCover.stream().mapToInt(Integer::intValue).toArray();
}
public static int[] inexactIS(Graph inputGraph){
int[][] adjacencyList = inputGraph.getGraph();
int n = adjacencyList.length;
// Initialize the independent set array (1 means selected, 0 means not selected)
int[] independentSet = new int[n];
Arrays.fill(independentSet,0); // Start with an empty independent set
// To keep track of selected vertices and their neighbors
boolean[] inSet = new boolean[n]; // Whether a vertex is in the independent set
// Iterate over all vertices and add to the independent set if possible
for (int vertex =0; vertex < n; vertex++){
if (!inSet[vertex]){// If vertex is not already in the independent set
// Add the vertex to the independent set
independentSet[vertex]=1;
inSet[vertex]= true;
// Mark all neighbors of the vertex as excluded
for (int neighbor : adjacencyList[vertex]){
inSet[neighbor]= true;
}
}
}
// Collect the vertices that are in the independent set
int setSize =0;
for (int i =0; i < n; i++){
if (independentSet[i]==1){
setSize++;
}
}
// Create a result array to store the independent set vertices
int[] result = new int[setSize];
int index =0;
for (int i =0; i < n; i++){
if (independentSet[i]==1){
result[index++]= i;
}
}
System.out.println("Inexact Independent Set found: "+ Arrays.toString(result));
return result;
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!