title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Fusc sequence
Java
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
public class FuscSequence { public static void main(String[] args) { System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format"); for ( int n = 0 ; n < 61 ; n++ ) { System.out.printf("%,d ", fusc[n]); } System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n"); int start = 0; for (int i = 0 ; i <= 5 ; i++ ) { int val = i != 0 ? (int) Math.pow(10, i) : -1; for ( int j = start ; j < FUSC_MAX ; j++ ) { if ( fusc[j] > val ) { System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] ); start = j; break; } } } } private static final int FUSC_MAX = 30000000; private static int[] fusc = new int[FUSC_MAX]; static { fusc[0] = 0; fusc[1] = 1; for ( int n = 2 ; n < FUSC_MAX ; n++ ) { fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]); } } }
Gapful numbers
Java from D
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''187''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''187'''. About 7.46% of positive integers are ''gapful''. ;Task: :* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page :* Show the first '''30''' gapful numbers :* Show the first '''15''' gapful numbers >= '''1,000,000''' :* Show the first '''10''' gapful numbers >= '''1,000,000,000''' ;Related tasks: :* Harshad or Niven series. :* palindromic gapful numbers. :* largest number divisible by its digits. ;Also see: :* The OEIS entry: A108343 gapful numbers. :* numbersaplenty gapful numbers
import java.util.List; public class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)); int le = sb.length(); for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ','); } return sb.toString(); } public static void main(String[] args) { List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123); List<Integer> counts = List.of(30, 15, 15, 10, 25); for (int i = 0; i < starts.size(); ++i) { int count = 0; Long j = starts.get(i); long pow = 100; while (j >= pow * 10) { pow *= 10; } System.out.printf("First %d gapful numbers starting at %s:\n", counts.get(i), commatize(starts.get(i))); while (count < counts.get(i)) { long fl = (j / pow) * 10 + (j % 10); if (j % fl == 0) { System.out.printf("%d ", j); count++; } j++; if (j >= 10 * pow) { pow *= 10; } } System.out.println('\n'); } } }
Gauss-Jordan matrix inversion
Java
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
// Matrix.java public class Matrix { private int rows; private int columns; private double[][] elements; public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; elements = new double[rows][columns]; } public void set(int row, int column, double value) { elements[row][column] = value; } public double get(int row, int column) { return elements[row][column]; } public void print() { for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { if (column > 0) System.out.print(' '); System.out.printf("%7.3f", elements[row][column]); } System.out.println(); } } // Returns the inverse of this matrix public Matrix inverse() { assert(rows == columns); // Augment by identity matrix Matrix tmp = new Matrix(rows, columns * 2); for (int row = 0; row < rows; ++row) { System.arraycopy(elements[row], 0, tmp.elements[row], 0, columns); tmp.elements[row][row + columns] = 1; } tmp.toReducedRowEchelonForm(); Matrix inv = new Matrix(rows, columns); for (int row = 0; row < rows; ++row) System.arraycopy(tmp.elements[row], columns, inv.elements[row], 0, columns); return inv; } // Converts this matrix into reduced row echelon form public void toReducedRowEchelonForm() { for (int row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) { int i = row; while (elements[i][lead] == 0) { if (++i == rows) { i = row; if (++lead == columns) return; } } swapRows(i, row); if (elements[row][lead] != 0) { double f = elements[row][lead]; for (int column = 0; column < columns; ++column) elements[row][column] /= f; } for (int j = 0; j < rows; ++j) { if (j == row) continue; double f = elements[j][lead]; for (int column = 0; column < columns; ++column) elements[j][column] -= f * elements[row][column]; } } } // Returns the matrix product of a and b public static Matrix product(Matrix a, Matrix b) { assert(a.columns == b.rows); Matrix result = new Matrix(a.rows, b.columns); for (int i = 0; i < a.rows; ++i) { double[] resultRow = result.elements[i]; double[] aRow = a.elements[i]; for (int j = 0; j < a.columns; ++j) { double[] bRow = b.elements[j]; for (int k = 0; k < b.columns; ++k) resultRow[k] += aRow[j] * bRow[k]; } } return result; } private void swapRows(int i, int j) { double[] tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; } }
Gaussian elimination
Java
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
import java.util.Locale; public class GaussianElimination { public static double solve(double[][] a, double[][] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { throw new IllegalArgumentException("Invalid dimensions"); } int n = b.length, p = b[0].length; if (a.length != n || a[0].length != n) { throw new IllegalArgumentException("Invalid dimensions"); } double det = 1.0; for (int i = 0; i < n - 1; i++) { int k = i; for (int j = i + 1; j < n; j++) { if (Math.abs(a[j][i]) > Math.abs(a[k][i])) { k = j; } } if (k != i) { det = -det; for (int j = i; j < n; j++) { double s = a[i][j]; a[i][j] = a[k][j]; a[k][j] = s; } for (int j = 0; j < p; j++) { double s = b[i][j]; b[i][j] = b[k][j]; b[k][j] = s; } } for (int j = i + 1; j < n; j++) { double s = a[j][i] / a[i][i]; for (k = i + 1; k < n; k++) { a[j][k] -= s * a[i][k]; } for (k = 0; k < p; k++) { b[j][k] -= s * b[i][k]; } } } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { double s = a[i][j]; for (int k = 0; k < p; k++) { b[i][k] -= s * b[j][k]; } } double s = a[i][i]; det *= s; for (int k = 0; k < p; k++) { b[i][k] /= s; } } return det; } public static void main(String[] args) { double[][] a = new double[][] {{4.0, 1.0, 0.0, 0.0, 0.0}, {1.0, 4.0, 1.0, 0.0, 0.0}, {0.0, 1.0, 4.0, 1.0, 0.0}, {0.0, 0.0, 1.0, 4.0, 1.0}, {0.0, 0.0, 0.0, 1.0, 4.0}}; double[][] b = new double[][] {{1.0 / 2.0}, {2.0 / 3.0}, {3.0 / 4.0}, {4.0 / 5.0}, {5.0 / 6.0}}; double[] x = {39.0 / 400.0, 11.0 / 100.0, 31.0 / 240.0, 37.0 / 300.0, 71.0 / 400.0}; System.out.println("det: " + solve(a, b)); for (int i = 0; i < 5; i++) { System.out.printf(Locale.US, "%12.8f %12.4e\n", b[i][0], b[i][0] - x[i]); } } }
Generate Chess960 starting position
Java 1.5+
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); //List.toString adds some human stuff, remove that return pieces; } private static boolean check(String rank){ if(!rank.matches(".*R.*K.*R.*")) return false; //king between rooks if(!rank.matches(".*B(..|....|......|)B.*")) return false; //all possible ways bishops can be placed return true; } public static void main(String[] args){ for(int i = 0; i < 10; i++){ System.out.println(generateFirstRank()); } } }
Generate random chess position
Java
Generate a random chess position in FEN format. The position does not have to be realistic or even balanced, but it must comply to the following rules: :* there is one and only one king of each color (one black king and one white king); :* the kings must not be placed on adjacent squares; :* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank); :* including the kings, up to 32 pieces of either color can be placed. :* There is no requirement for material balance between sides. :* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. :* it is white's turn. :* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); placePieces(grid, "PPPPPPPP", true); placePieces(grid, "pppppppp", true); placePieces(grid, "RNBQBNR", false); placePieces(grid, "rnbqbnr", false); return toFen(grid); } static void placeKings(char[][] grid) { int r1, c1, r2, c2; while (true) { r1 = rand.nextInt(8); c1 = rand.nextInt(8); r2 = rand.nextInt(8); c2 = rand.nextInt(8); if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) break; } grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; } static void placePieces(char[][] grid, String pieces, boolean isPawn) { int numToPlace = rand.nextInt(pieces.length()); for (int n = 0; n < numToPlace; n++) { int r, c; do { r = rand.nextInt(8); c = rand.nextInt(8); } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } static String toFen(char[][] grid) { StringBuilder fen = new StringBuilder(); int countEmpty = 0; for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { char ch = grid[r][c]; System.out.printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append(ch); } } if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append("/"); System.out.println(); } return fen.append(" w - - 0 1").toString(); } }
Generator/Exponential
java 8
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
import java.util.function.LongSupplier; import static java.util.stream.LongStream.generate; public class GeneratorExponential implements LongSupplier { private LongSupplier source, filter; private long s, f; public GeneratorExponential(LongSupplier source, LongSupplier filter) { this.source = source; this.filter = filter; f = filter.getAsLong(); } @Override public long getAsLong() { s = source.getAsLong(); while (s == f) { s = source.getAsLong(); f = filter.getAsLong(); } while (s > f) { f = filter.getAsLong(); } return s; } public static void main(String[] args) { generate(new GeneratorExponential(new SquaresGen(), new CubesGen())) .skip(20).limit(10) .forEach(n -> System.out.printf("%d ", n)); } } class SquaresGen implements LongSupplier { private long n; @Override public long getAsLong() { return n * n++; } } class CubesGen implements LongSupplier { private long n; @Override public long getAsLong() { return n * n * n++; } }
Get system command output
Java 7
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). ;Related task * Execute a system command
import java.io.*; import java.util.*; public class SystemCommand { public static void main(String args[]) throws IOException { String command = "cmd /c dir"; Process p = Runtime.getRuntime().exec(command); try (Scanner sc = new Scanner(p.getInputStream())) { System.out.printf("Output of the command: %s %n%n", command); while (sc.hasNext()) { System.out.println(sc.nextLine()); } } } }
Giuga numbers
Java
Definition A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors '''f''' divide (n/f - 1) exactly. All known Giuga numbers are even though it is not known for certain that there are no odd examples. ;Example 30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and: * 30/2 - 1 = 14 is divisible by 2 * 30/3 - 1 = 9 is divisible by 3 * 30/5 - 1 = 5 is divisible by 5 ;Task Determine and show here the first four Giuga numbers. ;Stretch Determine the fifth Giuga number and any more you have the patience for. ;References * Wikipedia: Giuga number * OEIS:A007850 - Giuga numbers
import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class GiugaNumbers { public static void main(String[] aArgs) { primes = List.of( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59 ); List<Integer> primeCounts = List.of( 3, 4, 5 ); for ( int primeCount : primeCounts ) { primeFactors = new ArrayList<Integer>(Collections.nCopies(primeCount, 0)); combinations(primeCount, 0, 0); } Collections.sort(results); System.out.println("Found Giuga numbers: " + results); } private static void checkIfGiugaNumber(List<Integer> aPrimeFactors) { final int product = aPrimeFactors.stream().reduce(1, Math::multiplyExact); for ( int factor : aPrimeFactors ) { final int divisor = factor * factor; if ( ( product - factor ) % divisor != 0 ) { return; } } results.add(product); } private static void combinations(int aPrimeCount, int aIndex, int aLevel) { if ( aLevel == aPrimeCount ) { checkIfGiugaNumber(primeFactors); return; } for ( int i = aIndex; i < primes.size(); i++ ) { primeFactors.set(aLevel, primes.get(i)); combinations(aPrimeCount, i + 1, aLevel + 1); } } private static List<Integer> primes; private static List<Integer> primeFactors; private static List<Integer> results = new ArrayList<Integer>(); }
Globally replace text in several files
Java 7
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
import java.io.*; import java.nio.file.*; public class GloballyReplaceText { public static void main(String[] args) throws IOException { for (String fn : new String[]{"test1.txt", "test2.txt"}) { String s = new String(Files.readAllBytes(Paths.get(fn))); s = s.replace("Goodbye London!", "Hello New York!"); try (FileWriter fw = new FileWriter(fn)) { fw.write(s); } } } }
Gray code
Java from C
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
Greatest subsequential sum
Java 1.5+
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
import java.util.Scanner; import java.util.ArrayList; public class Sub{ private static int[] indices; public static void main(String[] args){ ArrayList<Long> array= new ArrayList<Long>(); //the main set Scanner in = new Scanner(System.in); while(in.hasNextLong()) array.add(in.nextLong()); long highSum= Long.MIN_VALUE;//start the sum at the lowest possible value ArrayList<Long> highSet= new ArrayList<Long>(); //loop through all possible subarray sizes including 0 for(int subSize= 0;subSize<= array.size();subSize++){ indices= new int[subSize]; for(int i= 0;i< subSize;i++) indices[i]= i; do{ long sum= 0;//this subarray sum variable ArrayList<Long> temp= new ArrayList<Long>();//this subarray //sum it and save it for(long index:indices) {sum+= array.get(index); temp.add(array.get(index));} if(sum > highSum){//if we found a higher sum highSet= temp; //keep track of it highSum= sum; } }while(nextIndices(array));//while we haven't tested all subarrays } System.out.println("Sum: " + highSum + "\nSet: " + highSet); } /** * Computes the next set of choices from the previous. The * algorithm tries to increment the index of the final choice * first. Should that fail (index goes out of bounds), it * tries to increment the next-to-the-last index, and resets * the last index to one more than the next-to-the-last. * Should this fail the algorithm keeps starting at an earlier * choice until it runs off the start of the choice list without * Finding a legal set of indices for all the choices. * * @return true unless all choice sets have been exhausted. * @author James Heliotis */ private static boolean nextIndices(ArrayList<Long> a) { for(int i= indices.length-1;i >= 0;--i){ indices[i]++; for(int j=i+1;j < indices.length;++j){ indices[j]= indices[j - 1] + 1;//reset the last failed try } if(indices[indices.length - 1] < a.size()){//if this try went out of bounds return true; } } return false; } }
Greedy algorithm for Egyptian fractions
Java 9
An Egyptian fraction is the sum of distinct unit fractions such as: :::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48}) Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement :::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil} (simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function). For this task, Proper and improper fractions must be able to be expressed. Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n'']. ;Task requirements: * show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59} * for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has: ::* the largest number of terms, ::* the largest denominator. * for all one-, two-, and three-digit integers, find and show (as above). {extra credit} ;Also see: * Wolfram MathWorld(tm) entry: Egyptian fraction
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class EgyptianFractions { private static BigInteger gcd(BigInteger a, BigInteger b) { if (b.equals(BigInteger.ZERO)) { return a; } return gcd(b, a.mod(b)); } private static class Frac implements Comparable<Frac> { private BigInteger num, denom; public Frac(BigInteger n, BigInteger d) { if (d.equals(BigInteger.ZERO)) { throw new IllegalArgumentException("Parameter d may not be zero."); } BigInteger nn = n; BigInteger dd = d; if (nn.equals(BigInteger.ZERO)) { dd = BigInteger.ONE; } else if (dd.compareTo(BigInteger.ZERO) < 0) { nn = nn.negate(); dd = dd.negate(); } BigInteger g = gcd(nn, dd).abs(); if (g.compareTo(BigInteger.ZERO) > 0) { nn = nn.divide(g); dd = dd.divide(g); } num = nn; denom = dd; } public Frac(int n, int d) { this(BigInteger.valueOf(n), BigInteger.valueOf(d)); } public Frac plus(Frac rhs) { return new Frac( num.multiply(rhs.denom).add(denom.multiply(rhs.num)), rhs.denom.multiply(denom) ); } public Frac unaryMinus() { return new Frac(num.negate(), denom); } public Frac minus(Frac rhs) { return plus(rhs.unaryMinus()); } @Override public int compareTo(Frac rhs) { BigDecimal diff = this.toBigDecimal().subtract(rhs.toBigDecimal()); if (diff.compareTo(BigDecimal.ZERO) < 0) { return -1; } if (BigDecimal.ZERO.compareTo(diff) < 0) { return 1; } return 0; } @Override public boolean equals(Object obj) { if (null == obj || !(obj instanceof Frac)) { return false; } Frac rhs = (Frac) obj; return compareTo(rhs) == 0; } @Override public String toString() { if (denom.equals(BigInteger.ONE)) { return num.toString(); } return String.format("%s/%s", num, denom); } public BigDecimal toBigDecimal() { BigDecimal bdn = new BigDecimal(num); BigDecimal bdd = new BigDecimal(denom); return bdn.divide(bdd, MathContext.DECIMAL128); } public List<Frac> toEgyptian() { if (num.equals(BigInteger.ZERO)) { return Collections.singletonList(this); } List<Frac> fracs = new ArrayList<>(); if (num.abs().compareTo(denom.abs()) >= 0) { Frac div = new Frac(num.divide(denom), BigInteger.ONE); Frac rem = this.minus(div); fracs.add(div); toEgyptian(rem.num, rem.denom, fracs); } else { toEgyptian(num, denom, fracs); } return fracs; } public void toEgyptian(BigInteger n, BigInteger d, List<Frac> fracs) { if (n.equals(BigInteger.ZERO)) { return; } BigDecimal n2 = new BigDecimal(n); BigDecimal d2 = new BigDecimal(d); BigDecimal[] divRem = d2.divideAndRemainder(n2, MathContext.UNLIMITED); BigInteger div = divRem[0].toBigInteger(); if (divRem[1].compareTo(BigDecimal.ZERO) > 0) { div = div.add(BigInteger.ONE); } fracs.add(new Frac(BigInteger.ONE, div)); BigInteger n3 = d.negate().mod(n); if (n3.compareTo(BigInteger.ZERO) < 0) { n3 = n3.add(n); } BigInteger d3 = d.multiply(div); Frac f = new Frac(n3, d3); if (f.num.equals(BigInteger.ONE)) { fracs.add(f); return; } toEgyptian(f.num, f.denom, fracs); } } public static void main(String[] args) { List<Frac> fracs = List.of( new Frac(43, 48), new Frac(5, 121), new Frac(2014, 59) ); for (Frac frac : fracs) { List<Frac> list = frac.toEgyptian(); Frac first = list.get(0); if (first.denom.equals(BigInteger.ONE)) { System.out.printf("%s -> [%s] + ", frac, first); } else { System.out.printf("%s -> %s", frac, first); } for (int i = 1; i < list.size(); ++i) { System.out.printf(" + %s", list.get(i)); } System.out.println(); } for (Integer r : List.of(98, 998)) { if (r == 98) { System.out.println("\nFor proper fractions with 1 or 2 digits:"); } else { System.out.println("\nFor proper fractions with 1, 2 or 3 digits:"); } int maxSize = 0; List<Frac> maxSizeFracs = new ArrayList<>(); BigInteger maxDen = BigInteger.ZERO; List<Frac> maxDenFracs = new ArrayList<>(); boolean[][] sieve = new boolean[r + 1][]; for (int i = 0; i < r + 1; ++i) { sieve[i] = new boolean[r + 2]; } for (int i = 1; i < r; ++i) { for (int j = i + 1; j < r + 1; ++j) { if (sieve[i][j]) continue; Frac f = new Frac(i, j); List<Frac> list = f.toEgyptian(); int listSize = list.size(); if (listSize > maxSize) { maxSize = listSize; maxSizeFracs.clear(); maxSizeFracs.add(f); } else if (listSize == maxSize) { maxSizeFracs.add(f); } BigInteger listDen = list.get(list.size() - 1).denom; if (listDen.compareTo(maxDen) > 0) { maxDen = listDen; maxDenFracs.clear(); maxDenFracs.add(f); } else if (listDen.equals(maxDen)) { maxDenFracs.add(f); } if (i < r / 2) { int k = 2; while (true) { if (j * k > r + 1) break; sieve[i * k][j * k] = true; k++; } } } } System.out.printf(" largest number of items = %s\n", maxSize); System.out.printf("fraction(s) with this number : %s\n", maxSizeFracs); String md = maxDen.toString(); System.out.printf(" largest denominator = %s digits, ", md.length()); System.out.printf("%s...%s\n", md.substring(0, 20), md.substring(md.length() - 20, md.length())); System.out.printf("fraction(s) with this denominator : %s\n", maxDenFracs); } } }
Greyscale bars/Display
Java
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
import javax.swing.* ; import java.awt.* ; public class Greybars extends JFrame { private int width ; private int height ; public Greybars( ) { super( "grey bars example!" ) ; width = 640 ; height = 320 ; setSize( width , height ) ; setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ; setVisible( true ) ; } public void paint ( Graphics g ) { int run = 0 ; double colorcomp = 0.0 ; //component of the color for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) { double colorgap = 255.0 / (columncount - 1) ; //by this gap we change the background color int columnwidth = width / columncount ; int columnheight = height / 4 ; if ( run % 2 == 0 ) //switches color directions with every for loop colorcomp = 0.0 ; else { colorcomp = 255.0 ; colorgap *= -1.0 ; } int ystart = 0 + columnheight * run ; int xstart = 0 ; for ( int i = 0 ; i < columncount ; i++ ) { int icolor = (int)Math.round(colorcomp) ; //round to nearer integer Color nextColor = new Color( icolor , icolor, icolor ) ; g.setColor( nextColor ) ; g.fillRect( xstart , ystart , columnwidth , columnheight ) ; xstart += columnwidth ; colorcomp += colorgap ; } run++ ; } } public static void main( String[ ] args ) { Greybars gb = new Greybars( ) ; } }
Hailstone sequence
Java 1.5+
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class Hailstone { public static List<Long> getHailstoneSequence(long n) { if (n <= 0) throw new IllegalArgumentException("Invalid starting sequence number"); List<Long> list = new ArrayList<Long>(); list.add(Long.valueOf(n)); while (n != 1) { if ((n & 1) == 0) n = n / 2; else n = 3 * n + 1; list.add(Long.valueOf(n)); } return list; } public static void main(String[] args) { List<Long> sequence27 = getHailstoneSequence(27); System.out.println("Sequence for 27 has " + sequence27.size() + " elements: " + sequence27); long MAX = 100000; // Simple way { long highestNumber = 1; int highestCount = 1; for (long i = 2; i < MAX; i++) { int count = getHailstoneSequence(i).size(); if (count > highestCount) { highestCount = count; highestNumber = i; } } System.out.println("Method 1, number " + highestNumber + " has the longest sequence, with a length of " + highestCount); } // More memory efficient way { long highestNumber = 1; int highestCount = 1; for (long i = 2; i < MAX; i++) { int count = 1; long n = i; while (n != 1) { if ((n & 1) == 0) n = n / 2; else n = 3 * n + 1; count++; } if (count > highestCount) { highestCount = count; highestNumber = i; } } System.out.println("Method 2, number " + highestNumber + " has the longest sequence, with a length of " + highestCount); } // Efficient for analyzing all sequences { long highestNumber = 1; long highestCount = 1; Map<Long, Integer> sequenceMap = new HashMap<Long, Integer>(); sequenceMap.put(Long.valueOf(1), Integer.valueOf(1)); List<Long> currentList = new ArrayList<Long>(); for (long i = 2; i < MAX; i++) { currentList.clear(); Long n = Long.valueOf(i); Integer count = null; while ((count = sequenceMap.get(n)) == null) { currentList.add(n); long nValue = n.longValue(); if ((nValue & 1) == 0) n = Long.valueOf(nValue / 2); else n = Long.valueOf(3 * nValue + 1); } int curCount = count.intValue(); for (int j = currentList.size() - 1; j >= 0; j--) sequenceMap.put(currentList.get(j), Integer.valueOf(++curCount)); if (curCount > highestCount) { highestCount = curCount; highestNumber = i; } } System.out.println("Method 3, number " + highestNumber + " has the longest sequence, with a length of " + highestCount); } return; } }
Harshad or Niven series
Java 1.5+
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
public class Harshad{ private static long sumDigits(long n){ long sum = 0; for(char digit:Long.toString(n).toCharArray()){ sum += Character.digit(digit, 10); } return sum; } public static void main(String[] args){ for(int count = 0, i = 1; count < 20;i++){ if(i % sumDigits(i) == 0){ System.out.println(i); count++; } } System.out.println(); for(int i = 1001; ; i++){ if(i % sumDigits(i) == 0){ System.out.println(i); break; } } } }
Hash join
Java 8
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, {"Bob", "foo"}}; hashJoin(table1, 1, table2, 0).stream() .forEach(r -> System.out.println(Arrays.deepToString(r))); } static List<String[][]> hashJoin(String[][] records1, int idx1, String[][] records2, int idx2) { List<String[][]> result = new ArrayList<>(); Map<String, List<String[]>> map = new HashMap<>(); for (String[] record : records1) { List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>()); v.add(record); map.put(record[idx1], v); } for (String[] record : records2) { List<String[]> lst = map.get(record[idx2]); if (lst != null) { lst.stream().forEach(r -> { result.add(new String[][]{r, record}); }); } } return result; } }
Haversine formula
Java from Groovy
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
public class Haversine { public static final double R = 6372.8; // In kilometers public static double haversine(double lat1, double lon1, double lat2, double lon2) { lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double dLat = lat2 - lat1; double dLon = Math.toRadians(lon2 - lon1); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } public static void main(String[] args) { System.out.println(haversine(36.12, -86.67, 33.94, -118.40)); } }
Hello world/Line printer
Java
Cause a line printer attached to the computer to print a line containing the message: Hello World! ;Note: A line printer is not the same as standard output. A line printer was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Hello world/Newbie
Java
Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the [[Hello world/Text]] task. * Assume the language-newbie is a programmer in another language. * Assume the language-newbie is competent in installing software for the platform. * Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor). * Refer to, (and link to), already existing documentation as much as possible (but provide a summary here). * Remember to state where to view the output. * If particular IDE's or editors are required that are not standard, then point to/explain their installation too. ;Note: * If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated. * You may use sub-headings if giving instructions for multiple platforms.
public class HelloWorld { public static void main(String[]args){ HelloWorld hw = new HelloWorld(); hw.run(); } void run(){ //Print 'Hello world!' to console/terminal System.out.println("Hello world!"); } }
Heronian triangles
Java
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
import java.util.ArrayList; public class Heron { public static void main(String[] args) { ArrayList<int[]> list = new ArrayList<>(); for (int c = 1; c <= 200; c++) { for (int b = 1; b <= c; b++) { for (int a = 1; a <= b; a++) { if (gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c))){ int area = (int) heronArea(a, b, c); list.add(new int[]{a, b, c, a + b + c, area}); } } } } sort(list); System.out.printf("Number of primitive Heronian triangles with sides up " + "to 200: %d\n\nFirst ten when ordered by increasing area, then" + " perimeter:\nSides Perimeter Area", list.size()); for (int i = 0; i < 10; i++) { System.out.printf("\n%d x %d x %d %d %d", list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); } System.out.printf("\n\nArea = 210\nSides Perimeter Area"); for (int i = 0; i < list.size(); i++) { if (list.get(i)[4] == 210) System.out.printf("\n%d x %d x %d %d %d", list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); } } public static double heronArea(int a, int b, int c) { double s = (a + b + c) / 2f; return Math.sqrt(s * (s - a) * (s - b) * (s - c)); } public static boolean isHeron(double h) { return h % 1 == 0 && h > 0; } public static int gcd(int a, int b) { int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a; while (leftover != 0) { leftover = dividend % divisor; if (leftover > 0) { dividend = divisor; divisor = leftover; } } return divisor; } public static void sort(ArrayList<int[]> list) { boolean swapped = true; int[] temp; while (swapped) { swapped = false; for (int i = 1; i < list.size(); i++) { if (list.get(i)[4] < list.get(i - 1)[4] || list.get(i)[4] == list.get(i - 1)[4] && list.get(i)[3] < list.get(i - 1)[3]) { temp = list.get(i); list.set(i, list.get(i - 1)); list.set(i - 1, temp); swapped = true; } } } } }
Hickerson series of almost integers
Java
The following function, due to D. Hickerson, is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.) The function is: h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}} It is said to produce "almost integers" for '''n''' between '''1''' and '''17'''. The purpose of the task is to verify this assertion. Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation ;Task: Calculate all values of the function checking and stating which are "almost integers". Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example: h(18) = 3385534663256845326.39...
import java.math.*; public class Hickerson { final static String LN2 = "0.693147180559945309417232121458"; public static void main(String[] args) { for (int n = 1; n <= 17; n++) System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n)); } static boolean almostInteger(int n) { BigDecimal a = new BigDecimal(LN2); a = a.pow(n + 1).multiply(BigDecimal.valueOf(2)); long f = n; while (--n > 1) f *= n; BigDecimal b = new BigDecimal(f); b = b.divide(a, MathContext.DECIMAL128); BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN); return c.toString().matches("0|9"); } }
History variables
Java
''Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' ''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables. '' "History Variables: The Semantics, Formal Correctness, and Implementation of History Variables in an Imperative Programming Language" by Mallon and Takaoka Concept also discussed on LtU and Patents.com. ;Task: Demonstrate History variable support: * enable history variable support (if needed) * define a history variable * assign three values * non-destructively display the history * recall the three values. For extra points, if the language of choice does not support history variables, demonstrate how this might be implemented.
import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * A class for an "Integer with a history". * <p> * Note that it is not possible to create an empty Variable (so there is no "null") with this type. This is a design * choice, because if "empty" variables were allowed, reading of empty variables must return a value. Null is a * bad idea, and Java 8's Optional<T> (which is somewhat like the the official fix for the null-bad-idea) would * make things more complicated than an example should be. */ public class IntegerWithHistory { /** * The "storage Backend" is a list of all values that have been ever assigned to this variable. The List is * populated front to back, so a new value is inserted at the start (position 0), and older values move toward the end. */ private final List<Integer> history; /** * Creates this variable and assigns the initial value * * @param value initial value */ public IntegerWithHistory(Integer value) { history = new LinkedList<>(); history.add(value); } /** * Sets a new value, pushing the older ones back in the history * * @param value the new value to be assigned */ public void set(Integer value) { //History is populated from the front to the back, so the freshest value is stored a position 0 history.add(0, value); } /** * Gets the current value. Since history is populuated front to back, the current value is the first element * of the history. * * @return the current value */ public Integer get() { return history.get(0); } /** * Gets the entire history all values that have been assigned to this variable. * * @return a List of all values, including the current one, ordered new to old */ public List<Integer> getHistory() { return Collections.unmodifiableList(this.history); } /** * Rolls back the history one step, so the current value is removed from the history and replaced by it's predecessor. * This is a destructive operation! It is not possible to rollback() beyond the initial value! * * @return the value that had been the current value until history was rolled back. */ public Integer rollback() { if (history.size() > 1) { return history.remove(0); } else { return history.get(0); } } }
Hofstadter-Conway $10,000 sequence
Java
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
// Title: Hofstadter-Conway $10,000 sequence public class HofstadterConwaySequence { private static int MAX = (int) Math.pow(2, 20) + 1; private static int[] HCS = new int[MAX]; static { HCS[1] = 1; HCS[2] = 1; for ( int n = 3 ; n < MAX ; n++ ) { int nm1 = HCS[n - 1]; HCS[n] = HCS[nm1] + HCS[n - nm1]; } } public static void main(String[] args) { int mNum = 0; for ( int m = 1 ; m < 20 ; m++ ) { int min = (int) Math.pow(2, m); int max = min * 2; double maxRatio = 0.0; int nVal = 0; for ( int n = min ; n <= max ; n ++ ) { double ratio = (double) HCS[n] / n; if ( ratio > maxRatio ) { maxRatio = Math.max(ratio, maxRatio); nVal = n; } if ( ratio >= 0.55 ) { mNum = n; } } System.out.printf("Max ratio between 2^%d and 2^%d is %f at n = %,d%n", m, m+1, maxRatio, nVal); } System.out.printf("Mallow's number is %d.%n", mNum); } }
Hofstadter Figure-Figure sequences
Java
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
Hofstadter Q sequence
Java 1.5+
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001];//not part of the task public static int Q(int n){ nUses[n]++;//not part of the task if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6;//value for Q(10) int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); //Optional stuff below here int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Honeycombs
Java
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should display a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen. Optionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.) [[image:honeycomb.gif]]
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Honeycombs extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new Honeycombs(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }); } public Honeycombs() { add(new HoneycombsPanel(), BorderLayout.CENTER); setTitle("Honeycombs"); setResizable(false); pack(); setLocationRelativeTo(null); } } class HoneycombsPanel extends JPanel { Hexagon[] comb; public HoneycombsPanel() { setPreferredSize(new Dimension(600, 500)); setBackground(Color.white); setFocusable(true); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { for (Hexagon hex : comb) if (hex.contains(e.getX(), e.getY())) { hex.setSelected(); break; } repaint(); } }); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { for (Hexagon hex : comb) if (hex.letter == Character.toUpperCase(e.getKeyChar())) { hex.setSelected(); break; } repaint(); } }); char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); comb = new Hexagon[20]; int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; for (int i = 0; i < comb.length; i++) { int x, y; if (i < 12) { x = x1 + (i % 3) * w; y = y1 + (i / 3) * h; } else { x = x2 + (i % 2) * w; y = y2 + ((i - 12) / 2) * h; } comb[i] = new Hexagon(x, y, w / 3, letters[i]); } requestFocus(); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(new Font("SansSerif", Font.BOLD, 30)); g.setStroke(new BasicStroke(3)); for (Hexagon hex : comb) hex.draw(g); } } class Hexagon extends Polygon { final Color baseColor = Color.yellow; final Color selectedColor = Color.magenta; final char letter; private boolean hasBeenSelected; Hexagon(int x, int y, int halfWidth, char c) { letter = c; for (int i = 0; i < 6; i++) addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), (int) (y + halfWidth * Math.sin(i * Math.PI / 3))); getBounds(); } void setSelected() { hasBeenSelected = true; } void draw(Graphics2D g) { g.setColor(hasBeenSelected ? selectedColor : baseColor); g.fillPolygon(this); g.setColor(Color.black); g.drawPolygon(this); g.setColor(hasBeenSelected ? Color.black : Color.red); drawCenteredString(g, String.valueOf(letter)); } void drawCenteredString(Graphics2D g, String s) { FontMetrics fm = g.getFontMetrics(); int asc = fm.getAscent(); int dec = fm.getDescent(); int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); g.drawString(s, x, y); } }
Horner's rule for polynomial evaluation
Java 1.5+
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Horner { public static void main(String[] args){ List<Double> coeffs = new ArrayList<Double>(); coeffs.add(-19.0); coeffs.add(7.0); coeffs.add(-4.0); coeffs.add(6.0); System.out.println(polyEval(coeffs, 3)); } public static double polyEval(List<Double> coefficients, double x) { Collections.reverse(coefficients); Double accumulator = coefficients.get(0); for (int i = 1; i < coefficients.size(); i++) { accumulator = (accumulator * x) + (Double) coefficients.get(i); } return accumulator; } }
ISBN13 check digit
Java
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
public static void main(String[] args) { String[] isbn13s = { "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" }; for (String isbn13 : isbn13s) System.out.printf("%s %b%n", isbn13, validateISBN13(isbn13)); } static boolean validateISBN13(String string) { int[] digits = digits(string.strip().replace("-", "")); return digits[12] == checksum(digits); } static int[] digits(String string) { int[] digits = new int[13]; int index = 0; for (char character : string.toCharArray()) { if (character < '0' || character > '9') throw new IllegalArgumentException("Invalid ISBN-13"); /* convert ascii to integer */ digits[index++] = Character.digit(character, 10); } return digits; } static int checksum(int[] digits) { int total = 0; int index = 0; for (int digit : digits) { if (index == 12) break; if (index++ % 2 == 1) digit *= 3; total += digit; } return 10 - (total % 10); }
I before E except after C
Java
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plausible."); } boolean isPlausibleRule(String filename) { int truecount=0,falsecount=0; try { BufferedReader br=new BufferedReader(new FileReader(filename)); String word; while((word=br.readLine())!=null) { if(isPlausibleWord(word)) truecount++; else if(isOppPlausibleWord(word)) falsecount++; } br.close(); } catch(Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } System.out.println("Plausible count: "+truecount); System.out.println("Implausible count: "+falsecount); if(truecount>2*falsecount) return true; return false; } boolean isPlausibleWord(String word) { if(!word.contains("c")&&word.contains("ie")) return true; else if(word.contains("cei")) return true; return false; } boolean isOppPlausibleWord(String word) { if(!word.contains("c")&&word.contains("ei")) return true; else if(word.contains("cie")) return true; return false; } }
Identity matrix
Java
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
public class PrintIdentityMatrix { public static void main(String[] args) { int n = 5; int[][] array = new int[n][n]; IntStream.range(0, n).forEach(i -> array[i][i] = 1); Arrays.stream(array) .map((int[] a) -> Arrays.toString(a)) .forEach(System.out::println); } }
Idiomatically determine all the characters that can be used for symbols
Java 8
Idiomatically determine all the characters that can be used for ''symbols''. The word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''. The method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. You may want to mention what hardware architecture is being used, and if applicable, the operating system. Note that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned). ;See also * Idiomatically determine all the lowercase and uppercase letters.
import java.util.function.IntPredicate; import java.util.stream.IntStream; public class Test { public static void main(String[] args) throws Exception { print("Java Identifier start: ", 0, 0x10FFFF, 72, Character::isJavaIdentifierStart, "%c"); print("Java Identifier part: ", 0, 0x10FFFF, 25, Character::isJavaIdentifierPart, "[%d]"); print("Identifier ignorable: ", 0, 0x10FFFF, 25, Character::isIdentifierIgnorable, "[%d]"); print("Unicode Identifier start: ", 0, 0x10FFFF, 72, Character::isUnicodeIdentifierStart, "%c"); print("Unicode Identifier part : ", 0, 0x10FFFF, 25, Character::isUnicodeIdentifierPart, "[%d]"); } static void print(String msg, int start, int end, int limit, IntPredicate p, String fmt) { System.out.print(msg); IntStream.rangeClosed(start, end) .filter(p) .limit(limit) .forEach(cp -> System.out.printf(fmt, cp)); System.out.println("..."); } }
Idiomatically determine all the lowercase and uppercase letters
Java 8
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all: ::::::* lowercase letters ::::::* uppercase letters that can be used (allowed) by the computer program, where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. You may want to mention what hardware architecture is being used, and if applicable, the operating system. ;See also * Idiomatically determine all the characters that can be used for symbols.
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); System.out.print("Lower case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isLowerCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); } }
Imaginary base numbers
Java from Kotlin
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. ''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]'' Other imaginary bases are possible too but are not as widely discussed and aren't specifically named. '''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. At a minimum, support quater-imaginary (base 2i). For extra kudos, support positive or negative bases 2i through 6i (or higher). As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base. See Wikipedia: Quater-imaginary_base for more details. For reference, here are some some decimal and complex numbers converted to quater-imaginary. Base 10 Base 2i 1 1 2 2 3 3 4 10300 5 10301 6 10302 7 10303 8 10200 9 10201 10 10202 11 10203 12 10100 13 10101 14 10102 15 10103 16 10000 Base 10 Base 2i -1 103 -2 102 -3 101 -4 100 -5 203 -6 202 -7 201 -8 200 -9 303 -10 302 -11 301 -12 300 -13 1030003 -14 1030002 -15 1030001 -16 1030000 Base 10 Base 2i 1i 10.2 2i 10.0 3i 20.2 4i 20.0 5i 30.2 6i 30.0 7i 103000.2 8i 103000.0 9i 103010.2 10i 103010.0 11i 103020.2 12i 103020.0 13i 103030.2 14i 103030.0 15i 102000.2 16i 102000.0 Base 10 Base 2i -1i 0.2 -2i 1030.0 -3i 1030.2 -4i 1020.0 -5i 1020.2 -6i 1010.0 -7i 1010.2 -8i 1000.0 -9i 1000.2 -10i 2030.0 -11i 2030.2 -12i 2020.0 -13i 2020.2 -14i 2010.0 -15i 2010.2 -16i 2000.0
public class ImaginaryBaseNumber { private static class Complex { private Double real, imag; public Complex(double r, double i) { this.real = r; this.imag = i; } public Complex(int r, int i) { this.real = (double) r; this.imag = (double) i; } public Complex add(Complex rhs) { return new Complex( real + rhs.real, imag + rhs.imag ); } public Complex times(Complex rhs) { return new Complex( real * rhs.real - imag * rhs.imag, real * rhs.imag + imag * rhs.real ); } public Complex times(double rhs) { return new Complex( real * rhs, imag * rhs ); } public Complex inv() { double denom = real * real + imag * imag; return new Complex( real / denom, -imag / denom ); } public Complex unaryMinus() { return new Complex(-real, -imag); } public Complex divide(Complex rhs) { return this.times(rhs.inv()); } // only works properly if 'real' and 'imag' are both integral public QuaterImaginary toQuaterImaginary() { if (real == 0.0 && imag == 0.0) return new QuaterImaginary("0"); int re = real.intValue(); int im = imag.intValue(); int fi = -1; StringBuilder sb = new StringBuilder(); while (re != 0) { int rem = re % -4; re /= -4; if (rem < 0) { rem += 4; re++; } sb.append(rem); sb.append(0); } if (im != 0) { Double f = new Complex(0.0, imag).divide(new Complex(0.0, 2.0)).real; im = ((Double) Math.ceil(f)).intValue(); f = -4.0 * (f - im); int index = 1; while (im != 0) { int rem = im % -4; im /= -4; if (rem < 0) { rem += 4; im++; } if (index < sb.length()) { sb.setCharAt(index, (char) (rem + 48)); } else { sb.append(0); sb.append(rem); } index += 2; } fi = f.intValue(); } sb.reverse(); if (fi != -1) sb.append(".").append(fi); while (sb.charAt(0) == '0') sb.deleteCharAt(0); if (sb.charAt(0) == '.') sb.insert(0, '0'); return new QuaterImaginary(sb.toString()); } @Override public String toString() { double real2 = real == -0.0 ? 0.0 : real; // get rid of negative zero double imag2 = imag == -0.0 ? 0.0 : imag; // ditto String result = imag2 >= 0.0 ? String.format("%.0f + %.0fi", real2, imag2) : String.format("%.0f - %.0fi", real2, -imag2); result = result.replace(".0 ", " ").replace(".0i", "i").replace(" + 0i", ""); if (result.startsWith("0 + ")) result = result.substring(4); if (result.startsWith("0 - ")) result = result.substring(4); return result; } } private static class QuaterImaginary { private static final Complex TWOI = new Complex(0.0, 2.0); private static final Complex INVTWOI = TWOI.inv(); private String b2i; public QuaterImaginary(String b2i) { if (b2i.equals("") || !b2i.chars().allMatch(c -> "0123.".indexOf(c) > -1) || b2i.chars().filter(c -> c == '.').count() > 1) { throw new RuntimeException("Invalid Base 2i number"); } this.b2i = b2i; } public Complex toComplex() { int pointPos = b2i.indexOf("."); int posLen = pointPos != -1 ? pointPos : b2i.length(); Complex sum = new Complex(0, 0); Complex prod = new Complex(1, 0); for (int j = 0; j < posLen; ++j) { double k = b2i.charAt(posLen - 1 - j) - '0'; if (k > 0.0) sum = sum.add(prod.times(k)); prod = prod.times(TWOI); } if (pointPos != -1) { prod = INVTWOI; for (int j = posLen + 1; j < b2i.length(); ++j) { double k = b2i.charAt(j) - '0'; if (k > 0.0) sum = sum.add(prod.times(k)); prod = prod.times(INVTWOI); } } return sum; } @Override public String toString() { return b2i; } } public static void main(String[] args) { String fmt = "%4s -> %8s -> %4s"; for (int i = 1; i <= 16; ++i) { Complex c1 = new Complex(i, 0); QuaterImaginary qi = c1.toQuaterImaginary(); Complex c2 = qi.toComplex(); System.out.printf(fmt + " ", c1, qi, c2); c1 = c2.unaryMinus(); qi = c1.toQuaterImaginary(); c2 = qi.toComplex(); System.out.printf(fmt, c1, qi, c2); System.out.println(); } System.out.println(); for (int i = 1; i <= 16; ++i) { Complex c1 = new Complex(0, i); QuaterImaginary qi = c1.toQuaterImaginary(); Complex c2 = qi.toComplex(); System.out.printf(fmt + " ", c1, qi, c2); c1 = c2.unaryMinus(); qi = c1.toQuaterImaginary(); c2 = qi.toComplex(); System.out.printf(fmt, c1, qi, c2); System.out.println(); } } }
Include a file
Java
Demonstrate the language's ability to include source code from other files. ;See Also * [[Compiler/Simple file inclusion pre processor]]
public class Class1 { Class2 c2=new Class2(); static void main(String[] args) { c2.func1(); c2.func2(); } }
Increasing gaps between consecutive Niven numbers
Java
Note: '''Niven''' numbers are also called '''Harshad''' numbers. :::: They are also called '''multidigital''' numbers. '''Niven''' numbers are positive integers which are evenly divisible by the sum of its digits (expressed in base ten). ''Evenly divisible'' means ''divisible with no remainder''. ;Task: :* find the gap (difference) of a Niven number from the previous Niven number :* if the gap is ''larger'' than the (highest) previous gap, then: :::* show the index (occurrence) of the gap (the 1st gap is '''1''') :::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''') :::* show the Niven number that starts the gap :::* show all numbers with comma separators where appropriate (optional) :::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864''' :* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number :* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer :* show all output here, on this page ;Related task: :* Harshad or Niven series. ;Also see: :* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers. :* (PDF) version of the (above) article by Doyon.
public class NivenNumberGaps { // Title: Increasing gaps between consecutive Niven numbers public static void main(String[] args) { long prevGap = 0; long prevN = 1; long index = 0; System.out.println("Gap Gap Index Starting Niven"); for ( long n = 2 ; n < 20_000_000_000l ; n++ ) { if ( isNiven(n) ) { index++; long curGap = n - prevN; if ( curGap > prevGap ) { System.out.printf("%3d %,13d %,15d%n", curGap, index, prevN); prevGap = curGap; } prevN = n; } } } public static boolean isNiven(long n) { long sum = 0; long nSave = n; while ( n > 0 ) { sum += n % 10; n /= 10; } return nSave % sum == 0; } }
Index finite lists of positive integers
Java
It is known that the set of finite lists of positive integers is countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. ;Task: Implement such a mapping: :* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers. :* write a function ''unrank'' which is the ''rank'' inverse function. Demonstrate your solution by: :* picking a random-length list of random positive integers :* turn it into an integer, and :* get the list back. There are many ways to do this. Feel free to choose any one you like. ;Extra credit: Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
Translation of [[Index_finite_lists_of_positive_integers#Python|Python]] via [[Index_finite_lists_of_positive_integers#D|D]]
Index finite lists of positive integers
Java 8
It is known that the set of finite lists of positive integers is countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. ;Task: Implement such a mapping: :* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers. :* write a function ''unrank'' which is the ''rank'' inverse function. Demonstrate your solution by: :* picking a random-length list of random positive integers :* turn it into an integer, and :* get the list back. There are many ways to do this. Feel free to choose any one you like. ;Extra credit: Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
import java.math.BigInteger; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.Collectors.*; public class Test3 { static BigInteger rank(int[] x) { String s = stream(x).mapToObj(String::valueOf).collect(joining("F")); return new BigInteger(s, 16); } static List<BigInteger> unrank(BigInteger n) { BigInteger sixteen = BigInteger.valueOf(16); String s = ""; while (!n.equals(BigInteger.ZERO)) { s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s; n = n.divide(sixteen); } return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList()); } public static void main(String[] args) { int[] s = {1, 2, 3, 10, 100, 987654321}; System.out.println(Arrays.toString(s)); System.out.println(rank(s)); System.out.println(unrank(rank(s))); } }
Integer overflow
Java
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
public class IntegerOverflow { public static void main(String[] args) { System.out.println("Signed 32-bit:"); System.out.println(-(-2147483647 - 1)); System.out.println(2000000000 + 2000000000); System.out.println(-2147483647 - 2147483647); System.out.println(46341 * 46341); System.out.println((-2147483647 - 1) / -1); System.out.println("Signed 64-bit:"); System.out.println(-(-9223372036854775807L - 1)); System.out.println(5000000000000000000L + 5000000000000000000L); System.out.println(-9223372036854775807L - 9223372036854775807L); System.out.println(3037000500L * 3037000500L); System.out.println((-9223372036854775807L - 1) / -1); } }
Integer overflow
Java 8
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
import Math.{addExact => ++, multiplyExact => **, negateExact => ~~, subtractExact => --} def requireOverflow(f: => Unit) = try {f; println("Undetected overflow")} catch{case e: Exception => /* caught */} println("Testing overflow detection for 32-bit unsigned integers") requireOverflow(~~(--(~~(2147483647), 1))) // -(-2147483647-1) requireOverflow(++(2000000000, 2000000000)) // 2000000000 + 2000000000 requireOverflow(--(~~(2147483647), 2147483647)) // -2147483647 + 2147483647 requireOverflow(**(46341, 46341)) // 46341 * 46341 requireOverflow(**(--(~~(2147483647),1), -1)) // same as (-2147483647-1) / -1 println("Test - Expect Undetected overflow:") requireOverflow(++(1,1)) // Undetected overflow
Integer sequence
Java
Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library. If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
import java.math.BigInteger; public class Count{ public static void main(String[] args){ for(BigInteger i = BigInteger.ONE; ;i = i.add(BigInteger.ONE)) System.out.println(i); } }
Intersecting number wheels
Java
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
package intersectingNumberWheels; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; public class WheelController { private static final String IS_NUMBER = "[0-9]"; private static final int TWENTY = 20; private static Map<String, WheelModel> wheelMap; public static void advance(String wheel) { WheelModel w = wheelMap.get(wheel); if (w.list.get(w.position).matches(IS_NUMBER)) { w.printThePosition(); w.advanceThePosition(); } else { String wheelName = w.list.get(w.position); advance(wheelName); w.advanceThePosition(); } } public static void run() { System.out.println(wheelMap); IntStream.rangeClosed(1, TWENTY).forEach(i -> advance("A")); System.out.println(); wheelMap.clear(); } public static void main(String[] args) { wheelMap = new HashMap<>(); wheelMap.put("A", new WheelModel("A", "1", "2", "3")); run(); wheelMap.put("A", new WheelModel("A", "1", "B", "2")); wheelMap.put("B", new WheelModel("B", "3", "4")); run(); wheelMap.put("A", new WheelModel("A", "1", "D", "D")); wheelMap.put("D", new WheelModel("D", "6", "7", "8")); run(); wheelMap.put("A", new WheelModel("A", "1", "B", "C")); wheelMap.put("B", new WheelModel("B", "3", "4")); wheelMap.put("C", new WheelModel("C", "5", "B")); run(); } } class WheelModel { String name; List<String> list; int position; int endPosition; private static final int INITIAL = 0; public WheelModel(String name, String... values) { super(); this.name = name.toUpperCase(); this.list = new ArrayList<>(); for (String value : values) { list.add(value); } this.position = INITIAL; this.endPosition = this.list.size() - 1; } @Override public String toString() { return list.toString(); } public void advanceThePosition() { if (this.position == this.endPosition) { this.position = INITIAL;// new beginning } else { this.position++;// advance position } } public void printThePosition() { System.out.print(" " + this.list.get(position)); } }
Inverted syntax
Java
'''Inverted syntax with conditional expressions''' In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumbrella=true IF raining=true '''Inverted syntax with assignment''' In traditional syntax, assignments are usually expressed with the variable appearing before the expression: a = 6 In inverted syntax, the expression appears before the variable: 6 = a '''Task''' The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
The closest Java comes to placing an action before a condition is with do ... while(condition);
Isqrt (integer square root) of X
Java from Kotlin
Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a real non-negative number. Often '''X''' is actually a non-negative integer. For the purposes of this task, '''X''' can be an integer or a real number, but if it simplifies things in your computer programming language, assume it's an integer. One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or primes) up to the X of that integer, either to find the factors of that integer, or to determine primality. An alternative method for finding the '''Isqrt''' of a number is to calculate: floor( sqrt(X) ) ::* where '''sqrt''' is the square root function for non-negative real numbers, and ::* where '''floor''' is the floor function for real numbers. If the hardware supports the computation of (real) square roots, the above method might be a faster method for small numbers that don't have very many significant (decimal) digits. However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support. ;Pseudo-code using quadratic residue: For this task, the integer square root of a non-negative number will be computed using a version of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are used, only integer arithmetic. Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions. The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support. Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers): q <-- 1 /*initialize Q to unity. */ /*find a power of 4 that's greater than X.*/ perform while q <= x /*perform while Q <= X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ /*Q is now greater than X.*/ z <-- x /*set Z to the value of X.*/ r <-- 0 /*initialize R to zero. */ perform while q > 1 /*perform while Q > unity. */ q <-- q / 4 /*integer divide by four. */ t <-- z - r - q /*compute value of T. */ r <-- r / 2 /*integer divide by two. */ if t >= 0 then do z <-- t /*set Z to value of T. */ r <-- r + q /*compute new value of R. */ end end /*perform*/ /*R is now the Isqrt(X). */ /* Sidenote: Also, Z is now the remainder after square root (i.e. */ /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */ Another version for the (above) 1st '''perform''' is: perform until q > X /*perform until Q > X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ Integer square roots of some values: Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9 Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10 Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10 Isqrt( 3) is 1 Isqrt(63) is 7 Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10 Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11 Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11 Isqrt( 7) is 2 Isqrt(67) is 8 Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11 Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12 Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12 ;Task: Compute and show all output here (on this page) for: ::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format. ::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format. ::* use commas in the displaying of larger numbers. You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code. If your computer programming language only supports smaller integers, show what you can. ;Related tasks: :* sequence of non-squares :* integer roots :* square root by hand
import java.math.BigInteger; public class Isqrt { private static BigInteger isqrt(BigInteger x) { if (x.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException("Argument cannot be negative"); } var q = BigInteger.ONE; while (q.compareTo(x) <= 0) { q = q.shiftLeft(2); } var z = x; var r = BigInteger.ZERO; while (q.compareTo(BigInteger.ONE) > 0) { q = q.shiftRight(2); var t = z; t = t.subtract(r); t = t.subtract(q); r = r.shiftRight(1); if (t.compareTo(BigInteger.ZERO) >= 0) { z = t; r = r.add(q); } } return r; } public static void main(String[] args) { System.out.println("The integer square root of integers from 0 to 65 are:"); for (int i = 0; i <= 65; i++) { System.out.printf("%s ", isqrt(BigInteger.valueOf(i))); } System.out.println(); System.out.println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:"); System.out.println("power 7 ^ power integer square root"); System.out.println("----- --------------------------------------------------------------------------------- -----------------------------------------"); var pow7 = BigInteger.valueOf(7); var bi49 = BigInteger.valueOf(49); for (int i = 1; i < 74; i += 2) { System.out.printf("%2d %,84d %,41d\n", i, pow7, isqrt(pow7)); pow7 = pow7.multiply(bi49); } } }
Iterated digits squaring
Java 8
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
import java.util.stream.IntStream; public class IteratedDigitsSquaring { public static void main(String[] args) { long r = IntStream.range(1, 100_000_000) .parallel() .filter(n -> calc(n) == 89) .count(); System.out.println(r); } private static int calc(int n) { while (n != 89 && n != 1) { int total = 0; while (n > 0) { total += Math.pow(n % 10, 2); n /= 10; } n = total; } return n; } }
JSON
Java
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
import com.google.gson.Gson; public class JsonExample { public static void main(String[] args) { Gson gson = new Gson(); String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"; MyJsonObject obj = gson.fromJson(json, MyJsonObject.class); System.out.println(obj.getFoo()); for(String bar : obj.getBar()) { System.out.println(bar); } obj = new MyJsonObject(2, new String[] { "20", "oranges" }); json = gson.toJson(obj); System.out.println(json); } } class MyJsonObject { private int foo; private String[] bar; public MyJsonObject(int foo, String[] bar) { this.foo = foo; this.bar = bar; } public int getFoo() { return foo; } public String[] getBar() { return bar; } }
Jacobi symbol
Java
The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) * (a | p) 1 if a is a square (mod p) * (a | p) -1 if a is not a square (mod p) * (a | p) 0 if a 0 If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n). ;Task: Calculate the Jacobi symbol (a | n). ;Reference: * Wikipedia article on Jacobi symbol.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } // Compute (k n), where k is numerator private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
Jacobsthal numbers
Java
'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 x Jn-2 Terms may be calculated directly using one of several possible formulas: Jn = ( 2n - (-1)n ) / 3 '''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''. Terms may be calculated directly using one of several possible formulas: JLn = 2n + (-1)n '''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''. '''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime. ;Task * Find and display the first 30 '''Jacobsthal numbers''' * Find and display the first 30 '''Jacobsthal-Lucas numbers''' * Find and display the first 20 '''Jacobsthal oblong numbers''' * Find and display at least the first 10 '''Jacobsthal primes''' ;See also ;* Wikipedia: Jacobsthal number ;* Numbers Aplenty - Jacobsthal number ;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers) ;* OEIS:A014551 - Jacobsthal-Lucas numbers. ;* OEIS:A084175 - Jacobsthal oblong numbers ;* OEIS:A049883 - Primes in the Jacobsthal sequence ;* Related task: Fibonacci sequence ;* Related task: Leonardo numbers
import java.math.BigInteger; public final class JacobsthalNumbers { public static void main(String[] aArgs) { System.out.println("The first 30 Jacobsthal Numbers:"); for ( int i = 0; i < 6; i++ ) { for ( int k = 0; k < 5; k++ ) { System.out.print(String.format("%15s", jacobsthalNumber(i * 5 + k))); } System.out.println(); } System.out.println(); System.out.println("The first 30 Jacobsthal-Lucas Numbers:"); for ( int i = 0; i < 6; i++ ) { for ( int k = 0; k < 5; k++ ) { System.out.print(String.format("%15s", jacobsthalLucasNumber(i * 5 + k))); } System.out.println(); } System.out.println(); System.out.println("The first 20 Jacobsthal oblong Numbers:"); for ( int i = 0; i < 4; i++ ) { for ( int k = 0; k < 5; k++ ) { System.out.print(String.format("%15s", jacobsthalOblongNumber(i * 5 + k))); } System.out.println(); } System.out.println(); System.out.println("The first 10 Jacobsthal Primes:"); for ( int i = 0; i < 10; i++ ) { System.out.println(jacobsthalPrimeNumber(i)); } } private static BigInteger jacobsthalNumber(int aIndex) { BigInteger value = BigInteger.valueOf(parityValue(aIndex)); return BigInteger.ONE.shiftLeft(aIndex).subtract(value).divide(THREE); } private static long jacobsthalLucasNumber(int aIndex) { return ( 1 << aIndex ) + parityValue(aIndex); } private static long jacobsthalOblongNumber(int aIndex) { long nextJacobsthal = jacobsthalNumber(aIndex + 1).longValueExact(); long result = currentJacobsthal * nextJacobsthal; currentJacobsthal = nextJacobsthal; return result; } private static long jacobsthalPrimeNumber(int aIndex) { BigInteger candidate = jacobsthalNumber(latestIndex++); while ( ! candidate.isProbablePrime(CERTAINTY) ) { candidate = jacobsthalNumber(latestIndex++); } return candidate.longValueExact(); } private static int parityValue(int aIndex) { return ( aIndex & 1 ) == 0 ? +1 : -1; } private static long currentJacobsthal = 0; private static int latestIndex = 0; private static final BigInteger THREE = BigInteger.valueOf(3); private static final int CERTAINTY = 20; }
Jaro similarity
Java
The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match. ;;Definition The Jaro similarity d_j of two given strings s_1 and s_2 is : d_j = \left\{ \begin{array}{l l} 0 & \text{if }m = 0\\ \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right. Where: * m is the number of ''matching characters''; * t is half the number of ''transpositions''. Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters. Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one. ;;Example Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find: * m = 4 * |s_1| = 6 * |s_2| = 5 * t = 0 We find a Jaro score of: : d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822 ;Task Implement the Jaro algorithm and show the similarity scores for each of the following pairs: * ("MARTHA", "MARHTA") * ("DIXON", "DICKSONX") * ("JELLYFISH", "SMELLYFISH") ; See also * Jaro-Winkler distance on Wikipedia.
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boolean[] t_matches = new boolean[t_len]; int matches = 0; int transpositions = 0; for (int i = 0; i < s_len; i++) { int start = Integer.max(0, i-match_distance); int end = Integer.min(i+match_distance+1, t_len); for (int j = start; j < end; j++) { if (t_matches[j]) continue; if (s.charAt(i) != t.charAt(j)) continue; s_matches[i] = true; t_matches[j] = true; matches++; break; } } if (matches == 0) return 0; int k = 0; for (int i = 0; i < s_len; i++) { if (!s_matches[i]) continue; while (!t_matches[k]) k++; if (s.charAt(i) != t.charAt(k)) transpositions++; k++; } return (((double)matches / s_len) + ((double)matches / t_len) + (((double)matches - transpositions/2.0) / matches)) / 3.0; } public static void main(String[] args) { System.out.println(jaro( "MARTHA", "MARHTA")); System.out.println(jaro( "DIXON", "DICKSONX")); System.out.println(jaro("JELLYFISH", "SMELLYFISH")); } }
Jewels and stones
Java
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
import java.util.HashSet; import java.util.Set; public class App { private static int countJewels(String stones, String jewels) { Set<Character> bag = new HashSet<>(); for (char c : jewels.toCharArray()) { bag.add(c); } int count = 0; for (char c : stones.toCharArray()) { if (bag.contains(c)) { count++; } } return count; } public static void main(String[] args) { System.out.println(countJewels("aAAbbbb", "aA")); System.out.println(countJewels("ZZ", "z")); } }
Julia set
Java 8
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.stream.IntStream; public class JuliaSet extends JPanel { private static final int MAX_ITERATIONS = 300; private static final double ZOOM = 1; private static final double CX = -0.7; private static final double CY = 0.27015; private static final double MOVE_X = 0; private static final double MOVE_Y = 0; public JuliaSet() { setPreferredSize(new Dimension(800, 600)); setBackground(Color.white); } void drawJuliaSet(Graphics2D g) { int w = getWidth(); int h = getHeight(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); IntStream.range(0, w).parallel().forEach(x -> { IntStream.range(0, h).parallel().forEach(y -> { double zx = 1.5 * (x - w / 2) / (0.5 * ZOOM * w) + MOVE_X; double zy = (y - h / 2) / (0.5 * ZOOM * h) + MOVE_Y; float i = MAX_ITERATIONS; while (zx * zx + zy * zy < 4 && i > 0) { double tmp = zx * zx - zy * zy + CX; zy = 2.0 * zx * zy + CY; zx = tmp; i--; } int c = Color.HSBtoRGB((MAX_ITERATIONS / i) % 1, 1, i > 0 ? 1 : 0); image.setRGB(x, y, c); }); }); g.drawImage(image, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawJuliaSet(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Julia Set"); f.setResizable(false); f.add(new JuliaSet(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Jump anywhere
Java
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
loop1: while (x != 0) { loop2: for (int i = 0; i < 10; i++) { loop3: do { //some calculations... if (/*some condition*/) { //this continue will skip the rest of the while loop code and start it over at the next iteration continue loop1; } //more calculations skipped by the continue if it is executed if (/*another condition*/) { //this break will end the for loop and jump to its closing brace break loop2; } } while (y < 10); //loop2 calculations skipped if the break is executed } //loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed }
K-d tree
Java
{{wikipedia|K-d tree}} A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead. '''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets: # The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)]. # 1000 3-d points uniformly distributed in a 3-d cube. For the Wikipedia example, find the nearest neighbor to point (9, 2) For the random data, pick a random location and find the nearest neighbor. In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed. Output should show the point searched for, the point found, the distance to the point, and the number of nodes visited. There are variant algorithms for constructing the tree. You can use a simple median strategy or implement something more efficient. Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. You do not have to implement these. The requirement for this task is specifically the nearest single neighbor. Also there are algorithms for inserting, deleting, and balancing k-d trees. These are also not required for the task.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
Kaprekar numbers
Java
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; //parsing "" throws an exception ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); //if the right part is all zeroes, then it will be forever, so break if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
Kernighans large earthquake problem
Java
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
import java.io.BufferedReader; import java.io.FileReader; public class KernighansLargeEarthquakeProblem { public static void main(String[] args) throws Exception { try (BufferedReader reader = new BufferedReader(new FileReader("data.txt")); ) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("\\s+"); double magnitude = Double.parseDouble(split[2]); if ( magnitude > 6 ) { System.out.println(inLine); } } } } }
Knight's tour
Java 7
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
import java.util.*; public class KnightsTour { private final static int base = 12; private final static int[][] moves = {{1,-2},{2,-1},{2,1},{1,2},{-1,2}, {-2,1},{-2,-1},{-1,-2}}; private static int[][] grid; private static int total; public static void main(String[] args) { grid = new int[base][base]; total = (base - 4) * (base - 4); for (int r = 0; r < base; r++) for (int c = 0; c < base; c++) if (r < 2 || r > base - 3 || c < 2 || c > base - 3) grid[r][c] = -1; int row = 2 + (int) (Math.random() * (base - 4)); int col = 2 + (int) (Math.random() * (base - 4)); grid[row][col] = 1; if (solve(row, col, 2)) printResult(); else System.out.println("no result"); } private static boolean solve(int r, int c, int count) { if (count > total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[2] - b[2]; } }); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (!orphanDetected(count, r, c) && solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x); nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static boolean orphanDetected(int cnt, int r, int c) { if (cnt < total - 1) { List<int[]> nbrs = neighbors(r, c); for (int[] nb : nbrs) if (countNeighbors(nb[0], nb[1]) == 0) return true; } return false; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) continue; System.out.printf("%2d ", i); } System.out.println(); } } }
Knight's tour
Java 8
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
package com.knight.tour; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class KT { private int baseSize = 12; // virtual board size including unreachable out-of-board nodes. i.e. base 12 = 8X8 board int actualBoardSize = baseSize - 4; private static final int[][] moves = { { 1, -2 }, { 2, -1 }, { 2, 1 }, { 1, 2 }, { -1, 2 }, { -2, 1 }, { -2, -1 }, { -1, -2 } }; private static int[][] grid; private static int totalNodes; private ArrayList<int[]> travelledNodes = new ArrayList<>(); public KT(int baseNumber) { this.baseSize = baseNumber; this.actualBoardSize = baseSize - 4; } public static void main(String[] args) { new KT(12).tour(); // find a solution for 8X8 board // new KT(24).tour(); // then for 20X20 board // new KT(104).tour(); // then for 100X100 board } private void tour() { totalNodes = actualBoardSize * actualBoardSize; travelledNodes.clear(); grid = new int[baseSize][baseSize]; for (int r = 0; r < baseSize; r++) for (int c = 0; c < baseSize; c++) { if (r < 2 || r > baseSize - 3 || c < 2 || c > baseSize - 3) { grid[r][c] = -1; // mark as out-of-board nodes } else { grid[r][c] = 0; // nodes within chess board. } } // start from a random node int startRow = 2 + (int) (Math.random() * actualBoardSize); int startCol = 2 + (int) (Math.random() * actualBoardSize); int[] start = { startRow, startCol, 0, 1 }; grid[startRow][startCol] = 1; // mark the first traveled node travelledNodes.add(start); // add to partial solution chain, which will only have one node. // Start traveling forward autoKnightTour(start, 2); } // non-backtracking touring methods. Re-chain the partial solution when all neighbors are traveled to avoid back-tracking. private void autoKnightTour(int[] start, int nextCount) { List<int[]> nbrs = neighbors(start[0], start[1]); if (nbrs.size() > 0) { Collections.sort(nbrs, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[2] - b[2]; } }); // sort the list int[] next = nbrs.get(0); // the one with the less available neighbors - Warnsdorff's algorithm next[3] = nextCount; travelledNodes.add(next); grid[next[0]][next[1]] = nextCount; if (travelledNodes.size() == totalNodes) { System.out.println("Found a path for " + actualBoardSize + " X " + actualBoardSize + " chess board."); StringBuilder sb = new StringBuilder(); sb.append(System.lineSeparator()); for (int idx = 0; idx < travelledNodes.size(); idx++) { int[] item = travelledNodes.get(idx); sb.append("->(" + (item[0] - 2) + "," + (item[1] - 2) + ")"); if ((idx + 1) % 15 == 0) { sb.append(System.lineSeparator()); } } System.out.println(sb.toString() + "\n"); } else { // continuing the travel autoKnightTour(next, ++nextCount); } } else { // no travelable neighbors next - need to rechain the partial chain int[] last = travelledNodes.get(travelledNodes.size() - 1); travelledNodes = reChain(travelledNodes); if (travelledNodes.get(travelledNodes.size() - 1).equals(last)) { travelledNodes = reChain(travelledNodes); if (travelledNodes.get(travelledNodes.size() - 1).equals(last)) { System.out.println("Re-chained twice but no travllable node found. Quiting..."); } else { int[] end = travelledNodes.get(travelledNodes.size() - 1); autoKnightTour(end, nextCount); } } else { int[] end = travelledNodes.get(travelledNodes.size() - 1); autoKnightTour(end, nextCount); } } } private ArrayList<int[]> reChain(ArrayList<int[]> alreadyTraveled) { int[] last = alreadyTraveled.get(alreadyTraveled.size() - 1); List<int[]> candidates = neighborsInChain(last[0], last[1]); int cutIndex; int[] randomPicked = candidates.get((int) Math.random() * candidates.size()); cutIndex = grid[randomPicked[0]][randomPicked[1]] - 1; ArrayList<int[]> result = new ArrayList<int[]>(); //create empty list to copy already traveled nodes to for (int k = 0; k <= cutIndex; k++) { result.add(result.size(), alreadyTraveled.get(k)); } for (int j = alreadyTraveled.size() - 1; j > cutIndex; j--) { alreadyTraveled.get(j)[3] = result.size(); result.add(result.size(), alreadyTraveled.get(j)); } return result; // re-chained partial solution with different end node } private List<int[]> neighborsInChain(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] > 0 && grid[r + y][c + x] != grid[r][c] - 1) { int num = countNeighbors(r + y, c + x); nbrs.add(new int[] { r + y, c + x, num, 0 }); } } return nbrs; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x); nbrs.add(new int[] { r + y, c + x, num, 0 }); // not-traveled neighbors and number of their neighbors } } return nbrs; } private List<int[]> extendableNeighbors(List<int[]> neighbors) { List<int[]> nbrs = new ArrayList<>(); for (int[] node : neighbors) { if (node[2] > 0) nbrs.add(node); } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) { if (grid[r + m[1]][c + m[0]] == 0) { num++; } } return num; } }
Knuth's algorithm S
Java
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). ;The algorithm: :* Select the first n items as the sample as they become available; :* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. :* Repeat 2nd step for any subsequent items. ;The Task: :* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. :* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. :* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: :::# Use the s_of_n_creator with n == 3 to generate an s_of_n. :::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. Note: A class taking n and generating a callable instance/function might also be used. ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 ;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]]
import java.util.*; interface Function<S, T> { public T call(S x); } public class AlgorithmS { private static final Random rand = new Random(); public static <T> Function<T, List<T>> s_of_n_creator(final int n) { return new Function<T, List<T>>() { private List<T> sample = new ArrayList<T>(n); private int i = 0; public List<T> call(T item) { if (++i <= n) { sample.add(item); } else if (rand.nextInt(i) < n) { sample.set(rand.nextInt(n), item); } return sample; } }; } public static void main(String[] args) { int[] bin = new int[10]; for (int trial = 0; trial < 100000; trial++) { Function<Integer, List<Integer>> s_of_n = s_of_n_creator(3); for (int i = 0; i < 9; i++) s_of_n.call(i); for (int s : s_of_n.call(9)) bin[s]++; } System.out.println(Arrays.toString(bin)); } }
Koch curve
Java
Draw a Koch curve. See details: Koch curve
import java.awt.Point; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.ArrayList; import java.util.List; public final class KochCurve { public static void main(String[] aArgs) throws IOException { List<Point> points = initialEquilateralTriangle(); for ( int i = 1; i < 5; i++ ) { points = nextIteration(points); } String text = kochCurveText(points, IMAGE_SIZE); Files.write(Paths.get("C:/Users/psnow/Desktop/koch.svg"), text.getBytes()); } private static List<Point> initialEquilateralTriangle() { final int margin = 50; final int boxSize = IMAGE_SIZE - margin; final int sideLength = Math.round(boxSize * SIN_60_DEGREES); final int x = ( boxSize + margin - sideLength ) / 2; final int y = Math.round(( boxSize + margin ) / 2 - sideLength * SIN_60_DEGREES / 3); List<Point> points = Arrays.asList( new Point(x, y), new Point(x + sideLength / 2, Math.round(y + sideLength * SIN_60_DEGREES)), new Point(x + sideLength, y), new Point(x, y) ); return points; } private static List<Point> nextIteration(List<Point> aPoints) { List<Point> result = new ArrayList<Point>(); for ( int i = 0; i < aPoints.size() - 1; i++ ) { final int x0 = aPoints.get(i).x; final int y0 = aPoints.get(i).y; final int x1 = aPoints.get(i + 1).x; final int y1 = aPoints.get(i + 1).y; final int dy = y1 - y0; final int dx = x1 - x0; result.add(aPoints.get(i)); result.add( new Point(x0 + dx / 3, y0 + dy / 3) ); result.add( new Point(Math.round(x0 + dx / 2 - dy * SIN_60_DEGREES / 3), Math.round(y0 + dy / 2 + dx * SIN_60_DEGREES / 3)) ); result.add( new Point(x0 + 2 * dx / 3, y0 + 2 * dy / 3) ) ; } result.add(aPoints.get(aPoints.size() - 1)); return result; } private static String kochCurveText(List<Point> aPoints, int aSize) { StringBuilder text = new StringBuilder(); text.append("<svg xmlns='http://www.w3.org/2000/svg'"); text.append(" width='" + aSize + "' height='" + aSize + "'>\n"); text.append("<rect style='width:100%;height:100%;fill:cyan'/>\n"); text.append("<polygon points='"); for ( int i = 0; i < aPoints.size(); i++ ) { text.append(aPoints.get(i).x + ", " + aPoints.get(i).y + " "); } text.append("' style='fill:pink;stroke:black;stroke-width:2'/>\n</svg>\n"); return text.toString(); } private static final int IMAGE_SIZE = 700; private static final float SIN_60_DEGREES = (float) Math.sin(Math.PI / 3.0); }
Kolakoski sequence
Java from Kotlin
The natural numbers, (excluding zero); with the property that: : ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''. ;Example: This is ''not'' a Kolakoski sequence: 1,1,2,2,2,1,2,2,1,2,... Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this: : Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ... The above gives the RLE of: 2, 3, 1, 2, 1, ... The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''. ;Creating a Kolakoski sequence: Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,.... # We start the sequence s with the first item from the cycle c: 1 # An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s. We started s with 1 and therefore s[k] states that it should appear only the 1 time. Increment k Get the next item from c and append it to the end of sequence s. s will then become: 1, 2 k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2 Increment k Append the next item from the cycle to the list: 1, 2,2, 1 k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1 increment k ... '''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case. ;Task: # Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle. # Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence. # Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE). # Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 20 members of the sequence generated from (2, 1) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1) # Check the sequence againt its RLE. (There are rules on generating Kolakoski sequences from this method that are broken by the last example)
import java.util.Arrays; public class Kolakoski { private static class Crutch { final int len; int[] s; int i; Crutch(int len) { this.len = len; s = new int[len]; i = 0; } void repeat(int count) { for (int j = 0; j < count; j++) { if (++i == len) return; s[i] = s[i - 1]; } } } private static int nextInCycle(final int[] self, int index) { return self[index % self.length]; } private static int[] kolakoski(final int[] self, int len) { Crutch c = new Crutch(len); int k = 0; while (c.i < len) { c.s[c.i] = nextInCycle(self, k); if (c.s[k] > 1) { c.repeat(c.s[k] - 1); } if (++c.i == len) return c.s; k++; } return c.s; } private static boolean possibleKolakoski(final int[] self) { int[] rle = new int[self.length]; int prev = self[0]; int count = 1; int pos = 0; for (int i = 1; i < self.length; i++) { if (self[i] == prev) { count++; } else { rle[pos++] = count; count = 1; prev = self[i]; } } // no point adding final 'count' to rle as we're not going to compare it anyway for (int i = 0; i < pos; i++) { if (rle[i] != self[i]) { return false; } } return true; } public static void main(String[] args) { int[][] ias = new int[][]{ new int[]{1, 2}, new int[]{2, 1}, new int[]{1, 3, 1, 2}, new int[]{1, 3, 2, 1} }; int[] lens = new int[]{20, 20, 30, 30}; for (int i=0; i<ias.length; i++) { int len = lens[i]; int[] kol = kolakoski(ias[i], len); System.out.printf("First %d members of the sequence generated by %s: \n", len, Arrays.toString(ias[i])); System.out.printf("%s\n", Arrays.toString(kol)); System.out.printf("Possible Kolakoski sequence? %s\n\n", possibleKolakoski(kol)); } } }
Kosaraju
Java from Kotlin
{{wikipedia|Graph}} Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph. For this task consider the directed graph with these connections: 0 -> 1 1 -> 2 2 -> 0 3 -> 1, 3 -> 2, 3 -> 4 4 -> 3, 4 -> 5 5 -> 2, 5 -> 6 6 -> 5 7 -> 4, 7 -> 6, 7 -> 7 And report the kosaraju strongly connected component for each node. ;References: * The article on Wikipedia.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } private static List<Integer> kosaraju(List<List<Integer>> g) { // 1. For each vertex u of the graph, mark u as unvisited. Let l be empty. int size = g.size(); boolean[] vis = new boolean[size]; int[] l = new int[size]; AtomicInteger x = new AtomicInteger(size); List<List<Integer>> t = new ArrayList<>(); for (int i = 0; i < size; ++i) { t.add(new ArrayList<>()); } Recursive<IntConsumer> visit = new Recursive<>(); visit.func = (int u) -> { if (!vis[u]) { vis[u] = true; for (Integer v : g.get(u)) { visit.func.accept(v); t.get(v).add(u); } int xval = x.decrementAndGet(); l[xval] = u; } }; // 2. For each vertex u of the graph do visit(u) for (int i = 0; i < size; ++i) { visit.func.accept(i); } int[] c = new int[size]; Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>(); assign.func = (Integer u, Integer root) -> { if (vis[u]) { // repurpose vis to mean 'unassigned' vis[u] = false; c[u] = root; for (Integer v : t.get(u)) { assign.func.accept(v, root); } } }; // 3: For each element u of l in order, do assign(u, u) for (int u : l) { assign.func.accept(u, u); } return Arrays.stream(c).boxed().collect(Collectors.toList()); } public static void main(String[] args) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < 8; ++i) { g.add(new ArrayList<>()); } g.get(0).add(1); g.get(1).add(2); g.get(2).add(0); g.get(3).add(1); g.get(3).add(2); g.get(3).add(4); g.get(4).add(3); g.get(4).add(5); g.get(5).add(2); g.get(5).add(6); g.get(6).add(5); g.get(7).add(4); g.get(7).add(6); g.get(7).add(7); List<Integer> output = kosaraju(g); System.out.println(output); } }
Lah numbers
Java
Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations: L(n, 0), L(0, k) = 0 # for n, k > 0 L(n, n) = 1 L(n, 1) = n! L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers ''or'' L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers ;Task: :* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n). :* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Lah number''' :* '''OEIS:A105278 - Unsigned Lah numbers''' :* '''OEIS:A008297 - Signed Lah numbers''' ;Related Tasks: :* '''Stirling numbers of the first kind''' :* '''Stirling numbers of the second kind''' :* '''Bell numbers'''
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LahNumbers { public static void main(String[] args) { System.out.println("Show the unsigned Lah numbers up to n = 12:"); for ( int n = 0 ; n <= 12 ; n++ ) { System.out.printf("%5s", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%12s", lahNumber(n, k)); } System.out.printf("%n"); } System.out.println("Show the maximum value of L(100, k):"); int n = 100; BigInteger max = BigInteger.ZERO; for ( int k = 0 ; k <= n ; k++ ) { max = max.max(lahNumber(n, k)); } System.out.printf("%s", max); } private static Map<String,BigInteger> CACHE = new HashMap<>(); private static BigInteger lahNumber(int n, int k) { String key = n + "," + k; if ( CACHE.containsKey(key) ) { return CACHE.get(key); } // L(n,0) = 0; BigInteger result; if ( n == 0 && k == 0 ) { result = BigInteger.ONE; } else if ( k == 0 ) { result = BigInteger.ZERO; } else if ( k > n ) { result = BigInteger.ZERO; } else if ( n == 1 && k == 1 ) { result = BigInteger.ONE; } else { result = BigInteger.valueOf(n-1+k).multiply(lahNumber(n-1,k)).add(lahNumber(n-1,k-1)); } CACHE.put(key, result); return result; } }
Largest int from concatenated ints
Java 1.5+
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
import java.util.*; public class IntConcat { private static Comparator<Integer> sorter = new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2){ String o1s = o1.toString(); String o2s = o2.toString(); if(o1s.length() == o2s.length()){ return o2s.compareTo(o1s); } int mlen = Math.max(o1s.length(), o2s.length()); while(o1s.length() < mlen * 2) o1s += o1s; while(o2s.length() < mlen * 2) o2s += o2s; return o2s.compareTo(o1s); } }; public static String join(List<?> things){ String output = ""; for(Object obj:things){ output += obj; } return output; } public static void main(String[] args){ List<Integer> ints1 = new ArrayList<Integer>(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4)); Collections.sort(ints1, sorter); System.out.println(join(ints1)); List<Integer> ints2 = new ArrayList<Integer>(Arrays.asList(54, 546, 548, 60)); Collections.sort(ints2, sorter); System.out.println(join(ints2)); } }
Largest int from concatenated ints
Java 1.8+
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
import java.util.Comparator; import java.util.stream.Collectors; import java.util.stream.Stream; public interface IntConcat { public static Comparator<Integer> SORTER = (o1, o2) -> { String o1s = o1.toString(); String o2s = o2.toString(); if (o1s.length() == o2s.length()) { return o2s.compareTo(o1s); } int mlen = Math.max(o1s.length(), o2s.length()); while (o1s.length() < mlen * 2) { o1s += o1s; } while (o2s.length() < mlen * 2) { o2s += o2s; } return o2s.compareTo(o1s); }; public static void main(String[] args) { Stream<Integer> ints1 = Stream.of( 1, 34, 3, 98, 9, 76, 45, 4 ); System.out.println(ints1 .parallel() .sorted(SORTER) .map(String::valueOf) .collect(Collectors.joining()) ); Stream<Integer> ints2 = Stream.of( 54, 546, 548, 60 ); System.out.println(ints2 .parallel() .sorted(SORTER) .map(String::valueOf) .collect(Collectors.joining()) ); } }
Last Friday of each month
Java 1.5+
Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 ;Related tasks * [[Five weekends]] * [[Day of the week]] * [[Find the last Sunday of each month]]
import java.text.*; import java.util.*; public class LastFridays { public static void main(String[] args) throws Exception { int year = Integer.parseInt(args[0]); GregorianCalendar c = new GregorianCalendar(year, 0, 1); for (String mon : new DateFormatSymbols(Locale.US).getShortMonths()) { if (!mon.isEmpty()) { int totalDaysOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH); c.set(Calendar.DAY_OF_MONTH, totalDaysOfMonth); int daysToRollBack = (c.get(Calendar.DAY_OF_WEEK) + 1) % 7; int day = totalDaysOfMonth - daysToRollBack; c.set(Calendar.DAY_OF_MONTH, day); System.out.printf("%d %s %d\n", year, mon, day); c.set(year, c.get(Calendar.MONTH) + 1, 1); } } } }
Last letter-first letter
Java
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
// derived from C final class LastLetterFirstLetter { static int maxPathLength = 0; static int maxPathLengthCount = 0; static final StringBuffer maxPathExample = new StringBuffer(500); static final String[] names = {"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask"}; static void recursive(String[] part, int offset) { if (offset > maxPathLength) { maxPathLength = offset; maxPathLengthCount = 1; } else if (offset == maxPathLength) { maxPathLengthCount++; maxPathExample.setLength(0); for (int i = 0; i < offset; i++) { maxPathExample.append((i % 5 == 0 ? "\n " : " ")); maxPathExample.append(part[i]); } } final char lastChar = part[offset - 1].charAt(part[offset - 1].length()-1); for (int i = offset; i < part.length; i++) { if (part[i].charAt(0) == lastChar) { String tmp = names[offset]; names[offset] = names[i]; names[i] = tmp; recursive(names, offset+1); names[i] = names[offset]; names[offset] = tmp; } } } public static void main(String[] args) { for (int i = 0; i < names.length; i++) { String tmp = names[0]; names[0] = names[i]; names[i] = tmp; recursive(names, 1); names[i] = names[0]; names[0] = tmp; } System.out.println("maximum path length : " + maxPathLength); System.out.println("paths of that length : " + maxPathLengthCount); System.out.println("example path of that length:" + maxPathExample); } }
Latin Squares in reduced form
Java
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: * displaying the four reduced Latin Squares of order 4. * for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ) { System.out.printf("%s%n", square); } System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n"); for ( int n = 1 ; n <= 6 ; n++ ) { List<LatinSquare> list = getReducedLatinSquares(n); System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1)); } } private static long fact(int n) { if ( n == 0 ) { return 1; } int prod = 1; for ( int i = 1 ; i <= n ; i++ ) { prod *= i; } return prod; } private static List<LatinSquare> getReducedLatinSquares(int n) { List<LatinSquare> squares = new ArrayList<>(); squares.add(new LatinSquare(n)); PermutationGenerator permGen = new PermutationGenerator(n); for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) { List<LatinSquare> squaresNext = new ArrayList<>(); for ( LatinSquare square : squares ) { while ( permGen.hasMore() ) { int[] perm = permGen.getNext(); // If not the correct row - next permutation. if ( (perm[0]+1) != (fillRow+1) ) { continue; } // Check permutation against current square. boolean permOk = true; done: for ( int row = 0 ; row < fillRow ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { if ( square.get(row, col) == (perm[col]+1) ) { permOk = false; break done; } } } if ( permOk ) { LatinSquare newSquare = new LatinSquare(square); for ( int col = 0 ; col < n ; col++ ) { newSquare.set(fillRow, col, perm[col]+1); } squaresNext.add(newSquare); } } permGen.reset(); } squares = squaresNext; } return squares; } @SuppressWarnings("unused") private static int[] display(int[] in) { int [] out = new int[in.length]; for ( int i = 0 ; i < in.length ; i++ ) { out[i] = in[i] + 1; } return out; } private static class LatinSquare { int[][] square; int size; public LatinSquare(int n) { square = new int[n][n]; size = n; for ( int col = 0 ; col < n ; col++ ) { set(0, col, col + 1); } } public LatinSquare(LatinSquare ls) { int n = ls.size; square = new int[n][n]; size = n; for ( int row = 0 ; row < n ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { set(row, col, ls.get(row, col)); } } } public void set(int row, int col, int value) { square[row][col] = value; } public int get(int row, int col) { return square[row][col]; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for ( int row = 0 ; row < size ; row++ ) { sb.append(Arrays.toString(square[row])); sb.append("\n"); } return sb.toString(); } } private static class PermutationGenerator { private int[] a; private BigInteger numLeft; private BigInteger total; public PermutationGenerator (int n) { if (n < 1) { throw new IllegalArgumentException ("Min 1"); } a = new int[n]; total = getFactorial(n); reset(); } private void reset () { for ( int i = 0 ; i < a.length ; i++ ) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for ( int i = n ; i > 1 ; i-- ) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } /*-------------------------------------------------------- * Generate next permutation (algorithm from Rosen p. 284) *-------------------------------------------------------- */ public int[] getNext() { if ( numLeft.equals(total) ) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } // Find largest index j with a[j] < a[j+1] int j = a.length - 2; while ( a[j] > a[j+1] ) { j--; } // Find index k such that a[k] is smallest integer greater than a[j] to the right of a[j] int k = a.length - 1; while ( a[j] > a[k] ) { k--; } // Interchange a[j] and a[k] int temp = a[k]; a[k] = a[j]; a[j] = temp; // Put tail end of permutation after jth position in increasing order int r = a.length - 1; int s = j + 1; while (r > s) { int temp2 = a[s]; a[s] = a[r]; a[r] = temp2; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } }
Law of cosines - triples
Java
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
public class LawOfCosines { public static void main(String[] args) { generateTriples(13); generateTriples60(10000); } private static void generateTriples(int max) { for ( int coeff : new int[] {0, -1, 1} ) { int count = 0; System.out.printf("Max side length %d, formula: a*a + b*b %s= c*c%n", max, coeff == 0 ? "" : (coeff<0 ? "-" : "+") + " a*b "); for ( int a = 1 ; a <= max ; a++ ) { for ( int b = 1 ; b <= a ; b++ ) { int val = a*a + b*b + coeff*a*b; int c = (int) (Math.sqrt(val) + .5d); if ( c > max ) { break; } if ( c*c == val ) { System.out.printf(" (%d, %d, %d)%n", a, b ,c); count++; } } } System.out.printf("%d triangles%n", count); } } private static void generateTriples60(int max) { int count = 0; System.out.printf("%nExtra Credit.%nMax side length %d, sides different length, formula: a*a + b*b - a*b = c*c%n", max); for ( int a = 1 ; a <= max ; a++ ) { for ( int b = 1 ; b < a ; b++ ) { int val = a*a + b*b - a*b; int c = (int) (Math.sqrt(val) + .5d); if ( c*c == val ) { count++; } } } System.out.printf("%d triangles%n", count); } }
Least common multiple
Java
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); //prompts user for values to find the LCM for, then saves them to m and n System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); /* this section increases the value of mm until it is greater / than or equal to nn, then does it again when the lesser / becomes the greater--if they aren't equal. If either value is 1, / no need to calculate*/ if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Left factorials
Java
'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; the same notation can be confusingly seen being used for the two different definitions. Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: :::::::* !''n''` :::::::* !''n'' :::::::* ''n''! (It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''': ::::: !n = \sum_{k=0}^{n-1} k! :::: where ::::: !0 = 0 ;Task Display the left factorials for: * zero through ten (inclusive) * 20 through 110 (inclusive) by tens Display the length (in decimal digits) of the left factorials for: * 1,000 through 10,000 (inclusive), by thousands. ;Also see: * The OEIS entry: A003422 left factorials * The MathWorld entry: left factorial * The MathWorld entry: factorial sums * The MathWorld entry: subfactorial ;Related task: * permutations/derangements (subfactorials)
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n){ BigInteger ans = BigInteger.ZERO; for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){ ans = ans.add(factorial(k)); } return ans; } public static void main(String[] args){ for(int i = 0; i <= 10; i++){ System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); } for(int i = 20; i <= 110; i += 10){ System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); } for(int i = 1000; i <= 10000; i += 1000){ System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits"); } } }
Levenshtein distance
Java
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
public class Levenshtein { public static int distance(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); // i == 0 int [] costs = new int [b.length() + 1]; for (int j = 0; j < costs.length; j++) costs[j] = j; for (int i = 1; i <= a.length(); i++) { // j == 0; nw = lev(i - 1, j) costs[0] = i; int nw = i - 1; for (int j = 1; j <= b.length(); j++) { int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1); nw = costs[j]; costs[j] = cj; } } return costs[b.length()]; } public static void main(String [] args) { String [] data = { "kitten", "sitting", "saturday", "sunday", "rosettacode", "raisethysword" }; for (int i = 0; i < data.length; i += 2) System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1])); } }
Levenshtein distance
Java from C
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
public class Levenshtein{ public static int levenshtein(String s, String t){ /* if either string is empty, difference is inserting all chars * from the other */ if(s.length() == 0) return t.length(); if(t.length() == 0) return s.length(); /* if first letters are the same, the difference is whatever is * required to edit the rest of the strings */ if(s.charAt(0) == t.charAt(0)) return levenshtein(s.substring(1), t.substring(1)); /* else try: * changing first letter of s to that of t, * remove first letter of s, or * remove first letter of t */ int a = levenshtein(s.substring(1), t.substring(1)); int b = levenshtein(s, t.substring(1)); int c = levenshtein(s.substring(1), t); if(a > b) a = b; if(a > c) a = c; //any of which is 1 edit plus editing the rest of the strings return a + 1; } public static void main(String[] args) { String s1 = "kitten"; String s2 = "sitting"; System.out.println("distance between '" + s1 + "' and '" + s2 + "': " + levenshtein(s1, s2)); s1 = "rosettacode"; s2 = "raisethysword"; System.out.println("distance between '" + s1 + "' and '" + s2 + "': " + levenshtein(s1, s2)); StringBuilder sb1 = new StringBuilder(s1); StringBuilder sb2 = new StringBuilder(s2); System.out.println("distance between '" + sb1.reverse() + "' and '" + sb2.reverse() + "': " + levenshtein(sb1.reverse().toString(), sb2.reverse().toString())); } }
Levenshtein distance
Java from Python
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
import static java.lang.Math.abs; import static java.lang.Math.max; public class Levenshtein { public static int ld(String a, String b) { return distance(a, b, -1); } public static boolean ld(String a, String b, int max) { return distance(a, b, max) <= max; } private static int distance(String a, String b, int max) { if (a == b) return 0; int la = a.length(); int lb = b.length(); if (max >= 0 && abs(la - lb) > max) return max+1; if (la == 0) return lb; if (lb == 0) return la; if (la < lb) { int tl = la; la = lb; lb = tl; String ts = a; a = b; b = ts; } int[] cost = new int[lb+1]; for (int i=0; i<=lb; i+=1) { cost[i] = i; } for (int i=1; i<=la; i+=1) { cost[0] = i; int prv = i-1; int min = prv; for (int j=1; j<=lb; j+=1) { int act = prv + (a.charAt(i-1) == b.charAt(j-1) ? 0 : 1); cost[j] = min(1+(prv=cost[j]), 1+cost[j-1], act); if (prv < min) min = prv; } if (max >= 0 && min > max) return max+1; } if (max >= 0 && cost[lb] > max) return max+1; return cost[lb]; } private static int min(int ... a) { int min = Integer.MAX_VALUE; for (int i: a) if (i<min) min = i; return min; } public static void main(String[] args) { System.out.println( ld("kitten","kitten") + " " + // 0 ld("kitten","sitten") + " " + // 1 ld("kitten","sittes") + " " + // 2 ld("kitten","sityteng") + " " + // 3 ld("kitten","sittYing") + " " + // 4 ld("rosettacode","raisethysword") + " " + // 8 ld("kitten","kittenaaaaaaaaaaaaaaaaa") + " " + // 17 ld("kittenaaaaaaaaaaaaaaaaa","kitten") // 17 ); System.out.println( ld("kitten","kitten", 3) + " " + // true ld("kitten","sitten", 3) + " " + // true ld("kitten","sittes", 3) + " " + // true ld("kitten","sityteng", 3) + " " + // true ld("kitten","sittYing", 3) + " " + // false ld("rosettacode","raisethysword", 3) + " " + // false ld("kitten","kittenaaaaaaaaaaaaaaaaa", 3) + " " + // false ld("kittenaaaaaaaaaaaaaaaaa","kitten", 3) // false ); } }
Levenshtein distance/Alignment
Java
The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is: P-LACE PALACE ;Task: Write a function that shows the alignment of two strings for the corresponding levenshtein distance. As an example, use the words "rosettacode" and "raisethysword". You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); // i == 0 int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = 1; i <= a.length(); i++) { costs[i][0] = i; for (int j = 1; j <= b.length(); j++) { costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1); } } // walk back through matrix to figure out path StringBuilder aPathRev = new StringBuilder(); StringBuilder bPathRev = new StringBuilder(); for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) { if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) { aPathRev.append(a.charAt(--i)); bPathRev.append(b.charAt(--j)); } else if (costs[i][j] == 1 + costs[i-1][j]) { aPathRev.append(a.charAt(--i)); bPathRev.append('-'); } else if (costs[i][j] == 1 + costs[i][j-1]) { aPathRev.append('-'); bPathRev.append(b.charAt(--j)); } } return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()}; } public static void main(String[] args) { String[] result = alignment("rosettacode", "raisethysword"); System.out.println(result[0]); System.out.println(result[1]); } }
List rooted trees
Java from Kotlin
You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical. If we use a matching pair of parentheses to represent a bag, the ways are: For 1 bag, there's one way: () <- a bag for 2 bags, there's one way: (()) <- one bag in another for 3 bags, there are two: ((())) <- 3 bags nested Russian doll style (()()) <- 2 bags side by side, inside the third for 4 bags, four: (()()()) ((())()) ((()())) (((()))) Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration. It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81. ;Task: Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive. This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size. As an example output, run 5 bags. There should be 9 ways.
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
Long year
Java
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
import java.time.LocalDate; import java.time.temporal.WeekFields; public class LongYear { public static void main(String[] args) { System.out.printf("Long years this century:%n"); for (int year = 2000 ; year < 2100 ; year++ ) { if ( longYear(year) ) { System.out.print(year + " "); } } } private static boolean longYear(int year) { return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53; } }
Longest common subsequence
Java
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
public static String lcs(String a, String b) { int[][] lengths = new int[a.length()+1][b.length()+1]; // row 0 and column 0 are initialized to 0 already for (int i = 0; i < a.length(); i++) for (int j = 0; j < b.length(); j++) if (a.charAt(i) == b.charAt(j)) lengths[i+1][j+1] = lengths[i][j] + 1; else lengths[i+1][j+1] = Math.max(lengths[i+1][j], lengths[i][j+1]); // read the substring out from the matrix StringBuffer sb = new StringBuffer(); for (int x = a.length(), y = b.length(); x != 0 && y != 0; ) { if (lengths[x][y] == lengths[x-1][y]) x--; else if (lengths[x][y] == lengths[x][y-1]) y--; else { assert a.charAt(x-1) == b.charAt(y-1); sb.append(a.charAt(x-1)); x--; y--; } } return sb.reverse().toString(); }
Longest common substring
Java
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
public class LongestCommonSubstring { public static void main(String[] args) { System.out.println(lcs("testing123testing", "thisisatest")); System.out.println(lcs("test", "thisisatest")); System.out.println(lcs("testing", "sting")); System.out.println(lcs("testing", "thisisasting")); } static String lcs(String a, String b) { if (a.length() > b.length()) return lcs(b, a); String res = ""; for (int ai = 0; ai < a.length(); ai++) { for (int len = a.length() - ai; len > 0; len--) { for (int bi = 0; bi <= b.length() - len; bi++) { if (a.regionMatches(ai, b, bi, len) && len > res.length()) { res = a.substring(ai, ai + len); } } } } return res; } }
Longest increasing subsequence
Java
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); // sort into piles for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, node); if (i < 0) i = ~i; if (i != 0) node.pointer = pileTops.get(i-1); if (i != pileTops.size()) pileTops.set(i, node); else pileTops.add(node); } // extract LIS from nodes List<E> result = new ArrayList<E>(); for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); node != null; node = node.pointer) result.add(node.value); Collections.reverse(result); return result; } private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> { public E value; public Node<E> pointer; public int compareTo(Node<E> y) { return value.compareTo(y.value); } } public static void main(String[] args) { List<Integer> d = Arrays.asList(3,2,6,4,5,1); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); } }
Lucky and even lucky numbers
Java
Note that in the following explanation list indices are assumed to start at ''one''. ;Definition of lucky numbers ''Lucky numbers'' are positive integers that are formed by: # Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ... # Return the first number from the list (which is '''1'''). # (Loop begins here) #* Note then return the second number from the list (which is '''3'''). #* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''7'''). #* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ... #* Note then return the 4th number from the list (which is '''9'''). #* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ... #* Take the 5th, i.e. '''13'''. Remove every 13th. #* Take the 6th, i.e. '''15'''. Remove every 15th. #* Take the 7th, i.e. '''21'''. Remove every 21th. #* Take the 8th, i.e. '''25'''. Remove every 25th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above ''except for the very first step'': # Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ... # Return the first number from the list (which is '''2'''). # (Loop begins here) #* Note then return the second number from the list (which is '''4'''). #* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''6'''). #* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ... #* Take the 4th, i.e. '''10'''. Remove every 10th. #* Take the 5th, i.e. '''12'''. Remove every 12th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Task requirements * Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' * Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: ** missing arguments ** too many arguments ** number (or numbers) aren't legal ** misspelled argument ('''lucky''' or '''evenLucky''') * The command line handling should: ** support mixed case handling of the (non-numeric) arguments ** support printing a particular number ** support printing a range of numbers by their index ** support printing a range of numbers by their values * The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) +-------------------+----------------------------------------------------+ | j | Jth lucky number | | j , lucky | Jth lucky number | | j , evenLucky | Jth even lucky number | | | | | j k | Jth through Kth (inclusive) lucky numbers | | j k lucky | Jth through Kth (inclusive) lucky numbers | | j k evenLucky | Jth through Kth (inclusive) even lucky numbers | | | | | j -k | all lucky numbers in the range j --> |k| | | j -k lucky | all lucky numbers in the range j --> |k| | | j -k evenLucky | all even lucky numbers in the range j --> |k| | +-------------------+----------------------------------------------------+ where |k| is the absolute value of k Demonstrate the program by: * showing the first twenty ''lucky'' numbers * showing the first twenty ''even lucky'' numbers * showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive) * showing all ''even lucky'' numbers in the same range as above * showing the 10,000th ''lucky'' number (extra credit) * showing the 10,000th ''even lucky'' number (extra credit) ;See also: * This task is related to the [[Sieve of Eratosthenes]] task. * OEIS Wiki Lucky numbers. * Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. * Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. * Entry lucky numbers on The Eric Weisstein's World of Mathematics.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LuckyNumbers { private static int MAX = 200000; private static List<Integer> luckyEven = luckyNumbers(MAX, true); private static List<Integer> luckyOdd = luckyNumbers(MAX, false); public static void main(String[] args) { // Case 1 and 2 if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) { int n = Integer.parseInt(args[0]); System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1)); } // Case 3 else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) { int n = Integer.parseInt(args[0]); System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1)); } // Case 4 through 9 else if ( args.length == 2 || args.length == 3 ) { int j = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); // Case 4 and 5 if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) { System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k)); } // Case 6 else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) { System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k)); } // Case 7 and 8 else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) { int n = Collections.binarySearch(luckyOdd, j); int m = Collections.binarySearch(luckyOdd, -k); System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } // Case 9 else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) { int n = Collections.binarySearch(luckyEven, j); int m = Collections.binarySearch(luckyEven, -k); System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } } } private static List<Integer> luckyNumbers(int max, boolean even) { List<Integer> luckyList = new ArrayList<>(); for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) { luckyList.add(i); } int start = 1; boolean removed = true; while ( removed ) { removed = false; int increment = luckyList.get(start); List<Integer> remove = new ArrayList<>(); for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) { remove.add(0, i); removed = true; } for ( int i : remove ) { luckyList.remove(i); } start++; } return luckyList; } }
Lychrel numbers
Java
::# Take an integer n, greater than zero. ::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n. ::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. ;Example: If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens ''after'' an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called '''Lychrel numbers'''. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. ;Seed and related Lychrel numbers: Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. ;Task: * Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500). * Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found. * Print any seed Lychrel or related number that is itself a palindrome. Show all output here. ;References: * What's special about 196? Numberphile video. * A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed). * Status of the 196 conjecture? Mathoverflow.
Translation of [[Lychrel_numbers#Python|Python]] via [[Lychrel_numbers#D|D]]
Lychrel numbers
Java 8
::# Take an integer n, greater than zero. ::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n. ::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. ;Example: If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens ''after'' an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called '''Lychrel numbers'''. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. ;Seed and related Lychrel numbers: Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. ;Task: * Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500). * Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found. * Print any seed Lychrel or related number that is itself a palindrome. Show all output here. ;References: * What's special about 196? Numberphile video. * A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed). * Status of the 196 conjecture? Mathoverflow.
import java.math.BigInteger; import java.util.*; public class Lychrel { static Map<BigInteger, Tuple> cache = new HashMap<>(); static class Tuple { final Boolean flag; final BigInteger bi; Tuple(boolean f, BigInteger b) { flag = f; bi = b; } } static BigInteger rev(BigInteger bi) { String s = new StringBuilder(bi.toString()).reverse().toString(); return new BigInteger(s); } static Tuple lychrel(BigInteger n) { Tuple res; if ((res = cache.get(n)) != null) return res; BigInteger r = rev(n); res = new Tuple(true, n); List<BigInteger> seen = new ArrayList<>(); for (int i = 0; i < 500; i++) { n = n.add(r); r = rev(n); if (n.equals(r)) { res = new Tuple(false, BigInteger.ZERO); break; } if (cache.containsKey(n)) { res = cache.get(n); break; } seen.add(n); } for (BigInteger bi : seen) cache.put(bi, res); return res; } public static void main(String[] args) { List<BigInteger> seeds = new ArrayList<>(); List<BigInteger> related = new ArrayList<>(); List<BigInteger> palin = new ArrayList<>(); for (int i = 1; i <= 10_000; i++) { BigInteger n = BigInteger.valueOf(i); Tuple t = lychrel(n); if (!t.flag) continue; if (n.equals(t.bi)) seeds.add(t.bi); else related.add(t.bi); if (n.equals(t.bi)) palin.add(t.bi); } System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds); System.out.printf("%d Lychrel related%n", related.size()); System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin); } }
MAC vendor lookup
Java
Every connected device around the world comes with a unique Media Access Control address, or a MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. ;Task: Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. '''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
package com.jamesdonnell.MACVendor; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** MAC Vendor Lookup class. * www.JamesDonnell.com * @author James A. Donnell Jr. */ public class Lookup { /** Base URL for API. The API from www.macvendors.com was chosen. */ private static final String baseURL = "http://api.macvendors.com/"; /** Performs lookup on MAC address(es) supplied in arguments. * @param args MAC address(es) to lookup. */ public static void main(String[] args) { for (String arguments : args) System.out.println(arguments + ": " + get(arguments)); } /** Performs lookup on supplied MAC address. * @param macAddress MAC address to lookup. * @return Manufacturer of MAC address. */ private static String get(String macAddress) { try { StringBuilder result = new StringBuilder(); URL url = new URL(baseURL + macAddress); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } catch (FileNotFoundException e) { // MAC not found return "N/A"; } catch (IOException e) { // Error during lookup, either network or API. return null; } } }
Mad Libs
Java
{{wikipedia}} Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. ;Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: went for a walk in the park. found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
import java.util.*; public class MadLibs { public static void main(String[] args){ Scanner input = new Scanner(System.in); String name, gender, noun; System.out.print("Enter a name: "); name = input.next(); System.out.print("He or she: "); gender = input.next(); System.out.print("Enter a noun: "); noun = input.next(); System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home."); } }
Magic 8-ball
Java
Create Magic 8-Ball. See details at: Magic 8-Ball.
import java.util.Random; import java.util.Scanner; public class MagicEightBall { public static void main(String[] args) { new MagicEightBall().run(); } private static String[] ANSWERS = new String[] {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "}; public void run() { Random random = new Random(); System.out.printf("Hello. The Magic 8 Ball knows all. Type your question.%n%n"); try ( Scanner in = new Scanner(System.in); ) { System.out.printf("? "); while ( (in.nextLine()).length() > 0 ) { System.out.printf("8 Ball Response: %s%n", ANSWERS[random.nextInt(ANSWERS.length)]); System.out.printf("? "); } } System.out.printf("%n8 Ball Done. Bye."); } }
Magic squares of doubly even order
Java
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction. {| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%" |- |'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8''' |- |'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16''' |- |'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41''' |- |'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33''' |- |'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25''' |- |'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17''' |- |'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56''' |- |'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64''' |} ;Task Create a magic square of '''8 x 8'''. ;Related tasks * [[Magic squares of odd order]] * [[Magic squares of singly even order]] ;See also: * Doubly Even Magic Squares (1728.org)
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); // pattern of count-up vs count-down zones int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; // how many multiples of 4 int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
Magic squares of odd order
Java
A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). The numbers are usually (but not always) the first '''N'''2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''. {| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%" |- | '''8''' || '''1''' || '''6''' |- | '''3''' || '''5''' || '''7''' |- | '''4''' || '''9''' || '''2''' |} ;Task For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. Optionally, show the ''magic number''. You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''. ; Related tasks * [[Magic squares of singly even order]] * [[Magic squares of doubly even order]] ; See also: * MathWorld(tm) entry: Magic_square * Odd Magic Squares (1728.org)
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
Magic squares of singly even order
Java
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction. ;Task Create a magic square of 6 x 6. ; Related tasks * [[Magic squares of odd order]] * [[Magic squares of doubly even order]] ; See also * Singly Even Magic Squares (1728.org)
public class MagicSquareSinglyEven { public static void main(String[] args) { int n = 6; for (int[] row : magicSquareSinglyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int n) { if (n < 3 || n % 2 == 0) throw new IllegalArgumentException("base must be odd and > 2"); int value = 0; int gridSize = n * n; int c = n / 2, r = 0; int[][] result = new int[n][n]; while (++value <= gridSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } static int[][] magicSquareSinglyEven(final int n) { if (n < 6 || (n - 2) % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4 plus 2"); int size = n * n; int halfN = n / 2; int subSquareSize = size / 4; int[][] subSquare = magicSquareOdd(halfN); int[] quadrantFactors = {0, 2, 3, 1}; int[][] result = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int quadrant = (r / halfN) * 2 + (c / halfN); result[r][c] = subSquare[r % halfN][c % halfN]; result[r][c] += quadrantFactors[quadrant] * subSquareSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } }
Map range
Java
Given two ranges: :::* [a_1,a_2] and :::* [b_1,b_2]; :::* then a value s in range [a_1,a_2] :::* is linearly mapped to a value t in range [b_1,b_2] where: :::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)} ;Task: Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0]. ;Extra credit: Show additional idiomatic ways of performing the mapping, using tools available to the language.
public class Range { public static void main(String[] args){ for(float s = 0;s <= 10; s++){ System.out.println(s + " in [0, 10] maps to "+ mapRange(0, 10, -1, 0, s)+" in [-1, 0]."); } } public static double mapRange(double a1, double a2, double b1, double b2, double s){ return b1 + ((s - a1)*(b2 - b1))/(a2 - a1); } }
Maximum triangle path sum
Java 8
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. ;Task: Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
McNuggets problem
Java
From Wikipedia: The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. ;Task: Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n'' where ''x'', ''y'' and ''z'' are natural numbers).
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; // Works like Sieve of Eratosthenes int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]; int numFound = 0; int total = 0; boolean advancedState = false; do { if (!found[total]) { found[total] = true; numFound++; } // Advance state advancedState = false; for (int i = 0; i < numSizes; i++) { int curSize = SIZES[i]; if ((total + curSize) > MAX_TOTAL) { // Reset to zero and go to the next box size total -= counts[i] * curSize; counts[i] = 0; } else { // Adding a box of this size still keeps the total at or below the maximum counts[i]++; total += curSize; advancedState = true; break; } } } while ((numFound < maxFound) && advancedState); if (numFound < maxFound) { // Did not find all counts within the search space for (int i = MAX_TOTAL; i >= 0; i--) { if (!found[i]) { System.out.println("Largest non-McNugget number in the search space is " + i); break; } } } else { System.out.println("All numbers in the search space are McNugget numbers"); } return; } }
Meissel–Mertens constant
Java
Calculate Meissel-Mertens constant up to a precision your language can handle. ;Motivation: Analogous to Euler's constant, which is important in determining the sum of reciprocal natural numbers, Meissel-Mertens' constant is important in calculating the sum of reciprocal primes. ;Example: We consider the finite sum of reciprocal natural numbers: ''1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n'' this sum can be well approximated with: ''log(n) + E'' where ''E'' denotes Euler's constant: 0.57721... ''log(n)'' denotes the natural logarithm of ''n''. Now consider the finite sum of reciprocal primes: ''1/2 + 1/3 + 1/5 + 1/7 + 1/11 ... 1/p'' this sum can be well approximated with: ''log( log(p) ) + M'' where ''M'' denotes Meissel-Mertens constant: 0.26149... ;See: :* Details in the Wikipedia article: Meissel-Mertens constant
import java.util.ArrayList; import java.util.BitSet; import java.util.List; /** * Calculates the Meissel-Mertens constant correct to 9 s.f. in approximately 15 seconds. */ public final class MeisselMertensConstant { public static void main(String[] aArgs) { List<Double> primeReciprocals = listPrimeReciprocals(1_000_000_000); final double euler = 0.577_215_664_901_532_861; double sum = 0.0; for ( double reciprocal : primeReciprocals ) { sum += reciprocal + Math.log(1.0 - reciprocal); } final double constant = euler + sum; System.out.println("The Meissel-Mertens constant = " + constant); } private static List<Double> listPrimeReciprocals(int aLimit) { BitSet sieve = new BitSet(aLimit + 1); sieve.set(2, aLimit + 1); final int squareRoot = (int) Math.sqrt(aLimit); for ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) { for ( int j = i * i; j <= aLimit; j += i ) { sieve.clear(j); } } List<Double> result = new ArrayList<Double>(sieve.cardinality()); for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) { result.add(1.0 / i); } return result; } }
Metallic ratios
Java
Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series of related ratios that are referred to as the "'''Metallic ratios'''". The '''Golden ratio''' was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was also known to the early Greeks, though was not named so until later as a nod to the '''Golden ratio''' to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means''). ''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".'' '''Metallic ratios''' are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer '''b''' determines which specific one it is. Using the quadratic equation: ( -b +- (b2 - 4ac) ) / 2a = x Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get: ( b +- (b2 + 4) ) ) / 2 = x We only want the real root: ( b + (b2 + 4) ) ) / 2 = x When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''. ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''. ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5''' are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''. We will refer to it here as the '''Platinum ratio''', though it is kind-of a degenerate case. '''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten '''Metallic ratios''' are: :::::: {| class="wikitable" style="text-align: center;" |+ Metallic ratios !Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link |- |Platinum||0||(0 + 4) / 2|| 1||-||- |- |Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]] |- |Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]] |- |Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]] |- |Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]] |- |Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]] |- |Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]] |- |Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]] |- |Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]] |- |Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]] |} There are other ways to find the '''Metallic ratios'''; one, (the focus of this task) is through '''successive approximations of Lucas sequences'''. A traditional '''Lucas sequence''' is of the form: x''n'' = P * x''n-1'' - Q * x''n-2'' and starts with the first 2 values '''0, 1'''. For our purposes in this task, to find the metallic ratios we'll use the form: x''n'' = b * x''n-1'' + x''n-2'' ( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' At any rate, when '''b = 1''' we get: x''n'' = x''n-1'' + x''n-2'' 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When '''b = 2''': x''n'' = 2 * x''n-1'' + x''n-2'' 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the ('''n+1''')th term by the '''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio. For '''b = 1''' (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest possible convergence for any irrational number. ;Task For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''': * Generate the corresponding "Lucas" sequence. * Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence. * Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places. * Show the '''value''' of the '''approximation''' at the required accuracy. * Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. ;See also * Wikipedia: Metallic mean * Wikipedia: Lucas sequence
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
Metronome
Java
The task is to implement a metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
class Metronome{ double bpm; int measure, counter; public Metronome(double bpm, int measure){ this.bpm = bpm; this.measure = measure; } public void start(){ while(true){ try { Thread.sleep((long)(1000*(60.0/bpm))); }catch(InterruptedException e) { e.printStackTrace(); } counter++; if (counter%measure==0){ System.out.println("TICK"); }else{ System.out.println("TOCK"); } } } } public class test { public static void main(String[] args) { Metronome metronome1 = new Metronome(120,4); metronome1.start(); } }
Mian-Chowla sequence
Java
The Mian-Chowla sequence is an integer sequence defined recursively. Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences. The sequence starts with: ::a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ::ai + aj is distinct, for all i and j less than or equal to n. ;The Task: :* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence. :* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence. Demonstrating working through the first few terms longhand: ::a1 = 1 ::1 + 1 = 2 Speculatively try a2 = 2 ::1 + 1 = 2 ::1 + 2 = 3 ::2 + 2 = 4 There are no repeated sums so '''2''' is the next number in the sequence. Speculatively try a3 = 3 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 3 = 4 ::2 + 2 = 4 ::2 + 3 = 5 ::3 + 3 = 6 Sum of '''4''' is repeated so '''3''' is rejected. Speculatively try a3 = 4 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 4 = 5 ::2 + 2 = 4 ::2 + 4 = 6 ::4 + 4 = 8 There are no repeated sums so '''4''' is the next number in the sequence. And so on... ;See also: :* OEIS:A005282 Mian-Chowla sequence
import java.util.Arrays; public class MianChowlaSequence { public static void main(String[] args) { long start = System.currentTimeMillis(); System.out.println("First 30 terms of the Mian–Chowla sequence."); mianChowla(1, 30); System.out.println("Terms 91 through 100 of the Mian–Chowla sequence."); mianChowla(91, 100); long end = System.currentTimeMillis(); System.out.printf("Elapsed = %d ms%n", (end-start)); } private static void mianChowla(int minIndex, int maxIndex) { int [] sums = new int[1]; int [] chowla = new int[maxIndex+1]; sums[0] = 2; chowla[0] = 0; chowla[1] = 1; if ( minIndex == 1 ) { System.out.printf("%d ", 1); } int chowlaLength = 1; for ( int n = 2 ; n <= maxIndex ; n++ ) { // Sequence is strictly increasing. int test = chowla[n - 1]; // Bookkeeping. Generate only new sums. int[] sumsNew = Arrays.copyOf(sums, sums.length + n); int sumNewLength = sums.length; int savedsSumNewLength = sumNewLength; // Generate test candidates for the next value of the sequence. boolean found = false; while ( ! found ) { test++; found = true; sumNewLength = savedsSumNewLength; // Generate test sums for ( int j = 0 ; j <= chowlaLength ; j++ ) { int testSum = (j == 0 ? test : chowla[j]) + test; boolean duplicate = false; // Check if test Sum in array for ( int k = 0 ; k < sumNewLength ; k++ ) { if ( sumsNew[k] == testSum ) { duplicate = true; break; } } if ( ! duplicate ) { // Add to array sumsNew[sumNewLength] = testSum; sumNewLength++; } else { // Duplicate found. Therefore, test candidate of the next value of the sequence is not OK. found = false; break; } } } // Bingo! Now update bookkeeping. chowla[n] = test; chowlaLength++; sums = sumsNew; if ( n >= minIndex ) { System.out.printf("%d %s", chowla[n], (n==maxIndex ? "\n" : "")); } } } }
Middle three digits
Java
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
Mind boggling card trick
Java
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. ; 1. Cards. # Create a common deck of cards of 52 cards (which are half red, half black). # Give the pack a good shuffle. ; 2. Deal from the shuffled deck, you'll be creating three piles. # Assemble the cards face down. ## Turn up the ''top card'' and hold it in your hand. ### if the card is black, then add the ''next'' card (unseen) to the "black" pile. ### If the card is red, then add the ''next'' card (unseen) to the "red" pile. ## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness). # Repeat the above for the rest of the shuffled deck. ; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles. # Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch. # Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch. # Put the "red" bunch into the "black" pile. # Put the "black" bunch into the "red" pile. # (The above two steps complete the swap of '''X''' cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). ; 4. Order from randomness? # Verify (or not) the mathematician's assertion that: '''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.''' (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; public final class MindBogglingCardTrick { public static void main(String[] aArgs) { List<Character> cards = new ArrayList<Character>(52); cards.addAll(Collections.nCopies(26, 'R')); cards.addAll(Collections.nCopies(26, 'B')); Collections.shuffle(cards); List<Character> redPile = new ArrayList<Character>(); List<Character> blackPile = new ArrayList<Character>(); List<Character> discardPile = new ArrayList<Character>(); for ( int i = 0; i < 52; i += 2 ) { if ( cards.get(i) == 'R' ) { redPile.add(cards.get(i + 1)); } else { blackPile.add(cards.get(i + 1)); } discardPile.add(cards.get(i)); } System.out.println("A sample run." + System.lineSeparator()); System.out.println("After dealing the cards the state of the piles is:"); System.out.println(String.format(" Red : %2d cards -> %s", redPile.size(), redPile)); System.out.println(String.format(" Black : %2d cards -> %s", blackPile.size(), blackPile)); System.out.println(String.format(" Discard: %2d cards -> %s", discardPile.size(), discardPile)); ThreadLocalRandom random = ThreadLocalRandom.current(); final int minimumSize = Math.min(redPile.size(), blackPile.size()); final int choice = random.nextInt(1, minimumSize + 1); List<Integer> redIndexes = IntStream.range(0, redPile.size()).boxed().collect(Collectors.toList()); List<Integer> blackIndexes = IntStream.range(0, blackPile.size()).boxed().collect(Collectors.toList()); Collections.shuffle(redIndexes); Collections.shuffle(blackIndexes); List<Integer> redChosenIndexes = redIndexes.subList(0, choice); List<Integer> blackChosenIndexes = blackIndexes.subList(0, choice); System.out.println(System.lineSeparator() + "Number of cards are to be swapped: " + choice); System.out.println("The respective zero-based indices of the cards to be swapped are:"); System.out.println(" Red : " + redChosenIndexes); System.out.println(" Black : " + blackChosenIndexes); for ( int i = 0; i < choice; i++ ) { final char temp = redPile.get(redChosenIndexes.get(i)); redPile.set(redChosenIndexes.get(i), blackPile.get(blackChosenIndexes.get(i))); blackPile.set(blackChosenIndexes.get(i), temp); } System.out.println(System.lineSeparator() + "After swapping cards the state of the red and black piless is:"); System.out.println(" Red : " + redPile); System.out.println(" Black : " + blackPile); int redCount = 0; for ( char ch : redPile ) { if ( ch == 'R' ) { redCount += 1; } } int blackCount = 0; for ( char ch : blackPile ) { if ( ch == 'B' ) { blackCount += 1; } } System.out.println(System.lineSeparator() + "The number of red cards in the red pile: " + redCount); System.out.println("The number of black cards in the black pile: " + blackCount); if ( redCount == blackCount ) { System.out.println("So the asssertion is correct."); } else { System.out.println("So the asssertion is incorrect."); } } }
Minimal steps down to 1
Java
Given: * A starting, positive integer (greater than one), N. * A selection of possible integer perfect divisors, D. * And a selection of possible subtractors, S. The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be: * Divided by any member of D if it is perfectly divided by D, (remainder zero). * OR have one of S subtracted from it, if N is greater than the member of S. There may be many ways to reduce the initial N down to 1. Your program needs to: * Find the ''minimum'' number of ''steps'' to reach 1. * Show '''one''' way of getting fron N to 1 in those minimum steps. ;Examples: No divisors, D. a single subtractor of 1. :Obviousely N will take N-1 subtractions of 1 to reach 1 Single divisor of 2; single subtractor of 1: :N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1 :N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1 Divisors 2 and 3; subtractor 1: :N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1 ;Task: Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1: :1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2: :3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. ;Optional stretch goal: :2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000 ;Reference: * Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MinimalStepsDownToOne { public static void main(String[] args) { runTasks(getFunctions1()); runTasks(getFunctions2()); runTasks(getFunctions3()); } private static void runTasks(List<Function> functions) { Map<Integer,List<String>> minPath = getInitialMap(functions, 5); // Task 1 int max = 10; populateMap(minPath, functions, max); System.out.printf("%nWith functions: %s%n", functions); System.out.printf(" Minimum steps to 1:%n"); for ( int n = 2 ; n <= max ; n++ ) { int steps = minPath.get(n).size(); System.out.printf(" %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n)); } // Task 2 displayMaxMin(minPath, functions, 2000); // Task 2a displayMaxMin(minPath, functions, 20000); // Task 2a + displayMaxMin(minPath, functions, 100000); } private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) { populateMap(minPath, functions, max); List<Integer> maxIntegers = getMaxMin(minPath, max); int maxSteps = maxIntegers.remove(0); int numCount = maxIntegers.size(); System.out.printf(" There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers); } private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) { int maxSteps = Integer.MIN_VALUE; List<Integer> maxIntegers = new ArrayList<Integer>(); for ( int n = 2 ; n <= max ; n++ ) { int len = minPath.get(n).size(); if ( len > maxSteps ) { maxSteps = len; maxIntegers.clear(); maxIntegers.add(n); } else if ( len == maxSteps ) { maxIntegers.add(n); } } maxIntegers.add(0, maxSteps); return maxIntegers; } private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) { for ( int n = 2 ; n <= max ; n++ ) { if ( minPath.containsKey(n) ) { continue; } Function minFunction = null; int minSteps = Integer.MAX_VALUE; for ( Function f : functions ) { if ( f.actionOk(n) ) { int result = f.action(n); int steps = 1 + minPath.get(result).size(); if ( steps < minSteps ) { minFunction = f; minSteps = steps; } } } int result = minFunction.action(n); List<String> path = new ArrayList<String>(); path.add(minFunction.toString(n)); path.addAll(minPath.get(result)); minPath.put(n, path); } } private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) { Map<Integer,List<String>> minPath = new HashMap<>(); for ( int i = 2 ; i <= max ; i++ ) { for ( Function f : functions ) { if ( f.actionOk(i) ) { int result = f.action(i); if ( result == 1 ) { List<String> path = new ArrayList<String>(); path.add(f.toString(i)); minPath.put(i, path); } } } } return minPath; } private static List<Function> getFunctions3() { List<Function> functions = new ArrayList<>(); functions.add(new Divide2Function()); functions.add(new Divide3Function()); functions.add(new Subtract2Function()); functions.add(new Subtract1Function()); return functions; } private static List<Function> getFunctions2() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract2Function()); return functions; } private static List<Function> getFunctions1() { List<Function> functions = new ArrayList<>(); functions.add(new Divide3Function()); functions.add(new Divide2Function()); functions.add(new Subtract1Function()); return functions; } public abstract static class Function { abstract public int action(int n); abstract public boolean actionOk(int n); abstract public String toString(int n); } public static class Divide2Function extends Function { @Override public int action(int n) { return n/2; } @Override public boolean actionOk(int n) { return n % 2 == 0; } @Override public String toString(int n) { return "/2 -> " + n/2; } @Override public String toString() { return "Divisor 2"; } } public static class Divide3Function extends Function { @Override public int action(int n) { return n/3; } @Override public boolean actionOk(int n) { return n % 3 == 0; } @Override public String toString(int n) { return "/3 -> " + n/3; } @Override public String toString() { return "Divisor 3"; } } public static class Subtract1Function extends Function { @Override public int action(int n) { return n-1; } @Override public boolean actionOk(int n) { return true; } @Override public String toString(int n) { return "-1 -> " + (n-1); } @Override public String toString() { return "Subtractor 1"; } } public static class Subtract2Function extends Function { @Override public int action(int n) { return n-2; } @Override public boolean actionOk(int n) { return n > 2; } @Override public String toString(int n) { return "-2 -> " + (n-2); } @Override public String toString() { return "Subtractor 2"; } } }
Minimum multiple of m where digital sum equals m
Java
Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''. ;Task * Find the first 40 elements of the sequence. ;Stretch * Find the next 30 elements of the sequence. ;See also ;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
public final class MinimumMultipleDigitSum { public static void main(String[] aArgs) { for ( int n = 1; n <= 70; n++ ) { int k = 0; while ( digitSum(k += n) != n ); System.out.print(String.format("%8d%s", k / n, ( n % 10 ) == 0 ? "\n" : " ")); } } private static int digitSum(int aN) { int sum = 0; while ( aN > 0 ) { sum += aN % 10; aN /= 10; } return sum; } }
Minimum positive multiple in base 10 using only 0 and 1
Java
Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''". ;Task: Write a routine to find the B10 of a given integer. E.G. '''n''' '''B10''' '''n''' x '''multiplier''' 1 1 ( 1 x 1 ) 2 10 ( 2 x 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the '''B10''' value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find '''B10''' for: 1998, 2079, 2251, 2277 Stretch goal; find '''B10''' for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation. ;See also: :* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. :* How to find Minimum Positive Multiple in base 10 using only 0 and 1
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; // Title: Minimum positive multiple in base 10 using only 0 and 1 public class MinimumNumberOnlyZeroAndOne { public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = getA004290(n); System.out.printf("A004290(%d) = %s = %s * %s%n", n, result, n, result.divide(BigInteger.valueOf(n))); } } private static List<Integer> getTestCases() { List<Integer> testCases = new ArrayList<>(); for ( int i = 1 ; i <= 10 ; i++ ) { testCases.add(i); } for ( int i = 95 ; i <= 105 ; i++ ) { testCases.add(i); } for (int i : new int[] {297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878} ) { testCases.add(i); } return testCases; } private static BigInteger getA004290(int n) { if ( n == 1 ) { return BigInteger.valueOf(1); } int[][] L = new int[n][n]; for ( int i = 2 ; i < n ; i++ ) { L[0][i] = 0; } L[0][0] = 1; L[0][1] = 1; int m = 0; BigInteger ten = BigInteger.valueOf(10); BigInteger nBi = BigInteger.valueOf(n); while ( true ) { m++; // if L[m-1, (-10^m) mod n] = 1 then break if ( L[m-1][mod(ten.pow(m).negate(), nBi).intValue()] == 1 ) { break; } L[m][0] = 1; for ( int k = 1 ; k < n ; k++ ) { //L[m][k] = Math.max(L[m-1][k], L[m-1][mod(k-pow(10,m), n)]); L[m][k] = Math.max(L[m-1][k], L[m-1][mod(BigInteger.valueOf(k).subtract(ten.pow(m)), nBi).intValue()]); } } //int r = pow(10,m); //int k = mod(-pow(10,m), n); BigInteger r = ten.pow(m); BigInteger k = mod(r.negate(), nBi); for ( int j = m-1 ; j >= 1 ; j-- ) { if ( L[j-1][k.intValue()] == 0 ) { //r = r + pow(10, j); //k = mod(k-pow(10, j), n); r = r.add(ten.pow(j)); k = mod(k.subtract(ten.pow(j)), nBi); } } if ( k.compareTo(BigInteger.ONE) == 0 ) { r = r.add(BigInteger.ONE); } return r; } private static BigInteger mod(BigInteger m, BigInteger n) { BigInteger result = m.mod(n); if ( result.compareTo(BigInteger.ZERO) < 0 ) { result = result.add(n); } return result; } @SuppressWarnings("unused") private static int mod(int m, int n) { int result = m % n; if ( result < 0 ) { result += n; } return result; } @SuppressWarnings("unused") private static int pow(int base, int exp) { return (int) Math.pow(base, exp); } }