import  java.net.URL;
import  java.net.URLConnection;
import  java.io.*;
import  java.util.*;

public class GetRCLanguages
{
    // Custom sort Comparator for sorting the language list
    // assumes the first character is the page count and the rest is the language name
    private static class LanguageComparator implements Comparator<String>
    {
        public int compare( String a, String b )
        {
            // as we "know" we will be comparaing languages, we will assume the Strings have the appropriate format
            int result = ( b.charAt( 0 ) - a.charAt( 0 ) );
            if( result == 0 )
            {
                // the counts are the same - compare the names
                result = a.compareTo( b );
            } // if result == 0
        return result;
        } // compare
    } // LanguageComparator

    // get the string following marker in text
    private static String after( String text, int marker )
    {
        String result = "";
        int    pos    = text.indexOf( marker );
        if( pos >= 0 )
        {
            // the marker is in the string
            result = text.substring( pos + 1 );
        } // if pos >= 0
    return result;
    } // after

    // read and parse the content of path
    // results returned in gcmcontinue and languageList
    public static void parseContent( String path
                                   , String[] gcmcontinue
                                   , ArrayList<String> languageList
                                   )
    {
        try
        {

            URL            url = new URL( path );
            URLConnection  rc  = url.openConnection();
            // Rosetta Code objects to the default Java user agant so use a blank one
            rc.setRequestProperty( "User-Agent", "" );
            BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );

            gcmcontinue[0]      = "";
            String languageName = "?";
            String line         = bfr.readLine();
            while( line != null )
            {
                line = line.trim();
                if     ( line.startsWith( "[title]" ) )
                {
                    // have a programming language - should look like "[title] => Category:languageName"
                    languageName = after( line, ':' ).trim();
                }
                else if( line.startsWith( "[pages]" ) )
                {
                    // number of pages the language has (probably)
                    String pageCount = after( line, '>' ).trim();
                    if( pageCount.compareTo( "Array" ) != 0 )
                    {
                        // haven't got "[pages] => Array" - must be a number of pages
                        languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );
                        languageName = "?";
                    } // if [pageCount.compareTo( "Array" ) != 0
                }
                else if( line.startsWith( "[gcmcontinue]" ) )
                {
                    // have an indication of wether there is more data or not
                    gcmcontinue[0] = after( line, '>' ).trim();
                } // if various line starts
                line = bfr.readLine();
            } // while line != null
            bfr.close();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        } // try-catch
    } // parseContent

    public static void main( String[] args )
    {
        // get the languages
        ArrayList<String> languageList = new ArrayList<String>( 1000 );
        String[]          gcmcontinue  = new String[1];
        gcmcontinue[0]                 = "";
        do
        {
            String path = ( "http://www.rosettacode.org/mw/api.php?action=query"
                          + "&generator=categorymembers"
                          + "&gcmtitle=Category:Programming%20Languages"
                          + "&gcmlimit=500"
                          + ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) )
                          + "&prop=categoryinfo"
                          + "&format=txt"
                          );
            parseContent( path, gcmcontinue, languageList );
        }
        while( gcmcontinue[0].compareTo( "" ) != 0 );
        // sort the languages
        String[] languages = languageList.toArray(new String[]{});
        Arrays.sort( languages, new LanguageComparator() );
        // print the languages
        int    lastTie    = -1;
        int    lastCount  = -1;
        for( int lPos = 0; lPos < languages.length; lPos ++ )
        {
            int    count = (int) ( languages[ lPos ].charAt( 0 ) );
            System.out.format( "%4d: %4d: %s\n"
                             , 1 + ( count == lastCount ? lastTie : lPos )
                             , count
                             , languages[ lPos ].substring( 1 )
                             );
            if( count != lastCount )
            {
                lastTie   = lPos;
                lastCount = count;
            } // if count != lastCount
        } // for lPos
    } // main
} // GetRCLanguages

The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data either through web scraping or the API method. The code also has the option to filter incorrect results. The final output is a complete ranked list of all programming languages.


Works with: Java version 1.5+
Iterable<Type> collect;
...
for(Type i:collect){
   System.out.println(i);
}

Works with: Java version 1.8+
Iterable collect;
...
collect.forEach(o -> System.out.println(o));

Iterates and prints each element in a collection in order using a "for each" loop or another loop if "for each" is not available. It works with any Iterable and all Collections, but not with arrays.


Works with: Java version 1.0+

Works with: Java version 1.8+
String toTokenize = "Hello,How,Are,You,Today";
System.out.println(String.join(".", toTokenize.split(",")));

Works with: Java version 1.4+
String toTokenize = "Hello,How,Are,You,Today";

String words[] = toTokenize.split(",");//splits on one comma, multiple commas yield multiple splits
               //toTokenize.split(",+") if you want to ignore empty fields
for(int i=0; i<words.length; i++) {
    System.out.print(words[i] + ".");
}

Works with: Java version 1.0+
String toTokenize = "Hello,How,Are,You,Today";

StringTokenizer tokenizer = new StringTokenizer(toTokenize, ",");
while(tokenizer.hasMoreTokens()) {
    System.out.print(tokenizer.nextToken() + ".");
}

Tokenizes a given string by splitting it at commas into an array, and then displays the words separated by a period. The code utilizes either the split method with regex or the StringTokenizer class, the latter of which skips any empty tokens.


/* recursive */
int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}

public static long gcd(long a, long b){
   long factor= Math.min(a, b);
   for(long loop= factor;loop > 1;loop--){
      if(a % loop == 0 && b % loop == 0){
         return loop;
      }
   }
   return 1;
}

public static int gcd(int a, int b) //valid for positive integers.
{
	while(b > 0)
	{
		int c = a % b;
		a = b;
		b = c;
	}
	return a;
}

Optimized static int gcd(int a,int b)
	{
		int min=a>b?b:a,max=a+b-min, div=min;
		for(int i=1;i<min;div=min/++i)
			if(min%div==0&&max%div==0)
				return div;
		return 1;
	}
public static long gcd(long u, long v){
  long t, k;

  if (v == 0) return u;

  u = Math.abs(u);
  v = Math.abs(v);
  if (u < v){
    t = u;
    u = v;
    v = t;
  }

  for(k = 1; (u & 1) == 0 && (v & 1) == 0; k <<= 1){
    u >>= 1; v >>= 1;
  }

  t = (u & 1) != 0 ? -v : u;
  while (t != 0){
    while ((t & 1) == 0) t >>= 1;

    if (t > 0)
      u = t;
    else
      v = -t;

    t = u - v;
  }
  return u * k;
}

public static long gcd(long a, long b){
   if(a == 0) return b;
   if(b == 0) return a;
   if(a > b) return gcd(b, a % b);
   return gcd(a, b % a);
}

import java.math.BigInteger;

public static long gcd(long a, long b){
   return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue();
}

implement a function to find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. This is related to finding the least common multiple. Refer to MathWorld and Wikipedia for more information on the greatest common divisor. The code uses javax.swing.table.DefaultTableModel.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


Integer.parseInt("12345")

Float.parseFloat("123.456")

public static void main(String[] args) {
    String value;
    value = "1234567";
    System.out.printf("%-10s %b%n", value, isInteger(value));
    value = "12345abc";
    System.out.printf("%-10s %b%n", value, isInteger(value));
    value = "-123.456";
    System.out.printf("%-10s %b%n", value, isFloatingPoint(value));
    value = "-.456";
    System.out.printf("%-10s %b%n", value, isFloatingPoint(value));
    value = "123.";
    System.out.printf("%-10s %b%n", value, isFloatingPoint(value));
    value = "123.abc";
    System.out.printf("%-10s %b%n", value, isFloatingPoint(value));
}

static boolean isInteger(String string) {
    String digits = "0123456789";
    for (char character : string.toCharArray()) {
        if (!digits.contains(String.valueOf(character)))
            return false;
    }
    return true;
}

static boolean isFloatingPoint(String string) {
    /* at least one decimal-point */
    int indexOf = string.indexOf('.');
    if (indexOf == -1)
        return false;
    /* assure only 1 decimal-point */
    if (indexOf != string.lastIndexOf('.'))
        return false;
    if (string.charAt(0) == '-' || string.charAt(0) == '+') {
        string = string.substring(1);
        indexOf--;
    }
    String integer = string.substring(0, indexOf);
    if (!integer.isEmpty()) {
        if (!isInteger(integer))
            return false;
    }
    String decimal = string.substring(indexOf + 1);
    if (!decimal.isEmpty())
        return isInteger(decimal);
    return true;
}

1234567    true
12345abc   false
-123.456   true
-.456      true
123.       true
123.abc    false

public boolean isNumeric(String input) {
  try {
    Integer.parseInt(input);
    return true;
  }
  catch (NumberFormatException e) {
    // s is not numeric
    return false;
  }
}

private static final boolean isNumeric(final String s) {
  if (s == null || s.isEmpty()) return false;
  for (int x = 0; x < s.length(); x++) {
    final char c = s.charAt(x);
    if (x == 0 && (c == '-')) continue;  // negative
    if ((c >= '0') && (c <= '9')) continue;  // 0 - 9
    return false; // invalid
  }
  return true; // valid
}

public static boolean isNumeric(String inputData) {
  return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}

public static boolean isNumeric(String inputData) {
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition pos = new ParsePosition(0);
  formatter.parse(inputData, pos);
  return inputData.length() == pos.getIndex();
}

public static boolean isNumeric(String inputData) {
  Scanner sc = new Scanner(inputData);
  return sc.hasNextInt();
}

The code defines a boolean function to check if a given string is numeric, including floating point and negative numbers. It uses different alternatives such as parsing methods from Integer, Long, Float, or Double class, checking each character in the string, using a regular expression, using the positional parser in the java.text.NumberFormat object, and using the java.util.Scanner object. It also handles exceptions and considers performance implications.


URL url = new URL("https://sourceforge.net");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;

public class Main {
    public static void main(String[] args) {
        var request = HttpRequest.newBuilder(URI.create("https://sourceforge.net"))
                .GET()
                .build();

        HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()))
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println)
                .join();
    }
}

