Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add graph algorithms- hamiltonian cycle(for issue#286) and add Comb Sort algorithm(issue #326) #345

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package com.williamfiset.algorithms.graphtheory;

import java.util.List;
import java.util.Scanner;
import java.util.Arrays;

public class HamiltonianCycle {
/**elements used to store path and the graph **/
private int V, pathCount;
private int[] path;
private int[][] graph;

public void setGraph(int[][] graph1){
this.graph=graph1;
}

public int[] getPath(){
return this.path;
}
/** Function to find cycle
* Take the graph as input
* And will print "No solution" if the graph has no HamiltionianCycle
* Function solve will do actual find paths job
* **/
public void findHamiltonianCycle(int[][] g)
{
if(g==null)throw new IllegalArgumentException("Graph cannot be null.");
V = g.length;
path = new int[V+1];
Arrays.fill(path, -1);
graph = g;
try
{
path[0] = 0;
pathCount = 1;
solve(0);
System.out.print("No solution");
}
catch (Exception e)
{
path[V]=path[0];
System.out.println(e.getMessage());
display();
}
}

/** function to find paths recursively
*Take int as input
*Will add coordinators into the path list.
* **/
public void solve(int vertex) throws Exception
{
/** solution **/
if (graph[vertex][0] == 1 && pathCount == V)
throw new Exception("Solution found");
/** all vertices selected but last vertex not linked to 0 **/
if (pathCount == V)
return;
for (int v = 0; v < V; v++)
{
/** if connected **/
if (graph[vertex][v] == 1)
{
/** add to path **/
path[pathCount++] = v;
/** remove connection **/
graph[vertex][v] = 0;
graph[v][vertex] = 0;
/** if vertex not already selected solve recursively **/
if (!isPresent(v))
solve(v);
/** restore connection **/
graph[vertex][v] = 1;
graph[v][vertex] = 1;
/** remove path **/
path[--pathCount] = -1;
}
}

}

/** function to check if path is already selected **/
public boolean isPresent(int v)
{
for (int i = 0; i < pathCount - 1; i++)
if (path[i] == v)
return true;
return false;
}

/** display solution **/
public void display()
{
System.out.print("\nPath : ");
for (int i = 0; i <= V; i++)
System.out.print(path[i % V] + " ");
System.out.println();
}

/** Main function **/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/** Make an object of HamiltonianCycle class **/
HamiltonianCycle hc = new HamiltonianCycle();
/** Accept number of vertices **/
System.out.println("Enter number of vertices");
int V = scan.nextInt();
/** get graph **/
System.out.println("Enter adjacency matrix");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = scan.nextInt();
hc.findHamiltonianCycle(graph);
scan.close();
}
}

74 changes: 74 additions & 0 deletions src/main/java/com/williamfiset/algorithms/sorting/CombSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.williamfiset.algorithms.sorting;

import java.util.Scanner;

class CombSort
{
// To find gap between elements
int getNextGap(int gap)
{
// Shrink gap by Shrink factor
gap = (gap*10)/13;
if (gap < 1)
return 1;
return gap;
}

// Function to sort arr[] using Comb Sort
void sort(int arr[])
{
int n = arr.length;

// initialize gap
int gap = n;

// Initialize swapped as true to make sure that
// loop runs
boolean swapped = true;

// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);

// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;

// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (arr[i] > arr[i+gap])
{
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;

// Set swapped
swapped = true;
}
}
}
}

