Posts

tsp genetic

  import java . util .*; class TravellingSalesmanGenetic {     // Constants     static final int POPULATION_SIZE = 100 ; // Size of population     static final int NUM_GENERATIONS = 1000 ; // Number of generations     static final double MUTATION_RATE = 0.05 ; // Mutation rate     // Cities' coordinates (e.g., a small example for TSP)     static final int [][] cities = {         { 0 , 0 }, { 1 , 3 }, { 4 , 3 }, { 6 , 1 }, { 3 , 2 }, { 5 , 4 }, { 7 , 8 }     };     public static void main( String [] args ) {         TravellingSalesmanGenetic tsp = new TravellingSalesmanGenetic();         tsp.solveTSP(cities);     }     // Solve TSP using Genetic Algorithm     public void solveTSP( int [][] cities ) {         List < int []> population = initializePopulation( cities .leng...

tsp bb

  import java . util . Arrays ; import java.util. PriorityQueue ; class TravellingSalesman {     static class Node implements Comparable < Node > {         int level;         int [] path;         int bound;         int cost;         Node( int level , int [] path , int bound , int cost ) {             this .level = level ;             this .path = Arrays .copyOf( path , path .length);             this .bound = bound ;             this .cost = cost ;         }         @ Override         public int compareTo( Node o ) {             return Integer .compare( this .bound, o .bound);         }     }       ...

nqueens

  import java . util . ArrayList ; import java.util. List ; public class NQueens {         public static List < List < String >> solveNQueens( int n ) {         List < List < String >> solutions = new ArrayList<>();         char [][] board = new char [ n ][ n ];                 for ( int i = 0 ; i < n ; i++) {             for ( int j = 0 ; j < n ; j++) {                 board[i][j] = '.' ;             }         }         placeQueens(solutions, board, 0 , n );         return solutions;     }         private static void placeQueens( List < List < String >> solutions , char [][] board , int row , int n ) {        ...

knasack

 knapsack import java.util. ArrayList ; import java.util. List ; public class KnapsackDP {         public static int knapsack( int [] values , int [] weights , int capacity ) {         int n = values .length;         int [][] dp = new int [n + 1 ][ capacity + 1 ];         // Build dp table         for ( int i = 1 ; i <= n; i++) {             for ( int w = 1 ; w <= capacity ; w++) {                 if ( weights [i - 1 ] <= w) {                     dp[i][w] = Math .max(dp[i - 1 ][w], dp[i - 1 ][w - weights [i - 1 ]] + values [i - 1 ]);                 } else {                     dp[i][w] = dp[i - 1 ][w];              ...