send a GET request to the URL "https://www.w3.org/" and print the response to the console without authentication, also check the host certificate for validity using Java 11 HTTP Client and javax.net.ssl.HttpsURLConnection interface.


Works with: Java version 7
import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;

public class SutherlandHodgman extends JFrame {

    SutherlandHodgmanPanel panel;

    public static void main(String[] args) {
        JFrame f = new SutherlandHodgman();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    public SutherlandHodgman() {
        Container content = getContentPane();
        content.setLayout(new BorderLayout());
        panel = new SutherlandHodgmanPanel();
        content.add(panel, BorderLayout.CENTER);
        setTitle("SutherlandHodgman");
        pack();
        setLocationRelativeTo(null);
    }
}

class SutherlandHodgmanPanel extends JPanel {
    List<double[]> subject, clipper, result;

    public SutherlandHodgmanPanel() {
        setPreferredSize(new Dimension(600, 500));

        // these subject and clip points are assumed to be valid
        double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},
        {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};

        double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};

        subject = new ArrayList<>(Arrays.asList(subjPoints));
        result  = new ArrayList<>(subject);
        clipper = new ArrayList<>(Arrays.asList(clipPoints));

        clipPolygon();
    }

    private void clipPolygon() {
        int len = clipper.size();
        for (int i = 0; i < len; i++) {

            int len2 = result.size();
            List<double[]> input = result;
            result = new ArrayList<>(len2);

            double[] A = clipper.get((i + len - 1) % len);
            double[] B = clipper.get(i);

            for (int j = 0; j < len2; j++) {

                double[] P = input.get((j + len2 - 1) % len2);
                double[] Q = input.get(j);

                if (isInside(A, B, Q)) {
                    if (!isInside(A, B, P))
                        result.add(intersection(A, B, P, Q));
                    result.add(Q);
                } else if (isInside(A, B, P))
                    result.add(intersection(A, B, P, Q));
            }
        }
    }

    private boolean isInside(double[] a, double[] b, double[] c) {
        return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);
    }

    private double[] intersection(double[] a, double[] b, double[] p, double[] q) {
        double A1 = b[1] - a[1];
        double B1 = a[0] - b[0];
        double C1 = A1 * a[0] + B1 * a[1];

        double A2 = q[1] - p[1];
        double B2 = p[0] - q[0];
        double C2 = A2 * p[0] + B2 * p[1];

        double det = A1 * B2 - A2 * B1;
        double x = (B2 * C1 - B1 * C2) / det;
        double y = (A1 * C2 - A2 * C1) / det;

        return new double[]{x, y};
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.translate(80, 60);
        g2.setStroke(new BasicStroke(3));
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawPolygon(g2, subject, Color.blue);
        drawPolygon(g2, clipper, Color.red);
        drawPolygon(g2, result, Color.green);
    }

    private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {
        g2.setColor(color);
        int len = points.size();
        Line2D line = new Line2D.Double();
        for (int i = 0; i < len; i++) {
            double[] p1 = points.get(i);
            double[] p2 = points.get((i + 1) % len);
            line.setLine(p1[0], p1[1], p2[0], p2[1]);
            g2.draw(line);
        }
    }
}

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


Works with: Java version 8
import java.util.*;

public class RankingMethods {

    final static String[] input = {"44 Solomon", "42 Jason", "42 Errol",
        "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"};

    public static void main(String[] args) {
        int len = input.length;

        Map<String, int[]> map = new TreeMap<>((a, b) -> b.compareTo(a));
        for (int i = 0; i < len; i++) {
            String key = input[i].split("\\s+")[0];
            int[] arr;
            if ((arr = map.get(key)) == null)
                arr = new int[]{i, 0};
            arr[1]++;
            map.put(key, arr);
        }
        int[][] groups = map.values().toArray(new int[map.size()][]);

        standardRanking(len, groups);
        modifiedRanking(len, groups);
        denseRanking(len, groups);
        ordinalRanking(len);
        fractionalRanking(len, groups);
    }

    private static void standardRanking(int len, int[][] groups) {
        System.out.println("\nStandard ranking");
        for (int i = 0, rank = 0, group = 0; i < len; i++) {
            if (group < groups.length && i == groups[group][0]) {
                rank = i + 1;
                group++;
            }
            System.out.printf("%d %s%n", rank, input[i]);
        }
    }

    private static void modifiedRanking(int len, int[][] groups) {
        System.out.println("\nModified ranking");
        for (int i = 0, rank = 0, group = 0; i < len; i++) {
            if (group < groups.length && i == groups[group][0])
                rank += groups[group++][1];
            System.out.printf("%d %s%n", rank, input[i]);
        }
    }

    private static void denseRanking(int len, int[][] groups) {
        System.out.println("\nDense ranking");
        for (int i = 0, rank = 0; i < len; i++) {
            if (rank < groups.length && i == groups[rank][0])
                rank++;
            System.out.printf("%d %s%n", rank, input[i]);
        }
    }

    private static void ordinalRanking(int len) {
        System.out.println("\nOrdinal ranking");
        for (int i = 0; i < len; i++)
            System.out.printf("%d %s%n", i + 1, input[i]);
    }

    private static void fractionalRanking(int len, int[][] groups) {
        System.out.println("\nFractional ranking");
        float rank = 0;
        for (int i = 0, tmp = 0, group = 0; i < len; i++) {
            if (group < groups.length && i == groups[group][0]) {
                tmp += groups[group++][1];
                rank = (i + 1 + tmp) / 2.0F;
            }
            System.out.printf("%2.1f %s%n", rank, input[i]);
        }
    }
}

Standard ranking
1 44 Solomon
2 42 Jason
2 42 Errol
4 41 Garry
4 41 Bernard
4 41 Barry
7 39 Stephen

Modified ranking
1 44 Solomon
3 42 Jason
3 42 Errol
6 41 Garry
6 41 Bernard
6 41 Barry
7 39 Stephen

Dense ranking
1 44 Solomon
2 42 Jason
2 42 Errol
3 41 Garry
3 41 Bernard
3 41 Barry
4 39 Stephen

Ordinal ranking
1 44 Solomon
2 42 Jason
3 42 Errol
4 41 Garry
5 41 Bernard
6 41 Barry
7 39 Stephen

Fractional ranking
1,0 44 Solomon
2,5 42 Jason
2,5 42 Errol
5,0 41 Garry
5,0 41 Bernard
5,0 41 Barry
7,0 39 Stephen

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


public class Trig {
        public static void main(String[] args) {
                //Pi / 4 is 45 degrees. All answers should be the same.
                double radians = Math.PI / 4;
                double degrees = 45.0;
                //sine
                System.out.println(Math.sin(radians) + " " + Math.sin(Math.toRadians(degrees)));
                //cosine
                System.out.println(Math.cos(radians) + " " + Math.cos(Math.toRadians(degrees)));
                //tangent
                System.out.println(Math.tan(radians) + " " + Math.tan(Math.toRadians(degrees)));
                //arcsine
                double arcsin = Math.asin(Math.sin(radians));
                System.out.println(arcsin + " " + Math.toDegrees(arcsin));
                //arccosine
                double arccos = Math.acos(Math.cos(radians));
                System.out.println(arccos + " " + Math.toDegrees(arccos));
                //arctangent
                double arctan = Math.atan(Math.tan(radians));
                System.out.println(arctan + " " + Math.toDegrees(arctan));
        }
}

demonstrate the usage of trigonometric functions such as sine, cosine, tangent, and their inverses in a given programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian/degree pair. For inverse functions, the same number is used and its answer is converted to both radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. In the case of Java, the Math class, which contains all six functions and accepts only radians, is utilized.


package hu.pj.alg.test;

import hu.pj.alg.BoundedKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;

public class BoundedKnapsackForTourists {
    public BoundedKnapsackForTourists() {
        BoundedKnapsack bok = new BoundedKnapsack(400); // 400 dkg = 400 dag = 4 kg

        // making the list of items that you want to bring
        bok.add("map", 9, 150, 1);
        bok.add("compass", 13, 35, 1);
        bok.add("water", 153, 200, 3);
        bok.add("sandwich", 50, 60, 2);
        bok.add("glucose", 15, 60, 2);
        bok.add("tin", 68, 45, 3);
        bok.add("banana", 27, 60, 3);
        bok.add("apple", 39, 40, 3);
        bok.add("cheese", 23, 30, 1);
        bok.add("beer", 52, 10, 3);
        bok.add("suntan cream", 11, 70, 1);
        bok.add("camera", 32, 30, 1);
        bok.add("t-shirt", 24, 15, 2);
        bok.add("trousers", 48, 10, 2);
        bok.add("umbrella", 73, 40, 1);
        bok.add("waterproof trousers", 42, 70, 1);
        bok.add("waterproof overclothes", 43, 75, 1);
        bok.add("note-case", 22, 80, 1);
        bok.add("sunglasses", 7, 20, 1);
        bok.add("towel", 18, 12, 2);
        bok.add("socks", 4, 50, 1);
        bok.add("book", 30, 10, 2);

        // calculate the solution:
        List<Item> itemList = bok.calcSolution();

        // write out the solution in the standard output
        if (bok.isCalculated()) {
            NumberFormat nf  = NumberFormat.getInstance();

            System.out.println(
                "Maximal weight           = " +
                nf.format(bok.getMaxWeight() / 100.0) + " kg"
            );
            System.out.println(
                "Total weight of solution = " +
                nf.format(bok.getSolutionWeight() / 100.0) + " kg"
            );
            System.out.println(
                "Total value              = " +
                bok.getProfit()
            );
            System.out.println();
            System.out.println(
                "You can carry te following materials " +
                "in the knapsack:"
            );
            for (Item item : itemList) {
                if (item.getInKnapsack() > 0) {
                    System.out.format(
                        "%1$-10s %2$-23s %3$-3s %4$-5s %5$-15s \n",
                        item.getInKnapsack() + " unit(s) ",
                        item.getName(),
                        item.getInKnapsack() * item.getWeight(), "dag  ",
                        "(value = " + item.getInKnapsack() * item.getValue() + ")"
                    );
                }
            }
        } else {
            System.out.println(
                "The problem is not solved. " +
                "Maybe you gave wrong data."
            );
        }

    }