// Driver method
public static void main(String args[])
{
CombSort ob = new CombSort();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of the numbers you want to sort");
int V = scan.nextInt();
System.out.println("Enter the numbers:");
int[] arr = new int[V];
for (int i=0;i<V;i++)
arr[i]=scan.nextInt();
ob.sort(arr);
System.out.println("sorted array");
for (int i=0; i<arr.length; ++i)
System.out.print(arr[i] + " ");

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.williamfiset.algorithms.graphtheory;

import org.junit.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.*;

import static com.google.common.truth.Truth.assertThat;

public class HamiltonianCycleTest {

HamiltonianCycle solver;

@Before
public void setUp() {
solver = null;
}

// Initialize graph with 'n' nodes.
public static int[][] initializeEmptyGraph() {
int[][] graph = null;
return graph;
}

// Add directed edge to graph.
public static void addDirectedEdge(int[][] graph, int a, int b) {
graph[a][b]=1;
}

//test empty
@Test(expected = IllegalArgumentException.class)
public void testEmptyGraph() {
int[][] graph = initializeEmptyGraph();
HamiltonianCycle solver;
solver = new HamiltonianCycle();
solver.setGraph(graph);
solver.findHamiltonianCycle(graph);
}

//valid test 1
@Test
public void validHC1() {
int[][] graph = new int[5][5];
int[] result= new int[6];
result[0]=0;result[1]=1;result[2]=2;result[3]=4;result[4]=3;result[5]=0;
/**
* the example graph
* (0)--(1)--(2)
* | / \ |
* | / \ |
* | / \ |
* (3)-------(4)
*
* the 2D should be
* 0 1 0 1 0
* 1 0 1 1 1
* 0 1 0 0 1
* 1 1 0 0 1
* 0 1 1 1 0
*
*/
graph [0][0]=0;graph [0][1]=1;graph [0][2]=0;graph [0][3]=1;graph [0][4]=0;
graph [1][0]=1;graph [1][1]=0;graph [1][2]=1;graph [1][3]=1;graph [1][4]=1;
graph [2][0]=0;graph [2][1]=1;graph [2][2]=0;graph [2][3]=0;graph [2][4]=1;
graph [3][0]=1;graph [3][1]=1;graph [3][2]=0;graph [3][3]=0;graph [3][4]=1;
graph [4][0]=0;graph [4][1]=1;graph [4][2]=1;graph [4][3]=1;graph [4][4]=0;
HamiltonianCycle solver;
solver = new HamiltonianCycle();
solver.setGraph(graph);
solver.findHamiltonianCycle(graph);
assertThat(solver.getPath()).isEqualTo(result);
}

//invalid test 1, generally same as valid 1, but change a little and make it invalid
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;

@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}

@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
public void invalidHC1() {
int[][] graph = new int[5][5];
int[] invalidresult= new int[6];
Arrays.fill(invalidresult, -1);
/**
* the example graph
* (0)--(1)--(2)
* | / \ |
* | / \ |
* | / \ |
* (3) (4)
*
* the 2D should be
* 0 1 0 1 0
* 1 0 1 1 1
* 0 1 0 0 1
* 1 1 0 0 0
* 0 1 1 0 0
*
*/
graph [0][0]=0;graph [0][1]=1;graph [0][2]=0;graph [0][3]=1;graph [0][4]=0;
graph [1][0]=1;graph [1][1]=0;graph [1][2]=1;graph [1][3]=1;graph [1][4]=1;
graph [2][0]=0;graph [2][1]=1;graph [2][2]=0;graph [2][3]=0;graph [2][4]=1;
graph [3][0]=1;graph [3][1]=1;graph [3][2]=0;graph [3][3]=0;graph [3][4]=0;
graph [4][0]=0;graph [4][1]=1;graph [4][2]=1;graph [4][3]=0;graph [4][4]=0;
HamiltonianCycle solver;
solver = new HamiltonianCycle();
solver.setGraph(graph);
solver.findHamiltonianCycle(graph);
Assert.assertEquals("No solution",outContent.toString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.williamfiset.algorithms.sorting;

import org.junit.Test;

import java.util.Arrays;
import java.util.Random;

import static com.google.common.truth.Truth.assertThat;

public class CombSortTest {
static Random random = new Random();

CombSort ob = new CombSort();

@Test
public void randomCombSort_smallNumbers() {
for (int size = 0; size < 1000; size++) {
int[] values = new int[size];
for (int i = 0; i < size; i++) {
values[i] = randInt(1, 50);
}
int[] copy = values.clone();

Arrays.sort(values);
ob.sort(copy);
assertThat(values).isEqualTo(copy);
}
}

@Test
public void randomRadixSort_largeNumbers() {
for (int size = 0; size < 1000; size++) {
int[] values = new int[size];
for (int i = 0; i < size; i++) {
values[i] = randInt(1, Integer.MAX_VALUE);
}
int[] copy = values.clone();

Arrays.sort(values);
ob.sort(copy);

assertThat(values).isEqualTo(copy);
}
}

// return a random number between [min, max]
static int randInt(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
}