    public static void main(String[] args) {
        new BoundedKnapsackForTourists();
    }
} // class

package hu.pj.alg;

import hu.pj.obj.Item;
import java.util.*;

public class BoundedKnapsack extends ZeroOneKnapsack {
    public BoundedKnapsack() {}

    public BoundedKnapsack(int _maxWeight) {
        setMaxWeight(_maxWeight);
    }

    public BoundedKnapsack(List<Item> _itemList) {
        setItemList(_itemList);
    }

    public BoundedKnapsack(List<Item> _itemList, int _maxWeight) {
        setItemList(_itemList);
        setMaxWeight(_maxWeight);
    }

    @Override
    public List<Item> calcSolution() {
        int n = itemList.size();

        // add items to the list, if bounding > 1
        for (int i = 0; i < n; i++) {
            Item item = itemList.get(i);
            if (item.getBounding() > 1) {
                for (int j = 1; j < item.getBounding(); j++) {
                    add(item.getName(), item.getWeight(), item.getValue());
                }
            }
        }

        super.calcSolution();

        // delete the added items, and increase the original items
        while (itemList.size() > n) {
            Item lastItem = itemList.get(itemList.size() - 1);
            if (lastItem.getInKnapsack() == 1) {
                for (int i = 0; i < n; i++) {
                    Item iH = itemList.get(i);
                    if (lastItem.getName().equals(iH.getName())) {
                        iH.setInKnapsack(1 + iH.getInKnapsack());
                        break;
                    }
                }
            }
            itemList.remove(itemList.size() - 1);
        }

        return itemList;
    }

    // add an item to the item list
    public void add(String name, int weight, int value, int bounding) {
        if (name.equals(""))
            name = "" + (itemList.size() + 1);
        itemList.add(new Item(name, weight, value, bounding));
        setInitialStateForCalculation();
    }
} // class

package hu.pj.alg;

import hu.pj.obj.Item;
import java.util.*;

public class ZeroOneKnapsack {
    protected List<Item> itemList  = new ArrayList<Item>();
    protected int maxWeight        = 0;
    protected int solutionWeight   = 0;
    protected int profit           = 0;
    protected boolean calculated   = false;

    public ZeroOneKnapsack() {}

    public ZeroOneKnapsack(int _maxWeight) {
        setMaxWeight(_maxWeight);
    }

    public ZeroOneKnapsack(List<Item> _itemList) {
        setItemList(_itemList);
    }

    public ZeroOneKnapsack(List<Item> _itemList, int _maxWeight) {
        setItemList(_itemList);
        setMaxWeight(_maxWeight);
    }

    // calculte the solution of 0-1 knapsack problem with dynamic method:
    public List<Item> calcSolution() {
        int n = itemList.size();

        setInitialStateForCalculation();
        if (n > 0  &&  maxWeight > 0) {
            List< List<Integer> > c = new ArrayList< List<Integer> >();
            List<Integer> curr = new ArrayList<Integer>();

            c.add(curr);
            for (int j = 0; j <= maxWeight; j++)
                curr.add(0);
            for (int i = 1; i <= n; i++) {
                List<Integer> prev = curr;
                c.add(curr = new ArrayList<Integer>());
                for (int j = 0; j <= maxWeight; j++) {
                    if (j > 0) {
                        int wH = itemList.get(i-1).getWeight();
                        curr.add(
                            (wH > j)
                            ?
                            prev.get(j)
                            :
                            Math.max(
                                prev.get(j),
                                itemList.get(i-1).getValue() + prev.get(j-wH)
                            )
                        );
                    } else {
                        curr.add(0);
                    }
                } // for (j...)
            } // for (i...)
            profit = curr.get(maxWeight);

            for (int i = n, j = maxWeight; i > 0  &&  j >= 0; i--) {
                int tempI   = c.get(i).get(j);
                int tempI_1 = c.get(i-1).get(j);
                if (
                    (i == 0  &&  tempI > 0)
                    ||
                    (i > 0  &&  tempI != tempI_1)
                )
                {
                    Item iH = itemList.get(i-1);
                    int  wH = iH.getWeight();
                    iH.setInKnapsack(1);
                    j -= wH;
                    solutionWeight += wH;
                }
            } // for()
            calculated = true;
        } // if()
        return itemList;
    }

    // add an item to the item list
    public void add(String name, int weight, int value) {
        if (name.equals(""))
            name = "" + (itemList.size() + 1);
        itemList.add(new Item(name, weight, value));
        setInitialStateForCalculation();
    }

    // add an item to the item list
    public void add(int weight, int value) {
        add("", weight, value); // the name will be "itemList.size() + 1"!
    }

    // remove an item from the item list
    public void remove(String name) {
        for (Iterator<Item> it = itemList.iterator(); it.hasNext(); ) {
            if (name.equals(it.next().getName())) {
                it.remove();
            }
        }
        setInitialStateForCalculation();
    }

    // remove all items from the item list
    public void removeAllItems() {
        itemList.clear();
        setInitialStateForCalculation();
    }

    public int getProfit() {
        if (!calculated)
            calcSolution();
        return profit;
    }

    public int getSolutionWeight() {return solutionWeight;}
    public boolean isCalculated() {return calculated;}
    public int getMaxWeight() {return maxWeight;}

    public void setMaxWeight(int _maxWeight) {
        maxWeight = Math.max(_maxWeight, 0);
    }

    public void setItemList(List<Item> _itemList) {
        if (_itemList != null) {
            itemList = _itemList;
            for (Item item : _itemList) {
                item.checkMembers();
            }
        }
    }

    // set the member with name "inKnapsack" by all items:
    private void setInKnapsackByAll(int inKnapsack) {
        for (Item item : itemList)
            if (inKnapsack > 0)
                item.setInKnapsack(1);
            else
                item.setInKnapsack(0);
    }

    // set the data members of class in the state of starting the calculation:
    protected void setInitialStateForCalculation() {
        setInKnapsackByAll(0);
        calculated     = false;
        profit         = 0;
        solutionWeight = 0;
    }
} // class

package hu.pj.obj;

public class Item {
    protected String name    = "";
    protected int weight     = 0;
    protected int value      = 0;
    protected int bounding   = 1; // the maximal limit of item's pieces
    protected int inKnapsack = 0; // the pieces of item in solution

    public Item() {}

    public Item(Item item) {
        setName(item.name);
        setWeight(item.weight);
        setValue(item.value);
        setBounding(item.bounding);
    }

    public Item(int _weight, int _value) {
        setWeight(_weight);
        setValue(_value);
    }

    public Item(int _weight, int _value, int _bounding) {
        setWeight(_weight);
        setValue(_value);
        setBounding(_bounding);
    }

    public Item(String _name, int _weight, int _value) {
        setName(_name);
        setWeight(_weight);
        setValue(_value);
    }

    public Item(String _name, int _weight, int _value, int _bounding) {
        setName(_name);
        setWeight(_weight);
        setValue(_value);
        setBounding(_bounding);
    }

    public void setName(String _name) {name = _name;}
    public void setWeight(int _weight) {weight = Math.max(_weight, 0);}
    public void setValue(int _value) {value = Math.max(_value, 0);}

    public void setInKnapsack(int _inKnapsack) {
        inKnapsack = Math.min(getBounding(), Math.max(_inKnapsack, 0));
    }

    public void setBounding(int _bounding) {
        bounding = Math.max(_bounding, 0);
        if (bounding == 0)
            inKnapsack = 0;
    }

    public void checkMembers() {
        setWeight(weight);
        setValue(value);
        setBounding(bounding);
        setInKnapsack(inKnapsack);
    }

    public String getName() {return name;}
    public int getWeight() {return weight;}
    public int getValue() {return value;}
    public int getInKnapsack() {return inKnapsack;}
    public int getBounding() {return bounding;}
} // class

The code implements a solution to the bounded Knapsack problem. It helps a tourist to determine the optimal combination of items to carry on a trip, given a maximum weight limit of 4 kg. The items each have a weight, value, and quantity. The goal is to maximize the total value of items in the knapsack without exceeding the weight limit. The code uses a dynamic programming approach based on the method of Knapsack problem/0-1.


import sun.misc.Signal;
import sun.misc.SignalHandler;

public class ExampleSignalHandler {
    public static void main(String... args) throws InterruptedException {
        final long start = System.nanoTime();
        Signal.handle(new Signal("INT"), new SignalHandler() {
            public void handle(Signal sig) {
                System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
                System.exit(0);
            }
        });
        int counter = 0;
        while(true) {
            System.out.println(counter++);
            Thread.sleep(500);
        }
    }
}

public class ExampleSignalHandler {
    public static void main(String... args) throws InterruptedException {
        final long start = System.nanoTime();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
            }
        }));
        int counter = 0;
        while(true) {
            System.out.println(counter++);
            Thread.sleep(500);
        }
    }
}

The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, typically generated by user input such as ctrl-C or ctrl-\, to stop the output, display the runtime duration in seconds, and terminate the program. It may use sun.misc.SignalHandler to specify the signal to catch or a generic shutdown hook, although the latter doesn't provide a specific signal reference.


String s = "12345";
s = String.valueOf(Integer.parseInt(s) + 1);

String s = "123456789012345678901234567890.12345";
s = new BigDecimal(s).add(BigDecimal.ONE).toString();

Increments a numerical string, handles big decimal numbers, and trims spaces to prevent parseInt Exception.


Works with: Java version 1.5+

public class CommonPath {
	public static String commonPath(String... paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];
		for(int i = 0; i < paths.length; i++){
			folders[i] = paths[i].split("/"); //split on file separator
		}
		for(int j = 0; j < folders[0].length; j++){
			String thisFolder = folders[0][j]; //grab the next folder name in the first path
			boolean allMatched = true; //assume all have matched in case there are no more paths
			for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths
				if(folders[i].length < j){ //if there is no folder here
					allMatched = false; //no match
					break; //stop looking because we've gone as far as we can
				}
				//otherwise
				allMatched &= folders[i][j].equals(thisFolder); //check if it matched
			}
			if(allMatched){ //if they all matched this folder name
				commonPath += thisFolder + "/"; //add it to the answer
			}else{//otherwise
				break;//stop looking
			}
		}
		return commonPath;
	}

	public static void main(String[] args){
		String[] paths = { "/home/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths));

		String[] paths2 = { "/hame/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths2));
	}
}

/home/user1/tmp/
/

	static String commonPath(String...  paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];

		for(int i=0; i<paths.length; i++){
			folders[i] = paths[i].split("/");
		}

		for(int j = 0; j< folders[0].length; j++){
			String s = folders[0][j];
			for(int i=1; i<paths.length; i++){
				if(!s.equals(folders[i][j]))
					return commonPath;
			}
			commonPath += s + "/";
		}
		return commonPath;
	}

The code creates a routine that finds the common directory path from a set of given directory paths and a single character directory separator. It tests the routine using the forward slash '/' as the directory separator and three strings as input paths. The routine returns the valid directory common to all directories, not the longest common string. The routine is case-sensitive and allows for the addition of more separators. The separators in the result will be changed to "/", but they can be mixed in the path.


private static final Random rng = new Random();

void sattoloCycle(Object[] items) {
    for (int i = items.length-1; i > 0; i--) {
        int j = rng.nextInt(i);
        Object tmp = items[i];
        items[i] = items[j];
        items[j] = tmp;
    }
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


Works with: Java version 1.5+

double median(List<Double> values) {
    /* copy, as to prevent modifying 'values' */
    List<Double> list = new ArrayList<>(values);
    Collections.sort(list);
    /* 'mid' will be truncated */
    int mid = list.size() / 2;
    return switch (list.size() % 2) {
        case 0 -> {
            double valueA = list.get(mid);
            double valueB = list.get(mid + 1);
            yield (valueA + valueB) / 2;
        }
        case 1 -> list.get(mid);
        default -> 0;
    };
}

Works with: Java version 1.5+

public static double median2(List<Double> list) {
    PriorityQueue<Double> pq = new PriorityQueue<Double>(list);
    int n = list.size();
    for (int i = 0; i < (n - 1) / 2; i++)
        pq.poll(); // discard first half
    if (n % 2 != 0) // odd length
        return pq.poll();
    else
        return (pq.poll() + pq.poll()) / 2.0;
}

Works with: Java version 1.8+

@FunctionalInterface
interface MedianFinder<T, R> extends Function<Collection<T>, R> {
    @Override
    R apply(Collection<T> data);
}

class MedianFinderImpl<T, R> implements MedianFinder<T, R> {
    private final Supplier<R> ifEmpty;
    private final Function<T, R> ifOdd;
    private final Function<List<T>, R> ifEven;

    MedianFinderImpl(Supplier<R> ifEmpty, Function<T, R> ifOdd, Function<List<T>, R> ifEven) {
        this.ifEmpty = ifEmpty;
        this.ifOdd = ifOdd;
        this.ifEven = ifEven;
    }

    @Override
    public R apply(Collection<T> data) {
        return Objects.requireNonNull(data, "data must not be null").isEmpty()
                ? ifEmpty.get()
                : (data.size() & 1) == 0
                    ? ifEven.apply(data.stream().sorted()
                          .skip(data.size() / 2 - 1)
                          .limit(2).toList())
                    : ifOdd.apply(data.stream().sorted()
                          .skip(data.size() / 2)
                          .limit(1).findFirst().get());
    }
}

public class MedianOf {
    private static final MedianFinder<Integer, Integer> INTEGERS = new MedianFinderImpl<>(() -> 0, n -> n, pair -> (pair.get(0) + pair.get(1)) / 2);
    private static final MedianFinder<Integer, Float> INTEGERS_AS_FLOAT = new MedianFinderImpl<>(() -> 0f, n -> n * 1f, pair -> (pair.get(0) + pair.get(1)) / 2f);
    private static final MedianFinder<Integer, Double> INTEGERS_AS_DOUBLE = new MedianFinderImpl<>(() -> 0d, n -> n * 1d, pair -> (pair.get(0) + pair.get(1)) / 2d);
    private static final MedianFinder<Float, Float> FLOATS = new MedianFinderImpl<>(() -> 0f, n -> n, pair -> (pair.get(0) + pair.get(1)) / 2);
    private static final MedianFinder<Double, Double> DOUBLES = new MedianFinderImpl<>(() -> 0d, n -> n, pair -> (pair.get(0) + pair.get(1)) / 2);
    private static final MedianFinder<BigInteger, BigInteger> BIG_INTEGERS = new MedianFinderImpl<>(() -> BigInteger.ZERO, n -> n, pair -> pair.get(0).add(pair.get(1)).divide(BigInteger.TWO));
    private static final MedianFinder<BigInteger, BigDecimal> BIG_INTEGERS_AS_BIG_DECIMAL = new MedianFinderImpl<>(() -> BigDecimal.ZERO, BigDecimal::new, pair -> new BigDecimal(pair.get(0).add(pair.get(1))).divide(BigDecimal.valueOf(2), RoundingMode.FLOOR));
    private static final MedianFinder<BigDecimal, BigDecimal> BIG_DECIMALS = new MedianFinderImpl<>(() -> BigDecimal.ZERO, n -> n, pair -> pair.get(0).add(pair.get(1)).divide(BigDecimal.valueOf(2), RoundingMode.FLOOR));

    public static Integer    integers(Collection<Integer> integerCollection) { return INTEGERS.apply(integerCollection); }
    public static Float      integersAsFloat(Collection<Integer> integerCollection) { return INTEGERS_AS_FLOAT.apply(integerCollection); }
    public static Double     integersAsDouble(Collection<Integer> integerCollection) { return INTEGERS_AS_DOUBLE.apply(integerCollection); }
    public static Float      floats(Collection<Float> floatCollection) { return FLOATS.apply(floatCollection); }
    public static Double     doubles(Collection<Double> doubleCollection) { return DOUBLES.apply(doubleCollection); }
    public static BigInteger bigIntegers(Collection<BigInteger> bigIntegerCollection) { return BIG_INTEGERS.apply(bigIntegerCollection); }
    public static BigDecimal bigIntegersAsBigDecimal(Collection<BigInteger> bigIntegerCollection) { return BIG_INTEGERS_AS_BIG_DECIMAL.apply(bigIntegerCollection); }
    public static BigDecimal bigDecimals(Collection<BigDecimal> bigDecimalCollection) { return BIG_DECIMALS.apply(bigDecimalCollection); }
}

"Code calculates the median of a vector of floating-point numbers, handling even number of elements by returning the average of two middle values. It implements the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures like mean, mode, standard deviation, and different types of averages such as arithmetic, geometric, harmonic, quadratic, and circular. The code also demonstrates the use of a priority queue for sorting."


public class FizzBuzz {
    public static void main(String[] args) {
        for (int number = 1; number <= 100; number++) {
            if (number % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (number % 3 == 0) {
                System.out.println("Fizz");
            } else if (number % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(number);
            }
        }
    }
}

public class FizzBuzz {
    public static void main(String[] args) {
        int number = 1;
        while (number <= 100) {
            if (number % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (number % 3 == 0) {
                System.out.println("Fizz");
            } else if (number % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(number);
            }
            number++;
        }
    }
}

public class FizzBuzz {
    public static void main(String[] args) {
        int number = 1;
        while (number <= 100) {
            System.out.println(number % 15 == 0 ? "FizzBuzz" : number % 3 == 0 ? "Fizz" : number % 5 == 0 ? "Buzz" : number);
            number++;
        }
    }
}

import java.util.stream.IntStream;
class FizzBuzzJdk12 {
    public static void main(String[] args) {
        IntStream.range(1,101)
        .mapToObj(i->switch (i%15) {
            case 0 -> "FizzBuzz";
            case 3, 6, 9, 12 -> "Fizz";
            case 5, 10 -> "Buzz";
            default -> Integer.toString(i);
        })
        .forEach(System.out::println)
        ;
    }
}

import java.util.stream.IntStream;

class FizzBuzzJdk12 {
    static final int FIZZ_FLAG = 0x8000_0000;
    static final int BUZZ_FLAG = 0x4000_0000;
    static final int FIZZ_BUZZ_FLAG = FIZZ_FLAG|BUZZ_FLAG;
    static final int[] FLAGS = new int[] {
        FIZZ_BUZZ_FLAG|0, 1, 2, FIZZ_FLAG|3, 4,
        BUZZ_FLAG|5, FIZZ_FLAG|6, 7, 8, FIZZ_FLAG|9,
        BUZZ_FLAG|10, 11, FIZZ_FLAG|12, 13, 14
    };
    public static void main(String[] args) {
    IntStream.iterate(0,i->++i)
       .flatMap(i -> IntStream.range(0,15).map(j->FLAGS[j]+15*i))
       .mapToObj(
        // JDK12 switch expression ...
        n-> switch(n & FIZZ_BUZZ_FLAG) {
            case FIZZ_BUZZ_FLAG -> "fizzbuzz";
            case FIZZ_FLAG -> "fizz";
            case BUZZ_FLAG -> "buzz";
            default -> Integer.toString(~FIZZ_BUZZ_FLAG & n);
            }
       )
       .skip(1)
       .limit(100)
       .forEach(System.out::println)
       ;
    }
}

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both with 'FizzBuzz'.


Library: Swing Library: AWT
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;

public class Mandelbrot extends JFrame {

    private final int MAX_ITER = 570;
    private final double ZOOM = 150;
    private BufferedImage I;
    private double zx, zy, cX, cY, tmp;

    public Mandelbrot() {
        super("Mandelbrot Set");
        setBounds(100, 100, 800, 600);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < getHeight(); y++) {
            for (int x = 0; x < getWidth(); x++) {
                zx = zy = 0;
                cX = (x - 400) / ZOOM;
                cY = (y - 300) / ZOOM;
                int iter = MAX_ITER;
                while (zx * zx + zy * zy < 4 && iter > 0) {
                    tmp = zx * zx - zy * zy + cX;
                    zy = 2.0 * zx * zy + cY;
                    zx = tmp;
                    iter--;
                }
                I.setRGB(x, y, iter | (iter << 8));
            }
        }
    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(I, 0, 0, this);
    }

    public static void main(String[] args) {
        new Mandelbrot().setVisible(true);
    }
}

Library: AWT Library: Swing
import static java.awt.Color.HSBtoRGB;
import static java.awt.Color.black;
import static java.awt.event.KeyEvent.VK_BACK_SLASH;
import static java.awt.event.KeyEvent.VK_ESCAPE;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
import static java.lang.Integer.signum;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.System.currentTimeMillis;
import static java.util.Locale.ROOT;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.function.Consumer;
import java.util.function.Predicate;

import javax.swing.JFrame;

/*
 *      click: point to center
 * ctrl-click: point to origin
 *       drag: point to mouse release point
 *  ctrl-drag: point to origin + zoom
 * back-slash: back to previous point
 *        esc: back to previous zoom point - zoom
 */

public class Mandelbrot extends JFrame {
	private static final long serialVersionUID = 1L;

	private Insets insets;
	private int width, height;
	private double widthHeightRatio;
	private int minX, minY;
	private double Zoom;

	private int mpX, mpY, mdX, mdY;
	private boolean isCtrlDown, ctrl;
	private Stack stack = new Stack();

	private BufferedImage image;
	private boolean newImage = true;

	public static void main(String[] args) {
		new Mandelbrot(800, 600); // (800, 600), (1024, 768), (1600, 900), (1920, 1080)
		//new Mandelbrot(800, 600, 4.5876514379235943e-09, -0.6092161175392330, -0.4525577210859453);
		//new Mandelbrot(800, 600, 5.9512354925205320e-10, -0.6092146769531246, -0.4525564820098262);
		//new Mandelbrot(800, 600, 6.7178527589983420e-08, -0.7819036465400592, -0.1298363433443265);
		//new Mandelbrot(800, 600, 4.9716091454775210e-09, -0.7818800036717134, -0.1298044093748981);
		//new Mandelbrot(800, 600, 7.9333341281639390e-06, -0.7238770725243187, -0.2321214232559487);
		/*
		new Mandelbrot(800, 600, new double[][] {
			{5.0000000000000000e-03, -2.6100000000000000, -1.4350000000000000}, // done!
			{3.5894206549118390e-04, -0.7397795969773300, -0.4996473551637279}, // done!
			{3.3905106941862460e-05, -0.6270410477828043, -0.4587021918164572}, // done!
			{6.0636337351945460e-06, -0.6101531446039512, -0.4522561221394852}, // done!
			{1.5502741161769430e-06, -0.6077214060084073, -0.4503995886987711}, // done!
		});
		//*/
	}

	public Mandelbrot(int width, int height) {
		this(width, height, .005, -2.61, -1.435);
	}

	public Mandelbrot(int width, int height, double Zoom, double r, double i) {
		this(width, height, new double[] {Zoom, r, i});
	}

	public Mandelbrot(int width, int height, double[] ... points) {
		super("Mandelbrot Set");
		setResizable(false);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Dimension screen = getToolkit().getScreenSize();
		setBounds(
			rint((screen.getWidth() - width) / 2),
			rint((screen.getHeight() - height) / 2),
			width,
			height
		);
		addMouseListener(mouseAdapter);
		addMouseMotionListener(mouseAdapter);
		addKeyListener(keyAdapter);
		Point point = stack.push(points);
		this.Zoom = point.Zoom;
		this.minX = point.minX;
		this.minY = point.minY;
		setVisible(true);
		insets = getInsets();
		this.width = width -= insets.left + insets.right;
		this.height = height -= insets.top + insets.bottom;
		widthHeightRatio = (double) width / height;
	}

	private int rint(double d) {
		return (int) Math.rint(d); // half even
	}

	private void repaint(boolean newImage) {
		this.newImage = newImage;
		repaint();
	}

	private MouseAdapter mouseAdapter = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
			stack.push(false);
			if (!ctrl) {
				minX -= width / 2 ;
				minY -= height / 2;
			}
			minX += e.getX() - insets.left;
			minY += e.getY() - insets.top;
			ctrl = false;
			repaint(true);
	 	}
		public void mousePressed(MouseEvent e) {
			mpX = e.getX();
			mpY = e.getY();
			ctrl = isCtrlDown;
		}
		public void mouseDragged(MouseEvent e) {
			if (!ctrl) return;
			setMdCoord(e);
			repaint();
		}
		private void setMdCoord(MouseEvent e) {
			int dx = e.getX() - mpX;
			int dy = e.getY() - mpY;
			mdX = mpX + max(abs(dx), rint(abs(dy) * widthHeightRatio) * signum(dx));
			mdY = mpY + max(abs(dy), rint(abs(dx) / widthHeightRatio) * signum(dy));
			acceptIf(insets.left, ge(mdX), setMdXY);
			acceptIf(insets.top,  ge(mdY), setMdYX);
			acceptIf(insets.left+width-1, le(mdX), setMdXY);
			acceptIf(insets.top+height-1, le(mdY), setMdYX);
		}
		private void acceptIf(int value, Predicate<Integer> p, Consumer<Integer> c) { if (p.test(value)) c.accept(value); }
		private Predicate<Integer> ge(int md) { return v-> v >= md; }
		private Predicate<Integer> le(int md) { return v-> v <= md; }
		private Consumer<Integer> setMdXY = v-> mdY = mpY + rint(abs((mdX=v)-mpX) / widthHeightRatio) * signum(mdY-mpY);
		private Consumer<Integer> setMdYX = v-> mdX = mpX + rint(abs((mdY=v)-mpY) * widthHeightRatio) * signum(mdX-mpX);
		public void mouseReleased(MouseEvent e) {
			if (e.getX() == mpX && e.getY() == mpY) return;
			stack.push(ctrl);
			if (!ctrl) {
				minX += mpX - (mdX = e.getX());
				minY += mpY - (mdY = e.getY());
			}
			else {
				setMdCoord(e);
				if (mdX < mpX) { int t=mpX; mpX=mdX; mdX=t; }
				if (mdY < mpY) { int t=mpY; mpY=mdY; mdY=t; }
				minX += mpX - insets.left;
				minY += mpY - insets.top;
				double rZoom = (double) width / abs(mdX - mpX);
				minX *= rZoom;
				minY *= rZoom;
				Zoom /= rZoom;
			}
			ctrl = false;
			repaint(true);
		}
	};

	private KeyAdapter keyAdapter = new KeyAdapter() {
		public void keyPressed(KeyEvent e) {
			isCtrlDown = e.isControlDown();
		}
		public void keyReleased(KeyEvent e) {
			isCtrlDown = e.isControlDown();
		}
		public void keyTyped(KeyEvent e) {
			char c = e.getKeyChar();
			boolean isEsc = c == VK_ESCAPE;
			if (!isEsc && c != VK_BACK_SLASH) return;
			repaint(stack.pop(isEsc));
		}
	};

	private class Point {
		public boolean type;
		public double Zoom;
		public int minX;
		public int minY;
		Point(boolean type, double Zoom, int minX, int minY) {
			this.type = type;
			this.Zoom = Zoom;
			this.minX = minX;
			this.minY = minY;
		}
	}
	private class Stack extends java.util.Stack<Point> {
		private static final long serialVersionUID = 1L;
		public Point push(boolean type) {
			return push(type, Zoom, minX, minY);
		}
		public Point push(boolean type, double ... point) {
			double Zoom = point[0];
			return push(type, Zoom, rint(point[1]/Zoom), rint(point[2]/Zoom));
		}
		public Point push(boolean type, double Zoom, int minX, int minY) {
			return push(new Point(type, Zoom, minX, minY));
		}
		public Point push(double[] ... points) {
			Point lastPoint = push(false, points[0]);
			for (int i=0, e=points.length-1; i<e; i+=1) {
				double[] point = points[i];
				lastPoint = push(point[0] != points[i+1][0], point);
				done(printPoint(lastPoint));
			}
			return lastPoint;
		}
		public boolean pop(boolean type) {
			for (;;) {
				if (empty()) return false;
				Point d = super.pop();
				Zoom = d.Zoom;
				minX = d.minX;
				minY = d.minY;
				if (!type || d.type) return true;
			}
		}
	}

	@Override
	public void paint(Graphics g) {
		if (newImage) newImage();
		g.drawImage(image, insets.left, insets.top, this);
		//g.drawLine(insets.left+width/2, insets.top+0,        insets.left+width/2, insets.top+height);
		//g.drawLine(insets.left+0,       insets.top+height/2, insets.left+width,   insets.top+height/2);
		if (!ctrl) return;
		g.drawRect(min(mpX, mdX), min(mpY, mdY), abs(mpX - mdX), abs(mpY - mdY));
	}

	private void newImage() {
		long milli = printPoint();
		image = new BufferedImage(width, height, TYPE_INT_RGB);
		int maxX = minX + width;
		int maxY = minY + height;
		for (int x = minX; x < maxX; x+=1) {
			double r = x * Zoom;
			for (int y = minY; y < maxY; y+=1) {
				double i = y * Zoom;
				//System.out.printf("%+f%+fi\n", r, i);
				//             0f    1/6f  1/3f 1/2f 2/3f    5/6f
				//straight -> red  yellow green cian blue magenta <- reverse
				image.setRGB(x-minX, y-minY, color(r, i, 360, false, 2/3f));
			}
		}
		newImage = false;
		done(milli);
	}

	private long printPoint() {
		return printPoint(Zoom, minX, minY);
	}
	private long printPoint(Point point) {
		return printPoint(point.Zoom, point.minX, point.minY);
	}
	private long printPoint(double Zoom, int minX, int minY) {
		return printPoint(Zoom, minX*Zoom, minY*Zoom);
	}
	private long printPoint(Object ... point) {
		System.out.printf(ROOT,	"{%.16e, %.16g, %.16g},", point);
		return currentTimeMillis();
	}

	private void done(long milli) {
		milli = currentTimeMillis() - milli;
		System.out.println(" // " + milli + "ms done!");
	}

	private int color(double r0, double i0, int max, boolean straight, float shift) {
		int n = -1;
		double r=0, i=0, r2=0, i2=0;
		do {
			i = r*(i+i) + i0;
			r = r2-i2 + r0;
			r2 = r*r;
			i2 = i*i;
		}
		while (++n < max && r2 + i2 < 4);
		return n == max
			? black.getRGB()
			: HSBtoRGB(shift + (float) (straight ? n : max-n) / max * 11/12f + (straight ? 0f : 1/12f), 1, 1)
		;
	}
}

generate and draw the Mandelbrot set using various available algorithms and functions.


Works with: Java version 1.5+
public class SumProd
{
 public static void main(final String[] args)
 {
  int sum = 0;
  int prod = 1;
  int[] arg = {1,2,3,4,5};
  for (int i : arg)
  {
   sum += i;
   prod *= i;
  }
 }
}

Works with: Java version 1.8+
import java.util.Arrays;

public class SumProd
{
 public static void main(final String[] args)
 {
  int[] arg = {1,2,3,4,5};
  System.out.printf("sum = %d\n", Arrays.stream(arg).sum());
  System.out.printf("sum = %d\n", Arrays.stream(arg).reduce(0, (a, b) -> a + b));
  System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b));
 }
}

Calculate the sum and product of all integers in an array.


import java.util.GregorianCalendar;
import java.text.MessageFormat;

public class Leapyear{
        public static void main(String[] argv){
                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
                GregorianCalendar cal = new GregorianCalendar();
                for(int year : yrs){
                        System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
                                                                 year, cal.isLeapYear(year), isLeapYear(year)));
                }

        }
        public static boolean isLeapYear(int year){
                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
        }
}

determine if a given year is a leap year in the Gregorian calendar, using both the GregorianCalendar class and an algorithm from the wiki. The program switches from the Julian calendar to the Gregorian calendar at 15 October 1582 by default. Both results are printed in the output.


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OneTimePad {

    public static void main(String[] args) {
        String controlName = "AtomicBlonde";
        generatePad(controlName, 5, 60, 65, 90);
        String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES";
        String encrypted = parse(true, controlName, text.replaceAll(" ", ""));
        String decrypted = parse(false, controlName, encrypted);
        System.out.println("Input  text    = " + text);
        System.out.println("Encrypted text = " + encrypted);
        System.out.println("Decrypted text = " + decrypted);

        controlName = "AtomicBlondeCaseSensitive";
        generatePad(controlName, 5, 60, 32, 126);
        text = "It was the best of times, it was the worst of times.";
        encrypted = parse(true, controlName, text);
        decrypted = parse(false, controlName, encrypted);
        System.out.println();
        System.out.println("Input text     = " + text);
        System.out.println("Encrypted text = " + encrypted);
        System.out.println("Decrypted text = " + decrypted);
    }

    private static String parse(boolean encryptText, String controlName, String text) {
        StringBuilder sb = new StringBuilder();
        int minCh = 0;
        int maxCh = 0;
        Pattern minChPattern = Pattern.compile("^#  MIN_CH = ([\\d]+)$");
        Pattern maxChPattern = Pattern.compile("^#  MAX_CH = ([\\d]+)$");
        boolean validated = false;
        try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {
            String inLine = null;
            while ( (inLine = in.readLine()) != null ) {
                Matcher minMatcher = minChPattern.matcher(inLine);
                if ( minMatcher.matches() ) {
                    minCh = Integer.parseInt(minMatcher.group(1));
                    continue;
                }
                Matcher maxMatcher = maxChPattern.matcher(inLine);
                if ( maxMatcher.matches() ) {
                    maxCh = Integer.parseInt(maxMatcher.group(1));
                    continue;
                }
                if ( ! validated && minCh > 0 && maxCh > 0 ) {
                    validateText(text, minCh, maxCh);
                    validated = true;
                }
                //  # is comment.  - is used key.
                if ( inLine.startsWith("#") || inLine.startsWith("-") ) {
                    continue;
                }
                //  Have encryption key.
                String key = inLine;
                if ( encryptText ) {
                    for ( int i = 0 ; i < text.length(); i++) {
                        sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));
                    }
                }
                else {
                    for ( int i = 0 ; i < text.length(); i++) {
                        int decrypt = text.charAt(i) - key.charAt(i);
                        if ( decrypt < 0 ) {
                            decrypt += maxCh - minCh + 1;
                        }
                        decrypt += minCh;
                        sb.append((char) decrypt);
                    }
                }
                break;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    private static void validateText(String text, int minCh, int maxCh) {
        //  Validate text is in range
        for ( char ch : text.toCharArray() ) {
            if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {
                throw new IllegalArgumentException("ERROR 103:  Invalid text.");
            }
        }

    }

    private static String getFileName(String controlName) {
        return controlName + ".1tp";
    }

    private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {
        Random random = new Random();
        try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {
            writer.write("#  Lines starting with '#' are ignored.");
            writer.newLine();
            writer.write("#  Lines starting with '-' are previously used.");
            writer.newLine();
            writer.write("#  MIN_CH = " + minCh);
            writer.newLine();
            writer.write("#  MAX_CH = " + maxCh);
            writer.newLine();
            for ( int line = 0 ; line < keys ; line++ ) {
                StringBuilder sb = new StringBuilder();
                for ( int ch = 0 ; ch < keyLength ; ch++ ) {
                    sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));
                }
                writer.write(sb.toString());
                writer.newLine();
            }
            writer.write("#  EOF");
            writer.newLine();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for the pad based on user-specified filename and length, ensuring the use of true random numbers. It also reuses elements of the Vigenère cipher for encryption/decryption operations. The code supports management of One-time pads, allowing users to list, mark as used, delete, and keep track of pads. Pad files have a ".1tp" extension and can contain metadata or be marked as "used". The implementation supports multiple pads and includes start and end ASCII characters. It demonstrates the generation of a pad supporting uppercase only and another supporting lowercase, uppercase, symbols, and spaces.


Works with: Java version 1.5+

class MD5
{

  private static final int INIT_A = 0x67452301;
  private static final int INIT_B = (int)0xEFCDAB89L;
  private static final int INIT_C = (int)0x98BADCFEL;
  private static final int INIT_D = 0x10325476;

  private static final int[] SHIFT_AMTS = {
    7, 12, 17, 22,
    5,  9, 14, 20,
    4, 11, 16, 23,
    6, 10, 15, 21
  };

  private static final int[] TABLE_T = new int[64];
  static
  {
    for (int i = 0; i < 64; i++)
      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
  }

  public static byte[] computeMD5(byte[] message)
  {
    int messageLenBytes = message.length;
    int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
    int totalLen = numBlocks << 6;
    byte[] paddingBytes = new byte[totalLen - messageLenBytes];
    paddingBytes[0] = (byte)0x80;

    long messageLenBits = (long)messageLenBytes << 3;
    for (int i = 0; i < 8; i++)
    {
      paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;
      messageLenBits >>>= 8;
    }

    int a = INIT_A;
    int b = INIT_B;
    int c = INIT_C;
    int d = INIT_D;
    int[] buffer = new int[16];
    for (int i = 0; i < numBlocks; i ++)
    {
      int index = i << 6;
      for (int j = 0; j < 64; j++, index++)
        buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);
      int originalA = a;
      int originalB = b;
      int originalC = c;
      int originalD = d;
      for (int j = 0; j < 64; j++)
      {
        int div16 = j >>> 4;
        int f = 0;
        int bufferIndex = j;
        switch (div16)
        {
          case 0:
            f = (b & c) | (~b & d);
            break;

          case 1:
            f = (b & d) | (c & ~d);
            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
            break;

          case 2:
            f = b ^ c ^ d;
            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
            break;

          case 3:
            f = c ^ (b | ~d);
            bufferIndex = (bufferIndex * 7) & 0x0F;
            break;
        }
        int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
        a = d;
        d = c;
        c = b;
        b = temp;
      }

      a += originalA;
      b += originalB;
      c += originalC;
      d += originalD;
    }

    byte[] md5 = new byte[16];
    int count = 0;
    for (int i = 0; i < 4; i++)
    {
      int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
      for (int j = 0; j < 4; j++)
      {
        md5[count++] = (byte)n;
        n >>>= 8;
      }
    }
    return md5;
  }

  public static String toHexString(byte[] b)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < b.length; i++)
    {
      sb.append(String.format("%02X", b[i] & 0xFF));
    }
    return sb.toString();
  }

  public static void main(String[] args)
  {
    String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
    for (String s : testStrings)
      System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
    return;
  }

}

0xD41D8CD98F00B204E9800998ECF8427E <== ""
0x0CC175B9C0F1B6A831C399E269772661 <== "a"
0x900150983CD24FB0D6963F7D28E17F72 <== "abc"
0xF96B697D7CB7938D525A2F31AAF161D0 <== "message digest"
0xC3FCD3D76192E4007DFB496CCA67E13B <== "abcdefghijklmnopqrstuvwxyz"
0xD174AB98D277D9F5A5611C2C9F419D9F <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57EDF4A22BE3C955AC49DA2E2107B67A <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"

Works with: Java version 1.5+

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

class MD5
{

  private static final int INIT_A = 0x67452301;
  private static final int INIT_B = (int)0xEFCDAB89L;
  private static final int INIT_C = (int)0x98BADCFEL;
  private static final int INIT_D = 0x10325476;

  private static final int[] SHIFT_AMTS = {
    7, 12, 17, 22,
    5,  9, 14, 20,
    4, 11, 16, 23,
    6, 10, 15, 21
  };

  private static final int[] TABLE_T = new int[64];
  static
  {
    for (int i = 0; i < 64; i++)
      TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
  }

  public static byte[] computeMD5(byte[] message)
  {
    ByteBuffer padded = ByteBuffer.allocate((((message.length + 8) / 64) + 1) * 64).order(ByteOrder.LITTLE_ENDIAN);
    padded.put(message);
    padded.put((byte)0x80);
    long messageLenBits = (long)message.length * 8;
    padded.putLong(padded.capacity() - 8, messageLenBits);

    padded.rewind();

    int a = INIT_A;
    int b = INIT_B;
    int c = INIT_C;
    int d = INIT_D;
    while (padded.hasRemaining()) {
      // obtain a slice of the buffer from the current position,
      // and view it as an array of 32-bit ints
      IntBuffer chunk = padded.slice().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
      int originalA = a;
      int originalB = b;
      int originalC = c;
      int originalD = d;
      for (int j = 0; j < 64; j++)
      {
        int div16 = j >>> 4;
        int f = 0;
        int bufferIndex = j;
        switch (div16)
        {
          case 0:
            f = (b & c) | (~b & d);
            break;

          case 1:
            f = (b & d) | (c & ~d);
            bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
            break;

          case 2:
            f = b ^ c ^ d;
            bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
            break;

          case 3:
            f = c ^ (b | ~d);
            bufferIndex = (bufferIndex * 7) & 0x0F;
            break;
        }
        int temp = b + Integer.rotateLeft(a + f + chunk.get(bufferIndex) + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
        a = d;
        d = c;
        c = b;
        b = temp;
      }

      a += originalA;
      b += originalB;
      c += originalC;
      d += originalD;
      padded.position(padded.position() + 64);
    }

    ByteBuffer md5 = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);
    for (int n : new int[]{a, b, c, d})
    {
      md5.putInt(n);
    }
    return md5.array();
  }

  public static String toHexString(byte[] b)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < b.length; i++)
    {
      sb.append(String.format("%02X", b[i] & 0xFF));
    }
    return sb.toString();
  }

  public static void main(String[] args)
  {
    String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
    for (String s : testStrings)
      System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
    return;
  }

}

0xD41D8CD98F00B204E9800998ECF8427E <== ""
0x0CC175B9C0F1B6A831C399E269772661 <== "a"
0x900150983CD24FB0D6963F7D28E17F72 <== "abc"
0xF96B697D7CB7938D525A2F31AAF161D0 <== "message digest"
0xC3FCD3D76192E4007DFB496CCA67E13B <== "abcdefghijklmnopqrstuvwxyz"
0xD174AB98D277D9F5A5611C2C9F419D9F <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57EDF4A22BE3C955AC49DA2E2107B67A <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"

implement the MD5 Message Digest Algorithm directly without using any built-in or external hashing libraries. The implementation produces a correct message digest for an input string and does not mimic all calling modes. It also includes any challenges faced during implementation, choices made, or limitations. The code does not use built-in MD5 functions or library routines written in other languages. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes verification strings and hashes from RFC 1321. However, it does not guarantee security as MD5 has been broken.


public class DepartmentNumbers {
    public static void main(String[] args) {
        System.out.println("Police  Sanitation  Fire");
        System.out.println("------  ----------  ----");
        int count = 0;
        for (int i = 2; i <= 6; i += 2) {
            for (int j = 1; j <= 7; ++j) {
                if (j == i) continue;
                for (int k = 1; k <= 7; ++k) {
                    if (k == i || k == j) continue;
                    if (i + j + k != 12) continue;
                    System.out.printf("  %d         %d         %d\n", i, j, k);
                    count++;
                }
            }
        }
        System.out.printf("\n%d valid combinations", count);
    }
}

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


String src = "Hello";
String newAlias = src;
String strCopy = new String(src);

//"newAlias == src" is true
//"strCopy == src" is false
//"strCopy.equals(src)" is true

StringBuffer srcCopy = new StringBuffer("Hello");

create a copy of a string or make an additional reference to an existing string in Java, considering the immutability of Strings and the potential use of StringBuffer for mutable strings.


import java.util.HashMap;
import java.util.Map;

public class MutualRecursion {

    public static void main(final String args[]) {
        int max = 20;
        System.out.printf("First %d values of the Female sequence:  %n", max);
        for (int i = 0; i < max; i++) {
            System.out.printf("  f(%d) = %d%n", i, f(i));
        }
        System.out.printf("First %d values of the Male sequence:  %n", max);
        for (int i = 0; i < 20; i++) {
            System.out.printf("  m(%d) = %d%n", i, m(i));
        }
    }

    private static Map<Integer,Integer> F_MAP = new HashMap<>();

    private static int f(final int n) {
        if ( F_MAP.containsKey(n) ) {
            return F_MAP.get(n);
        }
        int fn = n == 0 ? 1 : n - m(f(n - 1));
        F_MAP.put(n, fn);
        return fn;
    }

    private static Map<Integer,Integer> M_MAP = new HashMap<>();

    private static int m(final int n) {
        if ( M_MAP.containsKey(n) ) {
            return M_MAP.get(n);
        }
        int mn = n == 0 ? 0 : n - f(m(n - 1));
        M_MAP.put(n, mn);
        return mn;
    }

}

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions handle base cases for n=0 and use the formula n-M(F(n-1)) for the female sequence and n-F(M(n-1)) for the male sequence for n>0. The functions also print the first 20 values of both sequences.


import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used

demonstrate how to select a random element from a list. If the order of the list is not important, the list is shuffled and the first element is selected. This process is repeated each time unless the selected item is removed from the list.


import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

URLDecoder.decode("http%3A%2F%2Ffoo%20bar%2F", StandardCharsets.UTF_8)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String decode(String string) {
    Pattern pattern = Pattern.compile("%([A-Za-z\\d]{2})");
    Matcher matcher = pattern.matcher(string);
    StringBuilder decoded = new StringBuilder(string);
    char character;
    int start, end, offset = 0;
    while (matcher.find()) {
        character = (char) Integer.parseInt(matcher.group(1), 16);
        /* offset the matched index since were adjusting the string */
        start = matcher.start() - offset;
        end = matcher.end() - offset;
        decoded.replace(start, end, String.valueOf(character));
        offset += 2;
    }
    return decoded.toString();
}

http://foo bar/
google.com/search?q=`Abdu'l-BahÃ¡

provide a function to convert URL-encoded strings back to their original unencoded form, using either Java's URLDecoder and URLEncoder classes or a regular expression. The function correctly handles cases like "%25%32%35" reverting to "%25" instead of "%".


public class BinarySearchIterative {

    public static int binarySearch(int[] nums, int check) {
        int hi = nums.length - 1;
        int lo = 0;
        while (hi >= lo) {
            int guess = (lo + hi) >>> 1;  // from OpenJDK
            if (nums[guess] > check) {
                hi = guess - 1;
            } else if (nums[guess] < check) {
                lo = guess + 1;
            } else {
                return guess;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] haystack = {1, 5, 6, 7, 8, 11};
        int needle = 5;
        int index = binarySearch(haystack, needle);
        if (index == -1) {
            System.out.println(needle + " is not in the array");
        } else {
            System.out.println(needle + " is at index " + index);
        }
    }
}

public class BinarySearchRecursive {

    public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
        if (hi < lo) {
            return -1;
        }
        int guess = (hi + lo) / 2;
        if (haystack[guess] > needle) {
            return binarySearch(haystack, needle, lo, guess - 1);
        } else if (haystack[guess] < needle) {
            return binarySearch(haystack, needle, guess + 1, hi);
        }
        return guess;
    }

    public static void main(String[] args) {
        int[] haystack = {1, 5, 6, 7, 8, 11};
        int needle = 5;

        int index = binarySearch(haystack, needle, 0, haystack.length);

        if (index == -1) {
            System.out.println(needle + " is not in the array");
        } else {
            System.out.println(needle + " is at index " + index);
        }
    }
}

import java.util.Arrays;

int index = Arrays.binarySearch(array, thing);
int index = Arrays.binarySearch(array, startIndex, endIndex, thing);

// for objects, also optionally accepts an additional comparator argument:
int index = Arrays.binarySearch(array, thing, comparator);
int index = Arrays.binarySearch(array, startIndex, endIndex, thing, comparator);

import java.util.Collections;

int index = Collections.binarySearch(list, thing);
int index = Collections.binarySearch(list, thing, comparator);

The code implements a binary search algorithm on a sorted integer array. It takes the starting point, ending point, and a "secret value" as inputs. The algorithm divides the range into halves and continues to narrow down the search field until the secret value is found. It can be implemented both recursively and iteratively. The code also handles multiple values equal to the given value and returns the index of the secret value if found. Additionally, it provides the "insertion point" for the secret value if it's not found in the array. The code also avoids overflow bugs by calculating the mid-point in a safe manner.


public static void main(String[] args)

myprogram -c "alpha beta" -h "gamma"

-c
alpha beta
-h
gamma

public class Arguments {
  public static void main(String[] args) {
     System.out.println("There are " + args.length + " arguments given.");
     for(int i = 0; i < args.length; i++)
        System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
  }
}

The code retrieves and prints the list of command-line arguments provided to the program. It parses these arguments intelligently and passes them to the main function as the only parameter. The code demonstrates how to use the Apache Commons CLI library for more sophisticated command-line option and argument parsing.


Library: Swing Library: AWT
import java.awt.*;
import javax.swing.*;

public class Pendulum extends JPanel implements Runnable {

    private double angle = Math.PI / 2;
    private int length;

    public Pendulum(int length) {
        this.length = length;
        setDoubleBuffered(true);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
        int ballX = anchorX + (int) (Math.sin(angle) * length);
        int ballY = anchorY + (int) (Math.cos(angle) * length);
        g.drawLine(anchorX, anchorY, ballX, ballY);
        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
        g.fillOval(ballX - 7, ballY - 7, 14, 14);
    }

    public void run() {
        double angleAccel, angleVelocity = 0, dt = 0.1;
        while (true) {
            angleAccel = -9.81 / length * Math.sin(angle);
            angleVelocity += angleAccel * dt;
            angle += angleVelocity * dt;
            repaint();
            try { Thread.sleep(15); } catch (InterruptedException ex) {}
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(2 * length + 50, length / 2 * 3);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Pendulum");
        Pendulum p = new Pendulum(200);
        f.add(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
        new Thread(p).start();
    }
}

create and animate a simple physical model of a gravity pendulum.


//  Parse JSON
//
//  Nigel Galloway - April 27th., 2012
//
grammar JSON ;
@members {
String Indent = "";
}
Number	:	(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS	:	(' ' | '\t' | '\r' |'\n') {skip();};
Tz	:	' ' .. '!' | '#' .. '[' | ']' .. '~';
Control	:	'\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode	:	'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword	:	'true' | 'false' | 'null';
String	:	'"' (Control? Tz)* '"';
object	:       '{' {System.out.println(Indent + "{Object}"); Indent += "    ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair	:	e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value	:	Number             {System.out.println(Indent + "{Number}  \t" + $Number.text);}
	|	object
	|	String             {System.out.println(Indent + "{String}  \t" + $String.text);}
	|	Keyword            {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
	|	array;
array	:	'[' {System.out.println(Indent + "Array"); Indent += "    ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};

>java Test
{
  "Nigel"
  :
  -110.2e-13
  ,
  "Fred"
  :
  {
    "Joe"
    :
    [3,true,"Nigel"]
  }
  "Harry"
  :
  [23,"Hello"]
}
^Z
{Object}
    {Property}  "Nigel"
    {Number}    -110.2e-13
    {Property}  "Fred"
    {Object}
        {Property}      "Joe"
        Array
            {Number}    3
            {Keyword}   true
            {String}    "Nigel"
    {Property}  "Harry"
    Array
        {Number}        23
        {String}        "Hello"

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON using objects and arrays."


public static double nthroot(int n, double A) {
	return nthroot(n, A, .001);
}
public static double nthroot(int n, double A, double p) {
	if(A < 0) {
		System.err.println("A < 0");// we handle only real positive numbers
		return -1;
	} else if(A == 0) {
		return 0;
	}
	double x_prev = A;
	double x = A / n;  // starting "guessed" value...
	while(Math.abs(x - x_prev) > p) {
		x_prev = x;
		x = ((n - 1.0) * x + A / Math.pow(x, n - 1.0)) / n;
	}
	return x;
}
public static double nthroot(int n, double x) {
  assert (n > 1 && x > 0);
  int np = n - 1;
  double g1 = x;
  double g2 = iter(g1, np, n, x);
  while (g1 != g2) {
    g1 = iter(g1, np, n, x);
    g2 = iter(iter(g2, np, n, x), np, n, x);
  }
  return g1;
}

private static double iter(double g, int np, int n, double x) {
  return (np * g + x / Math.pow(g, np)) / n;
}

Implement the principal nth root algorithm for a positive real number A.


import java.net.InetAddress;
import java.net.UnknownHostException;

void printHostname() throws UnknownHostException {
    InetAddress localhost = InetAddress.getLocalHost();
    System.out.println(localhost.getHostName());
}

penguin

"Determines and outputs the hostname of the current system where the routine is running."


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

@SuppressWarnings("SameParameterValue")
public class LeonardoNumbers {
    private static List<Integer> leonardo(int n) {
        return leonardo(n, 1, 1, 1);
    }

    private static List<Integer> leonardo(int n, int l0, int l1, int add) {
        Integer[] leo = new Integer[n];
        leo[0] = l0;
        leo[1] = l1;
        for (int i = 2; i < n; i++) {
            leo[i] = leo[i - 1] + leo[i - 2] + add;
        }
        return Arrays.asList(leo);
    }

    public static void main(String[] args) {
        System.out.println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:");
        System.out.println(leonardo(25));
        System.out.println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:");
        System.out.println(leonardo(25, 0, 1, 0));
    }
}

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


Works with: Java version 7
import java.util.*;

public class Game24 {
    static Random r = new Random();

    public static void main(String[] args) {

        int[] digits = randomDigits();
        Scanner in = new Scanner(System.in);

        System.out.print("Make 24 using these digits: ");
        System.out.println(Arrays.toString(digits));
        System.out.print("> ");

        Stack<Float> s = new Stack<>();
        long total = 0;
        for (char c : in.nextLine().toCharArray()) {
            if ('0' <= c && c <= '9') {
                int d = c - '0';
                total += (1 << (d * 5));
                s.push((float) d);
            } else if ("+/-*".indexOf(c) != -1) {
                s.push(applyOperator(s.pop(), s.pop(), c));
            }
        }
        if (tallyDigits(digits) != total)
            System.out.print("Not the same digits. ");
        else if (Math.abs(24 - s.peek()) < 0.001F)
            System.out.println("Correct!");
        else
            System.out.print("Not correct.");
    }

    static float applyOperator(float a, float b, char c) {
        switch (c) {
            case '+':
                return a + b;
            case '-':
                return b - a;
            case '*':
                return a * b;
            case '/':
                return b / a;
            default:
                return Float.NaN;
        }
    }

    static long tallyDigits(int[] a) {
        long total = 0;
        for (int i = 0; i < 4; i++)
            total += (1 << (a[i] * 5));
        return total;
    }

    static int[] randomDigits() {
        int[] result = new int[4];
        for (int i = 0; i < 4; i++)
            result[i] = r.nextInt(9) + 1;
        return result;
    }
}

"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits."


import java.util.regex.Matcher;
import java.util.regex.Pattern;

String encode(String string) {
    Pattern pattern = Pattern.compile("(.)\\1*");
    Matcher matcher = pattern.matcher(string);
    StringBuilder encoded = new StringBuilder();
    while (matcher.find()) {
        encoded.append(matcher.group().length());
        encoded.append(matcher.group().charAt(0));
    }
    return encoded.toString();
}

String decode(String string) {
    Pattern pattern = Pattern.compile("(\\d+)(.)");
    Matcher matcher = pattern.matcher(string);
    StringBuilder decoded = new StringBuilder();
    int count;
    while (matcher.find()) {
        count = Integer.parseInt(matcher.group(1));
        decoded.append(matcher.group(2).repeat(count));
    }
    return decoded.toString();
}

string = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
encoded = 12W1B12W3B24W1B14W
decoded = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
string.equals(decoded) = true

string = https://www.rosettacode.org/
encoded = 1h2t1p1s1:2/3w1.1r1o1s1e2t1a1c1o1d1e1.1o1r1g1/
decoded = https://www.rosettacode.org/
string.equals(decoded) = true

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {

    public static String encode(String source) {
        StringBuffer dest = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            int runLength = 1;
            while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
                runLength++;
                i++;
            }
            dest.append(runLength);
            dest.append(source.charAt(i));
        }
        return dest.toString();
    }

    public static String decode(String source) {
        StringBuffer dest = new StringBuffer();
        Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            int number = Integer.parseInt(matcher.group());
            matcher.find();
            while (number-- != 0) {
                dest.append(matcher.group());
            }
        }
        return dest.toString();
    }

    public static void main(String[] args) {
        String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
        System.out.println(encode(example));
        System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
    }
}

Library: JUnit
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class RunLengthEncodingTest {
	private RLE = new RunLengthEncoding();

	@Test
	public void encodingTest() {
		assertEquals("1W", RLE.encode("W"));
		assertEquals("4W", RLE.encode("WWWW"));
		assertEquals("5w4i7k3i6p5e4d2i1a",
				RLE.encode("wwwwwiiiikkkkkkkiiippppppeeeeeddddiia"));
		assertEquals("12B1N12B3N24B1N14B",
				RLE.encode("BBBBBBBBBBBBNBBBBBBBBBBBBNNNBBBBBBBBBBBBBBBBBBBBBBBBNBBBBBBBBBBBBBB"));
		assertEquals("12W1B12W3B24W1B14W",
				RLE.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"));
		assertEquals("1W1B1W1B1W1B1W1B1W1B1W1B1W1B", RLE.encode("WBWBWBWBWBWBWB"));

	}

	@Test
	public void decodingTest() {
		assertEquals("W", RLE.decode("1W"));
		assertEquals("WWWW", RLE.decode("4W"));
		assertEquals("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",
				RLE.decode("12W1B12W3B24W1B14W"));
		assertEquals("WBWBWBWBWBWBWB", RLE.decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
		assertEquals("WBWBWBWBWBWBWB", RLE.decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));

	}
}

implement a run-length encoding and decoding system. The codes take a string of uppercase characters, compresses repeated sequences of the same character by recording the length of the sequence, and provides a function to reverse the compression. The output format is flexible as long as the original input can be recreated. The codes also include a demonstration of how this can be achieved using regular expressions.


String string = "abc" + "def";

String string = "abc";
string += "def";

String string = "abc".concat("def");

StringBuilder string = new StringBuilder();
string.append("abc").append("def");

StringBuilder string = new StringBuilder();
string.append("abc");
string.insert(3, "def");

String string = String.format("%s%s", "abc", "def");

String string = "%s%s".formatted("abc", "def");

abcdef

public class Str{
   public static void main(String[] args){
      String s = "hello";
      System.out.println(s + " literal");
      String s2 = s + " literal";
      System.out.println(s2);
   }
}

create two string variables, one with a text value and the other concatenating the original string with another string literal. The code demonstrates various methods of string concatenation in Java, including the use of the plus operator, the String.concat method, StringBuilder, and the String.format or String.formatted methods. The result of each method is displayed.


import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

URLEncoder.encode("http://foo bar/", StandardCharsets.UTF_8)

String encode(String string) {
    StringBuilder encoded = new StringBuilder();
    for (char character : string.toCharArray()) {
        switch (character) {
            /* rfc3986 and html5 */
            case '-', '.', '_', '~', '*' -> encoded.append(character);
            case ' ' -> encoded.append('+');
            default -> {
                if (alphanumeric(character))
                    encoded.append(character);
                else {
                    encoded.append("%");
                    encoded.append("%02x".formatted((int) character));
                }
            }
        }
    }
    return encoded.toString();
}

boolean alphanumeric(char character) {
    return (character >= 'A' && character <= 'Z')
        || (character >= 'a' && character <= 'z')
        || (character >= '0' && character <= '9');
}

http%3a%2f%2ffoo+bar%2f

provide a function to convert a given string into URL encoding format. It replaces special, control, and extended characters with a percent symbol followed by a two-digit hexadecimal code. The conversion applies to all characters except 0-9, A-Z, and a-z. An exception string can be used to specify symbols that don't need conversion. The function can be implemented using Java's URLEncoder and URLDecoder classes or a basic for-loop.