title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Resistor mesh | Java from Kotlin | Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,
find the resistance between points '''A''' and '''B'''.
;See also:
* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica
| import java.util.ArrayList;
import java.util.List;
public class ResistorMesh {
private static final int S = 10;
private static class Node {
double v;
int fixed;
Node(double v, int fixed) {
this.v = v;
this.fixed = fixed;
}
}
private static void setBoundary(List<List<Node>> m) {
m.get(1).get(1).v = 1.0;
m.get(1).get(1).fixed = 1;
m.get(6).get(7).v = -1.0;
m.get(6).get(7).fixed = -1;
}
private static double calcDiff(List<List<Node>> m, List<List<Node>> d, int w, int h) {
double total = 0.0;
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
double v = 0.0;
int n = 0;
if (i > 0) {
v += m.get(i - 1).get(j).v;
n++;
}
if (j > 0) {
v += m.get(i).get(j - 1).v;
n++;
}
if (i + 1 < h) {
v += m.get(i + 1).get(j).v;
n++;
}
if (j + 1 < w) {
v += m.get(i).get(j + 1).v;
n++;
}
v = m.get(i).get(j).v - v / n;
d.get(i).get(j).v = v;
if (m.get(i).get(j).fixed == 0) {
total += v * v;
}
}
}
return total;
}
private static double iter(List<List<Node>> m, int w, int h) {
List<List<Node>> d = new ArrayList<>(h);
for (int i = 0; i < h; ++i) {
List<Node> t = new ArrayList<>(w);
for (int j = 0; j < w; ++j) {
t.add(new Node(0.0, 0));
}
d.add(t);
}
double[] cur = new double[3];
double diff = 1e10;
while (diff > 1e-24) {
setBoundary(m);
diff = calcDiff(m, d, w, h);
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
m.get(i).get(j).v -= d.get(i).get(j).v;
}
}
}
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
int k = 0;
if (i != 0) k++;
if (j != 0) k++;
if (i < h - 1) k++;
if (j < w - 1) k++;
cur[m.get(i).get(j).fixed + 1] += d.get(i).get(j).v * k;
}
}
return (cur[2] - cur[0]) / 2.0;
}
public static void main(String[] args) {
List<List<Node>> mesh = new ArrayList<>(S);
for (int i = 0; i < S; ++i) {
List<Node> t = new ArrayList<>(S);
for (int j = 0; j < S; ++j) {
t.add(new Node(0.0, 0));
}
mesh.add(t);
}
double r = 2.0 / iter(mesh, S, S);
System.out.printf("R = %.15f", r);
}
} |
Reverse words in a string | Java | Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| public class ReverseWords {
static final String[] lines = {
" ----------- Ice and Fire ----------- ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
" fire. favor who those with hold I ",
" ",
" ... elided paragraph last ... ",
" Frost Robert ----------------------- "};
public static void main(String[] args) {
for (String line : lines) {
String[] words = line.split("\\s");
for (int i = words.length - 1; i >= 0; i--)
System.out.printf("%s ", words[i]);
System.out.println();
}
}
} |
Reverse words in a string | Java 8+ | Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| package string;
import static java.util.Arrays.stream;
public interface ReverseWords {
public static final String[] LINES = {
" ----------- Ice and Fire ----------- ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
" fire. favor who those with hold I ",
" ",
" ... elided paragraph last ... ",
" Frost Robert ----------------------- "
};
public static String[] reverseWords(String[] lines) {
return stream(lines)
.parallel()
.map(l -> l.split("\\s"))
.map(ws -> stream(ws)
.parallel()
.map(w -> " " + w)
.reduce(
"",
(w1, w2) -> w2 + w1
)
)
.toArray(String[]::new)
;
}
public static void main(String... arguments) {
stream(reverseWords(LINES))
.forEach(System.out::println)
;
}
} |
Rhonda numbers | Java | A positive integer '''''n''''' is said to be a Rhonda number to base '''''b''''' if the product of the base '''''b''''' digits of '''''n''''' is equal to '''''b''''' times the sum of '''''n''''''s prime factors.
''These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.''
'''25662''' is a Rhonda number to base-'''10'''. The prime factorization is '''2 x 3 x 7 x 13 x 47'''; the product of its base-'''10''' digits is equal to the base times the sum of its prime factors:
2 x 5 x 6 x 6 x 2 = 720 = 10 x (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
''Rhonda numbers to base 10 '''always''' contain at least 1 digit 5 and '''always''' contain at least 1 even digit.''
;Task
* For the non-prime bases '''''b''''' from '''2''' through '''16''' , find and display here, on this page, at least the first '''10''' '''Rhonda numbers''' to base '''''b'''''. Display the found numbers at least in base '''10'''.
;Stretch
* Extend out to base '''36'''.
;See also
;* Wolfram Mathworld - Rhonda numbers
;* Numbers Aplenty - Rhonda numbers
;* OEIS:A100968 - Integers n that are Rhonda numbers to base 4
;* OEIS:A100969 - Integers n that are Rhonda numbers to base 6
;* OEIS:A100970 - Integers n that are Rhonda numbers to base 8
;* OEIS:A100973 - Integers n that are Rhonda numbers to base 9
;* OEIS:A099542 - Rhonda numbers to base 10
;* OEIS:A100971 - Integers n that are Rhonda numbers to base 12
;* OEIS:A100972 - Integers n that are Rhonda numbers to base 14
;* OEIS:A100974 - Integers n that are Rhonda numbers to base 15
;* OEIS:A100975 - Integers n that are Rhonda numbers to base 16
;* OEIS:A255735 - Integers n that are Rhonda numbers to base 18
;* OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
;* OEIS:A255736 - Integers that are Rhonda numbers to base 30
;* Related Task: Smith numbers
| public class RhondaNumbers {
public static void main(String[] args) {
final int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (isPrime(base))
continue;
System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base);
int numbers[] = new int[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (isRhonda(base, n))
numbers[count++] = n;
}
System.out.printf("In base 10:");
for (int i = 0; i < limit; ++i)
System.out.printf(" %d", numbers[i]);
System.out.printf("\nIn base %d:", base);
for (int i = 0; i < limit; ++i)
System.out.printf(" %s", Integer.toString(numbers[i], base));
System.out.printf("\n\n");
}
}
private static int digitProduct(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
private static int primeFactorSum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static boolean isRhonda(int base, int n) {
return digitProduct(base, n) == base * primeFactorSum(n);
}
} |
Roman numerals/Decode | Java 1.5+ | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| public class Roman {
private static int decodeSingle(char letter) {
switch(letter) {
case 'M': return 1000;
case 'D': return 500;
case 'C': return 100;
case 'L': return 50;
case 'X': return 10;
case 'V': return 5;
case 'I': return 1;
default: return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for(int i = 0;i < uRoman.length() - 1;i++) {//loop over all but the last character
//if this character has a lower value than the next character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i+1))) {
//subtract it
result -= decodeSingle(uRoman.charAt(i));
} else {
//add it
result += decodeSingle(uRoman.charAt(i));
}
}
//decode the last character, which is always added
result += decodeSingle(uRoman.charAt(uRoman.length()-1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
} |
Roman numerals/Decode | Java 1.8+ | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| import java.util.Set;
import java.util.EnumSet;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public interface RomanNumerals {
public enum Numeral {
M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);
public final long weight;
private static final Set<Numeral> SET = Collections.unmodifiableSet(EnumSet.allOf(Numeral.class));
private Numeral(long weight) {
this.weight = weight;
}
public static Numeral getLargest(long weight) {
return SET.stream()
.filter(numeral -> weight >= numeral.weight)
.findFirst()
.orElse(I)
;
}
};
public static String encode(long n) {
return LongStream.iterate(n, l -> l - Numeral.getLargest(l).weight)
.limit(Numeral.values().length)
.filter(l -> l > 0)
.mapToObj(Numeral::getLargest)
.map(String::valueOf)
.collect(Collectors.joining())
;
}
public static long decode(String roman) {
long result = new StringBuilder(roman.toUpperCase()).reverse().chars()
.mapToObj(c -> Character.toString((char) c))
.map(numeral -> Enum.valueOf(Numeral.class, numeral))
.mapToLong(numeral -> numeral.weight)
.reduce(0, (a, b) -> a + (a <= b ? b : -b))
;
if (roman.charAt(0) == roman.charAt(1)) {
result += 2 * Enum.valueOf(Numeral.class, roman.substring(0, 1)).weight;
}
return result;
}
public static void test(long n) {
System.out.println(n + " = " + encode(n));
System.out.println(encode(n) + " = " + decode(encode(n)));
}
public static void main(String[] args) {
LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
}
} |
Roman numerals/Encode | Java from Ada | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| The conversion function throws an IllegalArgumentException for non-positive numbers, since Java does not have unsigned primitives.
|
Roman numerals/Encode | Java 1.5+ | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| public class RN {
enum Numeral {
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
int weight;
Numeral(int weight) {
this.weight = weight;
}
};
public static String roman(long n) {
if( n <= 0) {
throw new IllegalArgumentException();
}
StringBuilder buf = new StringBuilder();
final Numeral[] values = Numeral.values();
for (int i = values.length - 1; i >= 0; i--) {
while (n >= values[i].weight) {
buf.append(values[i]);
n -= values[i].weight;
}
}
return buf.toString();
}
public static void test(long n) {
System.out.println(n + " = " + roman(n));
}
public static void main(String[] args) {
test(1999);
test(25);
test(944);
test(0);
}
} |
Roman numerals/Encode | Java 1.8+ | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| import java.util.Set;
import java.util.EnumSet;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public interface RomanNumerals {
public enum Numeral {
M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);
public final long weight;
private static final Set<Numeral> SET = Collections.unmodifiableSet(EnumSet.allOf(Numeral.class));
private Numeral(long weight) {
this.weight = weight;
}
public static Numeral getLargest(long weight) {
return SET.stream()
.filter(numeral -> weight >= numeral.weight)
.findFirst()
.orElse(I)
;
}
};
public static String encode(long n) {
return LongStream.iterate(n, l -> l - Numeral.getLargest(l).weight)
.limit(Numeral.values().length)
.filter(l -> l > 0)
.mapToObj(Numeral::getLargest)
.map(String::valueOf)
.collect(Collectors.joining())
;
}
public static long decode(String roman) {
long result = new StringBuilder(roman.toUpperCase()).reverse().chars()
.mapToObj(c -> Character.toString((char) c))
.map(numeral -> Enum.valueOf(Numeral.class, numeral))
.mapToLong(numeral -> numeral.weight)
.reduce(0, (a, b) -> a + (a <= b ? b : -b))
;
if (roman.charAt(0) == roman.charAt(1)) {
result += 2 * Enum.valueOf(Numeral.class, roman.substring(0, 1)).weight;
}
return result;
}
public static void test(long n) {
System.out.println(n + " = " + encode(n));
System.out.println(encode(n) + " = " + decode(encode(n)));
}
public static void main(String[] args) {
LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
}
} |
Runge-Kutta method | Java | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given)
* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| Translation of [[Runge-Kutta_method#Ada|Ada]] via [[Runge-Kutta_method#D|D]]
|
Runge-Kutta method | Java 8 | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given)
* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| import static java.lang.Math.*;
import java.util.function.BiFunction;
public class RungeKutta {
static void runge(BiFunction<Double, Double, Double> yp_func, double[] t,
double[] y, double dt) {
for (int n = 0; n < t.length - 1; n++) {
double dy1 = dt * yp_func.apply(t[n], y[n]);
double dy2 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy1 / 2.0);
double dy3 = dt * yp_func.apply(t[n] + dt / 2.0, y[n] + dy2 / 2.0);
double dy4 = dt * yp_func.apply(t[n] + dt, y[n] + dy3);
t[n + 1] = t[n] + dt;
y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0;
}
}
static double calc_err(double t, double calc) {
double actual = pow(pow(t, 2.0) + 4.0, 2) / 16.0;
return abs(actual - calc);
}
public static void main(String[] args) {
double dt = 0.10;
double[] t_arr = new double[101];
double[] y_arr = new double[101];
y_arr[0] = 1.0;
runge((t, y) -> t * sqrt(y), t_arr, y_arr, dt);
for (int i = 0; i < t_arr.length; i++)
if (i % 10 == 0)
System.out.printf("y(%.1f) = %.8f Error: %.6f%n",
t_arr[i], y_arr[i],
calc_err(t_arr[i], y_arr[i]));
}
} |
Runtime evaluation | Java | Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:///" + className + ".class"), JavaFileObject.Kind.CLASS){
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:///" + className + ".java"), JavaFileObject.Kind.SOURCE){
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
// Now we can compile!
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
// Invoke a method on the thing we compiled
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
} |
Runtime evaluation/In an environment | Java 6+ | Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
| import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:///" + CLASS_NAME + Kind.SOURCE.extension ), Kind.SOURCE );
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception /* lazy programmer */ {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
} |
Ruth-Aaron numbers | Java | A '''Ruth-Aaron''' pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A '''Ruth-Aaron''' triple consists of '''''three''''' consecutive integers with the same properties.
There is a second variant of '''Ruth-Aaron''' numbers, one which uses prime ''factors'' rather than prime ''divisors''. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each '''Ruth-Aaron''' group by the first number in it.
;Task
* Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (factors).
* Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (divisors).
;Stretch
* Find and show the first '''Ruth-Aaron triple''' (factors).
* Find and show the first '''Ruth-Aaron triple''' (divisors).
;See also
;*Wikipedia: Ruth-Aaron pair
;*OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
;*OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
| import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public final class RuthAaronNumbers {
public static void main(String[] aArgs) {
System.out.println("The first 30 Ruth-Aaron numbers (factors):");
firstRuthAaronNumbers(30, NumberType.FACTOR);
System.out.println("The first 30 Ruth-Aaron numbers (divisors):");
firstRuthAaronNumbers(30, NumberType.DIVISOR);
System.out.println("First Ruth-Aaron triple (factors): " + firstRuthAaronTriple(NumberType.FACTOR));
System.out.println();
System.out.println("First Ruth-Aaron triple (divisors): " + firstRuthAaronTriple(NumberType.DIVISOR));
System.out.println();
}
private enum NumberType { DIVISOR, FACTOR }
private static void firstRuthAaronNumbers(int aCount, NumberType aNumberType) {
primeSumOne = 0;
primeSumTwo = 0;
for ( int n = 2, count = 0; count < aCount; n++ ) {
primeSumTwo = switch ( aNumberType ) {
case DIVISOR -> primeDivisorSum(n);
case FACTOR -> primeFactorSum(n);
};
if ( primeSumOne == primeSumTwo ) {
count += 1;
System.out.print(String.format("%6d", n - 1));
if ( count == aCount / 2 ) {
System.out.println();
}
}
primeSumOne = primeSumTwo;
}
System.out.println();
System.out.println();
}
private static int firstRuthAaronTriple(NumberType aNumberType) {
primeSumOne = 0;
primeSumTwo = 0;
primeSumThree = 0;
int n = 2;
boolean found = false;
while ( ! found ) {
primeSumThree = switch ( aNumberType ) {
case DIVISOR -> primeDivisorSum(n);
case FACTOR -> primeFactorSum(n);
};
if ( primeSumOne == primeSumTwo && primeSumTwo == primeSumThree ) {
found = true;
}
n += 1;
primeSumOne = primeSumTwo;
primeSumTwo = primeSumThree;
}
return n - 2;
}
private static int primeDivisorSum(int aNumber) {
return primeSum(aNumber, new HashSet<Integer>());
}
private static int primeFactorSum(int aNumber) {
return primeSum(aNumber, new ArrayList<Integer>());
}
private static int primeSum(int aNumber, Collection<Integer> aCollection) {
Collection<Integer> values = aCollection;
for ( int i = 0, prime = 2; prime * prime <= aNumber; i++ ) {
while ( aNumber % prime == 0 ) {
aNumber /= prime;
values.add(prime);
}
prime = primes.get(i + 1);
}
if ( aNumber > 1 ) {
values.add(aNumber);
}
return values.stream().reduce(0, ( l, r ) -> l + r );
}
private static List<Integer> listPrimeNumbersUpTo(int aNumber) {
BitSet sieve = new BitSet(aNumber + 1);
sieve.set(2, aNumber + 1);
final int squareRoot = (int) Math.sqrt(aNumber);
for ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) {
for ( int j = i * i; j <= aNumber; j += i ) {
sieve.clear(j);
}
}
List<Integer> result = new ArrayList<Integer>(sieve.cardinality());
for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {
result.add(i);
}
return result;
}
private static int primeSumOne, primeSumTwo, primeSumThree;
private static List<Integer> primes = listPrimeNumbersUpTo(50_000);
}
|
SHA-1 | Java | '''SHA-1''' or '''SHA1''' is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
| The solution to this task would be a small modification to [[MD5#Java|MD5]] (replacing "MD5" with "SHA-1" as noted [http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest here]).
|
Sailors, coconuts and a monkey problem | Java from C | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)
# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
# Show your answers here.
;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.
;Note:
* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!
;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
| public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x))
x++;
System.out.printf("%d: %d%n", n, x);
}
}
} |
Same fringe | Java | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
| import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2);
// NOT using short-circuit operator
while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null))
if (!node1.getData().equals(node2.getData()))
return false;
// Return true if finished at same time
return (node1 == null) && (node2 == null);
}
private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack)
{
while (!stack.isEmpty())
{
Node<T> node = stack.pop();
if (node.isLeaf())
return node;
Node<T> rightNode = node.getRight();
if (rightNode != null)
stack.push(rightNode);
Node<T> leftNode = node.getLeft();
if (leftNode != null)
stack.push(leftNode);
}
return null;
}
public static void main(String[] args)
{
SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50)));
SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null))));
SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56)))));
System.out.print("Leaves for set 1: ");
simpleWalk(headNode1);
System.out.println();
System.out.print("Leaves for set 2: ");
simpleWalk(headNode2);
System.out.println();
System.out.print("Leaves for set 3: ");
simpleWalk(headNode3);
System.out.println();
System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2));
System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3));
}
public static void simpleWalk(Node<Integer> node)
{
if (node.isLeaf())
System.out.print(node.getData() + " ");
else
{
Node<Integer> left = node.getLeft();
if (left != null)
simpleWalk(left);
Node<Integer> right = node.getRight();
if (right != null)
simpleWalk(right);
}
}
} |
Selectively replace multiple instances of a character within a string | Java from JavaScript | Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.
Given the string: "abracadabra", replace programatically:
* the first 'a' with 'A'
* the second 'a' with 'B'
* the fourth 'a' with 'C'
* the fifth 'a' with 'D'
* the first 'b' with 'E'
* the second 'r' with 'F'
Note that there is no replacement for the third 'a', second 'b' or first 'r'.
The answer should, of course, be : "AErBcadCbFD".
| int findNth(String s, char c, int n) {
if (n == 1) return s.indexOf(c);
return s.indexOf(c, findNth(s, c, n - 1) + 1);
}
String selectiveReplace(String s, Set... ops) {
char[] chars = s.toCharArray();
for (Set set : ops)
chars[findNth(s, set.old, set.n)] = set.rep;
return new String(chars);
}
record Set(int n, char old, char rep) { }
|
Self-describing numbers | Java | {{task}}There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, '''2020''' is a four-digit self describing number:
* position 0 has value 2 and there are two 0s in the number;
* position 1 has value 0 and there are no 1s in the number;
* position 2 has value 2 and there are two 2s;
* position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
;Task Description
# Write a function/routine/method/... that will check whether a given positive integer is self-describing.
# As an optional stretch goal - generate and display the set of self-describing numbers.
;Related tasks:
* [[Fours is the number of letters in the ...]]
* [[Look-and-say sequence]]
* [[Number names]]
* [[Self-referential sequence]]
* [[Spelling of ordinal numbers]]
| public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0); // number of times i-th digit must occur for it to be a self describing number
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
} |
Self numbers | Java from C# | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
;See also:
;*OEIS: A003052 - Self numbers or Colombian numbers
;*Wikipedia: Self numbers
| public class SelfNumbers {
private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
private static final boolean[] SV = new boolean[MC + 1];
private static void sieve() {
int[] dS = new int[10_000];
for (int a = 9, i = 9999; a >= 0; a--) {
for (int b = 9; b >= 0; b--) {
for (int c = 9, s = a + b; c >= 0; c--) {
for (int d = 9, t = s + c; d >= 0; d--) {
dS[i--] = t + d;
}
}
}
}
for (int a = 0, n = 0; a < 103; a++) {
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {
for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {
SV[dS[c] + s++] = true;
}
}
}
}
public static void main(String[] args) {
sieve();
System.out.println("The first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) {
if (!SV[i]) {
count++;
if (count <= 50) {
System.out.printf("%d ", i);
} else {
System.out.printf("%n%n Index Self number%n");
}
}
}
for (int i = 0, limit = 1, count = 0; i < MC; i++) {
if (!SV[i]) {
if (++count == limit) {
System.out.printf("%,12d %,13d%n", count, i);
limit *= 10;
}
}
}
}
} |
Semordnilap | Java 7+ | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: ''lager'' and ''regal''
;Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
| import java.nio.file.*;
import java.util.*;
public class Semordnilap {
public static void main(String[] args) throws Exception {
List<String> lst = Files.readAllLines(Paths.get("unixdict.txt"));
Set<String> seen = new HashSet<>();
int count = 0;
for (String w : lst) {
w = w.toLowerCase();
String r = new StringBuilder(w).reverse().toString();
if (seen.contains(r)) {
if (count++ < 5)
System.out.printf("%-10s %-10s\n", w, r);
} else seen.add(w);
}
System.out.println("\nSemordnilap pairs found: " + count);
}
} |
Sequence: nth number with exactly n divisors | Java | Calculate the sequence where each term an is the nth that has '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;See also
:*OEIS:A073916
;Related tasks
:*[[Sequence: smallest number greater than previous term with exactly n divisors]]
:*[[Sequence: smallest number with exactly n divisors]]
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class SequenceNthNumberWithExactlyNDivisors {
public static void main(String[] args) {
int max = 45;
smallPrimes(max);
for ( int n = 1; n <= max ; n++ ) {
System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n));
}
}
private static List<Integer> smallPrimes = new ArrayList<>();
private static void smallPrimes(int numPrimes) {
smallPrimes.add(2);
for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) {
if ( isPrime(n) ) {
smallPrimes.add(n);
count++;
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long d = 3 ; d*d <= test ; d += 2 ) {
if ( test % d == 0 ) {
return false;
}
}
return true;
}
private static int getDivisorCount(long n) {
int count = 1;
while ( n % 2 == 0 ) {
n /= 2;
count += 1;
}
for ( long d = 3 ; d*d <= n ; d += 2 ) {
long q = n / d;
long r = n % d;
int dc = 0;
while ( r == 0 ) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if ( n != 1 ) {
count *= 2;
}
return count;
}
private static BigInteger OEISA073916(int n) {
if ( isPrime(n) ) {
return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1);
}
int count = 0;
int result = 0;
for ( int i = 1 ; count < n ; i++ ) {
if ( n % 2 == 1 ) {
// The solution for an odd (non-prime) term is always a square number
int sqrt = (int) Math.sqrt(i);
if ( sqrt*sqrt != i ) {
continue;
}
}
if ( getDivisorCount(i) == n ) {
count++;
result = i;
}
}
return BigInteger.valueOf(result);
}
}
|
Sequence: smallest number greater than previous term with exactly n divisors | Java from C | Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;See also
:* OEIS:A069654
;Related tasks
:* [[Sequence: smallest number with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]
| public class AntiPrimesPlus {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
public static void main(String[] args) {
final int max = 15;
System.out.printf("The first %d terms of the sequence are:\n", max);
for (int i = 1, next = 1; next <= max; ++i) {
if (next == count_divisors(i)) {
System.out.printf("%d ", i);
next++;
}
}
System.out.println();
}
} |
Sequence: smallest number with exactly n divisors | Java from C | Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;Related tasks:
:* [[Sequence: smallest number greater than previous term with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]
;See also:
:* OEIS:A005179
| import java.util.Arrays;
public class OEIS_A005179 {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
public static void main(String[] args) {
final int max = 15;
int[] seq = new int[max];
System.out.printf("The first %d terms of the sequence are:\n", max);
for (int i = 1, n = 0; n < max; ++i) {
int k = count_divisors(i);
if (k <= max && seq[k - 1] == 0) {
seq[k- 1] = i;
n++;
}
}
System.out.println(Arrays.toString(seq));
}
} |
Set consolidation | Java 7 | Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:
* The two input sets if no common item exists between the two input sets of items.
* The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
;'''Example 1:'''
:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
;'''Example 2:'''
:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
;'''Example 3:'''
:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}
'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]
| import java.util.*;
public class SetConsolidation {
public static void main(String[] args) {
List<Set<Character>> h1 = hashSetList("AB", "CD");
System.out.println(consolidate(h1));
List<Set<Character>> h2 = hashSetList("AB", "BD");
System.out.println(consolidateR(h2));
List<Set<Character>> h3 = hashSetList("AB", "CD", "DB");
System.out.println(consolidate(h3));
List<Set<Character>> h4 = hashSetList("HIK", "AB", "CD", "DB", "FGH");
System.out.println(consolidateR(h4));
}
// iterative
private static <E> List<Set<E>>
consolidate(Collection<? extends Set<E>> sets) {
List<Set<E>> r = new ArrayList<>();
for (Set<E> s : sets) {
List<Set<E>> new_r = new ArrayList<>();
new_r.add(s);
for (Set<E> x : r) {
if (!Collections.disjoint(s, x)) {
s.addAll(x);
} else {
new_r.add(x);
}
}
r = new_r;
}
return r;
}
// recursive
private static <E> List<Set<E>> consolidateR(List<Set<E>> sets) {
if (sets.size() < 2)
return sets;
List<Set<E>> r = new ArrayList<>();
r.add(sets.get(0));
for (Set<E> x : consolidateR(sets.subList(1, sets.size()))) {
if (!Collections.disjoint(r.get(0), x)) {
r.get(0).addAll(x);
} else {
r.add(x);
}
}
return r;
}
private static List<Set<Character>> hashSetList(String... set) {
List<Set<Character>> r = new ArrayList<>();
for (int i = 0; i < set.length; i++) {
r.add(new HashSet<Character>());
for (int j = 0; j < set[i].length(); j++)
r.get(i).add(set[i].charAt(j));
}
return r;
}
} |
Set of real numbers | Java | All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary:
* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.
'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x'' ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}
:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]
:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) - (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1] [0, 2)
:* [0, 2) (1, 2]
:* [0, 3) - (0, 1)
:* [0, 3) - [0, 1]
'''Implementation notes'''
* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that
|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
| import java.util.Objects;
import java.util.function.Predicate;
public class RealNumberSet {
public enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN,
}
public static class RealSet {
private Double low;
private Double high;
private Predicate<Double> predicate;
private double interval = 0.00001;
public RealSet(Double low, Double high, Predicate<Double> predicate) {
this.low = low;
this.high = high;
this.predicate = predicate;
}
public RealSet(Double start, Double end, RangeType rangeType) {
this(start, end, d -> {
switch (rangeType) {
case CLOSED:
return start <= d && d <= end;
case BOTH_OPEN:
return start < d && d < end;
case LEFT_OPEN:
return start < d && d <= end;
case RIGHT_OPEN:
return start <= d && d < end;
default:
throw new IllegalStateException("Unhandled range type encountered.");
}
});
}
public boolean contains(Double d) {
return predicate.test(d);
}
public RealSet union(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.or(other.predicate).test(d));
}
public RealSet intersect(RealSet other) {
double low2 = Math.min(low, other.low);
double high2 = Math.max(high, other.high);
return new RealSet(low2, high2, d -> predicate.and(other.predicate).test(d));
}
public RealSet subtract(RealSet other) {
return new RealSet(low, high, d -> predicate.and(other.predicate.negate()).test(d));
}
public double length() {
if (low.isInfinite() || high.isInfinite()) return -1.0; // error value
if (high <= low) return 0.0;
Double p = low;
int count = 0;
do {
if (predicate.test(p)) count++;
p += interval;
} while (p < high);
return count * interval;
}
public boolean isEmpty() {
if (Objects.equals(high, low)) {
return predicate.negate().test(low);
}
return length() == 0.0;
}
}
public static void main(String[] args) {
RealSet a = new RealSet(0.0, 1.0, RangeType.LEFT_OPEN);
RealSet b = new RealSet(0.0, 2.0, RangeType.RIGHT_OPEN);
RealSet c = new RealSet(1.0, 2.0, RangeType.LEFT_OPEN);
RealSet d = new RealSet(0.0, 3.0, RangeType.RIGHT_OPEN);
RealSet e = new RealSet(0.0, 1.0, RangeType.BOTH_OPEN);
RealSet f = new RealSet(0.0, 1.0, RangeType.CLOSED);
RealSet g = new RealSet(0.0, 0.0, RangeType.CLOSED);
for (int i = 0; i <= 2; i++) {
Double dd = (double) i;
System.out.printf("(0, 1] ∪ [0, 2) contains %d is %s\n", i, a.union(b).contains(dd));
System.out.printf("[0, 2) ∩ (1, 2] contains %d is %s\n", i, b.intersect(c).contains(dd));
System.out.printf("[0, 3) − (0, 1) contains %d is %s\n", i, d.subtract(e).contains(dd));
System.out.printf("[0, 3) − [0, 1] contains %d is %s\n", i, d.subtract(f).contains(dd));
System.out.println();
}
System.out.printf("[0, 0] is empty is %s\n", g.isEmpty());
System.out.println();
RealSet aa = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x * x)) > 0.5
);
RealSet bb = new RealSet(
0.0, 10.0,
x -> (0.0 < x && x < 10.0) && Math.abs(Math.sin(Math.PI * x)) > 0.5
);
RealSet cc = aa.subtract(bb);
System.out.printf("Approx length of A - B is %f\n", cc.length());
}
} |
Set right-adjacent bits | Java | Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000,
and a zero or more integer n :
* Output the result of setting the n bits to the right of any set bit in b
(if those bits are present in b and therefore also preserving the width, e).
'''Some examples:'''
Set of examples showing how one bit in a nibble gets changed:
n = 2; Width e = 4:
Input b: 1000
Result: 1110
Input b: 0100
Result: 0111
Input b: 0010
Result: 0011
Input b: 0000
Result: 0000
Set of examples with the same input with set bits of varying distance apart:
n = 0; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 010000000000100000000010000000010000000100000010000010000100010010
n = 1; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011000000000110000000011000000011000000110000011000011000110011011
n = 2; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011100000000111000000011100000011100000111000011100011100111011111
n = 3; Width e = 66:
Input b: 010000000000100000000010000000010000000100000010000010000100010010
Result: 011110000000111100000011110000011110000111100011110011110111111111
'''Task:'''
* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.
* Use it to show, here, the results for the input examples above.
* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
| public final class SetRightAdjacentBits {
public static void main(String[] aArgs) {
setRightAdjacent("1000", 2);
setRightAdjacent("0100", 2);
setRightAdjacent("0010", 2);
setRightAdjacent("0000", 2);
String test = "010000000000100000000010000000010000000100000010000010000100010010";
setRightAdjacent(test, 0);
setRightAdjacent(test, 1);
setRightAdjacent(test, 2);
setRightAdjacent(test, 3);
}
private static void setRightAdjacent(String aText, int aNumber) {
System.out.println("n = " + aNumber + ", Width = " + aText.length() + ", Input: " + aText);
char[] text = aText.toCharArray();
char[] result = aText.toCharArray();
for ( int i = 0; i < result.length; i++ ) {
if ( text[i] == '1' ) {
for ( int j = i + 1; j <= i + aNumber && j < result.length; j++ ) {
result[j] = '1';
}
}
}
String spaces = " ".repeat(16 + String.valueOf(aText.length()).length());
System.out.println(spaces + "Result: " + new String(result) + System.lineSeparator());
}
}
|
Shoelace formula for polygonal area | Java 9 | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
;Task:
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| import java.util.List;
public class ShoelaceFormula {
private static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
private static double shoelaceArea(List<Point> v) {
int n = v.size();
double a = 0.0;
for (int i = 0; i < n - 1; i++) {
a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y;
}
return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0;
}
public static void main(String[] args) {
List<Point> v = List.of(
new Point(3, 4),
new Point(5, 11),
new Point(12, 8),
new Point(9, 5),
new Point(5, 6)
);
double area = shoelaceArea(v);
System.out.printf("Given a polygon with vertices %s,%n", v);
System.out.printf("its area is %f,%n", area);
}
} |
Shortest common supersequence | Java from D | The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.
;;Task:
Given two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.
Demonstrate this by printing s where u = "abcbdab" and v = "bdcaba".
;Also see:
* Wikipedia: shortest common supersequence
| public class ShortestCommonSuperSequence {
private static boolean isEmpty(String s) {
return null == s || s.isEmpty();
}
private static String scs(String x, String y) {
if (isEmpty(x)) {
return y;
}
if (isEmpty(y)) {
return x;
}
if (x.charAt(0) == y.charAt(0)) {
return x.charAt(0) + scs(x.substring(1), y.substring(1));
}
if (scs(x, y.substring(1)).length() <= scs(x.substring(1), y).length()) {
return y.charAt(0) + scs(x, y.substring(1));
} else {
return x.charAt(0) + scs(x.substring(1), y);
}
}
public static void main(String[] args) {
System.out.println(scs("abcbdab", "bdcaba"));
}
} |
Show ASCII table | Java | Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
| public class ShowAsciiTable {
public static void main(String[] args) {
for ( int i = 32 ; i <= 127 ; i++ ) {
if ( i == 32 || i == 127 ) {
String s = i == 32 ? "Spc" : "Del";
System.out.printf("%3d: %s ", i, s);
}
else {
System.out.printf("%3d: %c ", i, i);
}
if ( (i-1) % 6 == 0 ) {
System.out.println();
}
}
}
}
|
Show the epoch | Java | Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
;Related task:
* [[Date format]]
| import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTest{
public static void main(String[] args) {
Date date = new Date(0);
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(date));
}
} |
Sierpinski pentagon | Java 8 | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
;See also
* Sierpinski pentagon
| import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;
public class SierpinskiPentagon extends JPanel {
// exterior angle
final double degrees072 = toRadians(72);
/* After scaling we'll have 2 sides plus a gap occupying the length
of a side before scaling. The gap is the base of an isosceles triangle
with a base angle of 72 degrees. */
final double scaleFactor = 1 / (2 + cos(degrees072) * 2);
final int margin = 20;
int limit = 0;
Random r = new Random();
public SierpinskiPentagon() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(3000, (ActionEvent e) -> {
limit++;
if (limit >= 5)
limit = 0;
repaint();
}).start();
}
void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
double angle = 3 * degrees072; // starting angle
if (depth == 0) {
Path2D p = new Path2D.Double();
p.moveTo(x, y);
// draw from the top
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * side;
y = y - sin(angle) * side;
p.lineTo(x, y);
angle += degrees072;
}
g.setColor(RandomHue.next());
g.fill(p);
} else {
side *= scaleFactor;
/* Starting at the top of the highest pentagon, calculate
the top vertices of the other pentagons by taking the
length of the scaled side plus the length of the gap. */
double distance = side + side * cos(degrees072) * 2;
/* The top positions form a virtual pentagon of their own,
so simply move from one to the other by changing direction. */
for (int i = 0; i < 5; i++) {
x = x + cos(angle) * distance;
y = y - sin(angle) * distance;
drawPentagon(g, x, y, side, depth - 1);
angle += degrees072;
}
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
double radius = w / 2 - 2 * margin;
double side = radius * sin(PI / 5) * 2;
drawPentagon(g, w / 2, 3 * margin, side, limit);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Pentagon");
f.setResizable(true);
f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class RandomHue {
/* Try to avoid random color values clumping together */
final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
private static double hue = Math.random();
static Color next() {
hue = (hue + goldenRatioConjugate) % 1;
return Color.getHSBColor((float) hue, 1, 1);
}
} |
Sierpinski triangle/Graphical | Java | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
[[File:Sierpinski_Triangle_Unicon.PNG]]
| import javax.swing.*;
import java.awt.*;
/**
* SierpinskyTriangle.java
* Draws a SierpinskyTriangle in a JFrame
* The order of complexity is given from command line, but
* defaults to 3
*
* @author Istarnion
*/
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3; // Default to 3
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
} |
Sierpinski triangle/Graphical | Java 8 | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
[[File:Sierpinski_Triangle_Unicon.PNG]]
| import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import javax.swing.*;
public class SierpinskiTriangle extends JPanel {
private final int dim = 512;
private final int margin = 20;
private int limit = dim;
public SierpinskiTriangle() {
setPreferredSize(new Dimension(dim + 2 * margin, dim + 2 * margin));
setBackground(Color.white);
setForeground(Color.green.darker());
new Timer(2000, (ActionEvent e) -> {
limit /= 2;
if (limit <= 2)
limit = dim;
repaint();
}).start();
}
void drawTriangle(Graphics2D g, int x, int y, int size) {
if (size <= limit) {
Path2D p = new Path2D.Float();
p.moveTo(x, y);
p.lineTo(x + size / 2, y + size);
p.lineTo(x - size / 2, y + size);
g.fill(p);
} else {
size /= 2;
drawTriangle(g, x, y, size);
drawTriangle(g, x + size / 2, y + size, size);
drawTriangle(g, x - size / 2, y + size, size);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(margin, margin);
drawTriangle(g, dim / 2, 0, dim);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Sierpinski Triangle");
f.setResizable(false);
f.add(new SierpinskiTriangle(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Smith numbers | Java 7 | sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are ''excluded'' as they (naturally) satisfy this condition!
Smith numbers are also known as ''joke'' numbers.
;Example
Using the number '''166'''
Find the prime factors of '''166''' which are: '''2''' x '''83'''
Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''
Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''
Therefore, the number '''166''' is a Smith number.
;Task
Write a program to find all Smith numbers ''below'' 10000.
;See also
* from Wikipedia: [Smith number].
* from MathWorld: [Smith number].
* from OEIS A6753: [OEIS sequence A6753].
* from OEIS A104170: [Number of Smith numbers below 10^n].
* from The Prime pages: [Smith numbers].
| import java.util.*;
public class SmithNumbers {
public static void main(String[] args) {
for (int n = 1; n < 10_000; n++) {
List<Integer> factors = primeFactors(n);
if (factors.size() > 1) {
int sum = sumDigits(n);
for (int f : factors)
sum -= sumDigits(f);
if (sum == 0)
System.out.println(n);
}
}
}
static List<Integer> primeFactors(int n) {
List<Integer> result = new ArrayList<>();
for (int i = 2; n % i == 0; n /= i)
result.add(i);
for (int i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
result.add(i);
n /= i;
}
}
if (n != 1)
result.add(n);
return result;
}
static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += (n % 10);
n /= 10;
}
return sum;
}
} |
Soloway's recurring rainfall | Java | Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.
'''The problem:'''
Write a program that will read in integers and output their average. Stop reading when the value 99999 is input.
For languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.
'''Implementation Details:'''
* Only Integers are to be accepted as input
* Output should be floating point
* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)
* For languages where the user is inputting data, the number of data inputs can be "infinite"
* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)
The purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more "advanced". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.
'''References:'''
* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf
* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf
* https://en.wikipedia.org/wiki/Moving_average#Cumulative_average
| class recurringrainfall
{
private static int GetNextInt()
{
while (true)
{
System.out.print("Enter rainfall int, 99999 to quit: ");
String input = System.console().readLine();
try
{
int n = Integer.parseInt(input);
return n;
}
catch (Exception e)
{
System.out.println("Invalid input");
}
}
}
private static void recurringRainfall() {
float currentAverage = 0;
int currentEntryNumber = 0;
while (true) {
int entry = GetNextInt();
if (entry == 99999)
return;
currentEntryNumber++;
currentAverage = currentAverage + ((float)1/currentEntryNumber)*entry - ((float)1/currentEntryNumber)*currentAverage;
System.out.println("New Average: " + currentAverage);
}
}
public static void main(String args[]) {
recurringRainfall();
}
}
|
Solve a Hidato puzzle | Java 7 | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
** The grid is not necessarily rectangular.
** The grid may have holes in it.
** The grid is always connected.
** The number "1" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from "1" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
** A square may only contain one number.
* In a proper Hidato puzzle, the solution is unique.
For example the following problem
Sample Hidato problem, from Wikipedia
has the following solution, with path marked on it:
Solution to sample Hidato problem
;Related tasks:
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]];
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"};
setup(input);
printBoard();
System.out.println("\nFound:");
solve(start[0], start[1], 1, 0);
printBoard();
}
private static void setup(String[] input) {
/* This task is not about input validation, so
we're going to trust the input to be valid */
String[][] puzzle = new String[input.length][];
for (int i = 0; i < input.length; i++)
puzzle[i] = input[i].split(" ");
int nCols = puzzle[0].length;
int nRows = puzzle.length;
List<Integer> list = new ArrayList<>(nRows * nCols);
board = new int[nRows + 2][nCols + 2];
for (int[] row : board)
for (int c = 0; c < nCols + 2; c++)
row[c] = -1;
for (int r = 0; r < nRows; r++) {
String[] row = puzzle[r];
for (int c = 0; c < nCols; c++) {
String cell = row[c];
switch (cell) {
case "_":
board[r + 1][c + 1] = 0;
break;
case ".":
break;
default:
int val = Integer.parseInt(cell);
board[r + 1][c + 1] = val;
list.add(val);
if (val == 1)
start = new int[]{r + 1, c + 1};
}
}
}
Collections.sort(list);
given = new int[list.size()];
for (int i = 0; i < given.length; i++)
given[i] = list.get(i);
}
private static boolean solve(int r, int c, int n, int next) {
if (n > given[given.length - 1])
return true;
if (board[r][c] != 0 && board[r][c] != n)
return false;
if (board[r][c] == 0 && given[next] == n)
return false;
int back = board[r][c];
if (back == n)
next++;
board[r][c] = n;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if (solve(r + i, c + j, n + 1, next))
return true;
board[r][c] = back;
return false;
}
private static void printBoard() {
for (int[] row : board) {
for (int c : row) {
if (c == -1)
System.out.print(" . ");
else
System.out.printf(c > 0 ? "%2d " : "__ ", c);
}
System.out.println();
}
}
} |
Solve a Holy Knight's tour | Java 8 | Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:
;Example:
0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| import java.util.*;
public class HolyKnightsTour {
final static String[] board = {
" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"1xxxxxx ",
" xx x ",
" xxx "};
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 = 2;
public static void main(String[] args) {
int row = 0, col = 0;
grid = new int[base][base];
for (int r = 0; r < base; r++) {
Arrays.fill(grid[r], -1);
for (int c = 2; c < base - 2; c++) {
if (r >= 2 && r < base - 2) {
if (board[r - 2].charAt(c - 2) == 'x') {
grid[r][c] = 0;
total++;
}
if (board[r - 2].charAt(c - 2) == '1') {
row = r;
col = c;
}
}
}
}
grid[row][col] = 1;
if (solve(row, col, 2))
printResult();
}
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, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (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) - 1;
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 void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
} |
Solve a Hopido puzzle | Java 8 | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:
"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!"
Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.
Example:
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 0 . . .
Extra credits are available for other interesting designs.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
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) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
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;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
} |
Solve a Numbrix puzzle | Java 8 | Numbrix puzzles are similar to Hidato.
The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
;Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
;Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
;Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve the no connection puzzle]]
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
} |
Sparkline in unicode | Java | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
;Task:
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '########'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
:(note the mix of separators in this second case)!
;Notes:
* A space is not part of the generated sparkline.
* The sparkline may be accompanied by simple statistics of the data such as its range.
* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
:: "0, 1, 19, 20" -> ####
:: (Aiming to use just two spark levels)
:: "0, 999, 4000, 4999, 7000, 7999" -> ######
:: (Aiming to use just three spark levels)
:: It may be helpful to include these cases in output tests.
* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| public class Sparkline
{
String bars="▁▂▃▄▅▆▇█";
public static void main(String[] args)
{
Sparkline now=new Sparkline();
float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
now.display1D(arr);
System.out.println(now.getSparkline(arr));
float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
now.display1D(arr1);
System.out.println(now.getSparkline(arr1));
}
public void display1D(float[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public String getSparkline(float[] arr)
{
float min=Integer.MAX_VALUE;
float max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
float range=max-min;
int num=bars.length()-1;
String line="";
for(int i=0;i<arr.length;i++)
{
line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));
}
return line;
}
}
|
Spelling of ordinal numbers | Java | '''Ordinal numbers''' (as used in this Rosetta Code task), are numbers that describe the ''position'' of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th ***
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
'''2,000,000,000''' is two billion, ''not'' two milliard.
;Task:
Write a driver and a function (subroutine/routine ***) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: '''123''' '''00123.0''' '''1.23e2''' all are forms of the same integer.
Show all output here.
;Test cases:
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
;Related tasks:
* [[Number names]]
* [[N'th]]
| import java.util.HashMap;
import java.util.Map;
public class SpellingOfOrdinalNumbers {
public static void main(String[] args) {
for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) {
System.out.printf("%d = %s%n", test, toOrdinal(test));
}
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
}
|
Sphenic numbers | Java | Definitions
A '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).
For the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive.
Note that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.
;Examples
30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.
[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.
;Task
Calculate and show here:
1. All sphenic numbers less than 1,000.
2. All sphenic triplets less than 10,000.
;Stretch
3. How many sphenic numbers are there less than 1 million?
4. How many sphenic triplets are there less than 1 million?
5. What is the 200,000th sphenic number and its 3 prime factors?
6. What is the 5,000th sphenic triplet?
Hint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.
;References
* Wikipedia: Sphenic number
* OEIS:A007304 - Sphenic numbers
* OEIS:A165936 - Sphenic triplets (in effect)
;Related tasks
* [[Almost prime]]
* [[Square-free integers]]
| import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class SphenicNumbers {
public static void main(String[] args) {
final int limit = 1000000;
final int imax = limit / 6;
boolean[] sieve = primeSieve(imax + 1);
boolean[] sphenic = new boolean[limit + 1];
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = Math.min(imax, limit / (i * i));
if (jmax <= i)
break;
for (int j = i + 1; j <= jmax; ++j) {
if (!sieve[j])
continue;
int p = i * j;
int kmax = Math.min(imax, limit / p);
if (kmax <= j)
break;
for (int k = j + 1; k <= kmax; ++k) {
if (!sieve[k])
continue;
assert(p * k <= limit);
sphenic[p * k] = true;
}
}
}
System.out.println("Sphenic numbers < 1000:");
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' ');
}
System.out.println("\nSphenic triplets < 10,000:");
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
System.out.printf("(%d, %d, %d)%c",
i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' ');
}
}
int count = 0, triplets = 0, s200000 = 0, t5000 = 0;
for (int i = 0; i < limit; ++i) {
if (!sphenic[i])
continue;
++count;
if (count == 200000)
s200000 = i;
if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {
++triplets;
if (triplets == 5000)
t5000 = i;
}
}
System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count);
System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets);
List<Integer> factors = primeFactors(s200000);
assert(factors.size() == 3);
System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n",
s200000, factors.get(0), factors.get(1),
factors.get(2));
System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n",
t5000 - 2, t5000 - 1, t5000);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
private static List<Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
if (n > 1 && (n & 1) == 0) {
factors.add(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.add(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.add(n);
return factors;
}
} |
Split a character string based on change of character | Java | Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
| package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a main method that will, for each arg provided,
* transform a String into a list of sub-strings, where each contiguous
* series of characters is made into a String, then the next, and so on,
* and then it will output them all separated by a comma and a space.
*/
public class SplitStringByCharacterChange {
public static void main(String... args){
for (String string : args){
List<String> resultStrings = splitStringByCharacter(string);
String output = formatList(resultStrings);
System.out.println(output);
}
}
/**
* @param string String - String to split
* @return List<\String> - substrings of contiguous characters
*/
public static List<String> splitStringByCharacter(String string){
List<String> resultStrings = new ArrayList<>();
StringBuilder currentString = new StringBuilder();
for (int pointer = 0; pointer < string.length(); pointer++){
currentString.append(string.charAt(pointer));
if (pointer == string.length() - 1
|| currentString.charAt(0) != string.charAt(pointer + 1)) {
resultStrings.add(currentString.toString());
currentString = new StringBuilder();
}
}
return resultStrings;
}
/**
* @param list List<\String> - list of strings to format as a comma+space-delimited string
* @return String
*/
public static String formatList(List<String> list){
StringBuilder output = new StringBuilder();
for (int pointer = 0; pointer < list.size(); pointer++){
output.append(list.get(pointer));
if (pointer != list.size() - 1){
output.append(", ");
}
}
return output.toString();
}
} |
Square-free integers | Java from Go | Write a function to test if a number is ''square-free''.
A ''square-free'' is an integer which is divisible by no perfect square other
than '''1''' (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
::* '''1''' ---> '''145''' (inclusive)
::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
::* '''1''' ---> one hundred (inclusive)
::* '''1''' ---> one thousand (inclusive)
::* '''1''' ---> ten thousand (inclusive)
::* '''1''' ---> one hundred thousand (inclusive)
::* '''1''' ---> one million (inclusive)
;See also:
:* the Wikipedia entry: square-free integer
| import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1]; // composite = true
// no need to process even numbers > 2
long p = 3;
for (;;) {
long p2 = p * p;
if (p2 > limit) break;
for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
for (;;) {
p += 2;
if (!c[(int)p]) break;
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[(int)i]) primes.add(i);
}
return primes;
}
private static List<Long> squareFree(long from, long to) {
long limit = (long)Math.sqrt((double)to);
List<Long> primes = sieve(limit);
List<Long> results = new ArrayList<Long>();
outer: for (long i = from; i <= to; i++) {
for (long p : primes) {
long p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) continue outer;
}
results.add(i);
}
return results;
}
private final static long TRILLION = 1000000000000L;
public static void main(String[] args) {
System.out.println("Square-free integers from 1 to 145:");
List<Long> sf = squareFree(1, 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 20 == 0) {
System.out.println();
}
System.out.printf("%4d", sf.get(i));
}
System.out.print("\n\nSquare-free integers");
System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 5 == 0) System.out.println();
System.out.printf("%14d", sf.get(i));
}
System.out.println("\n\nNumber of square-free integers:\n");
long[] tos = {100, 1000, 10000, 100000, 1000000};
for (long to : tos) {
System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size());
}
}
} |
Square but not cube | Java | Show the first '''30''' positive integers which are squares but not cubes of such integers.
Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
| public class SquaresCubes {
public static boolean isPerfectCube(long n) {
long c = (long)Math.cbrt((double)n);
return ((c * c * c) == n);
}
public static void main(String... args) {
long n = 1;
int squareOnlyCount = 0;
int squareCubeCount = 0;
while ((squareOnlyCount < 30) || (squareCubeCount < 3)) {
long sq = n * n;
if (isPerfectCube(sq)) {
squareCubeCount++;
System.out.println("Square and cube: " + sq);
}
else {
squareOnlyCount++;
System.out.println("Square: " + sq);
}
n++;
}
}
} |
Stair-climbing puzzle | Java from C++ | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
* Base case (if the step() call returns true): it stepped up one step. QED
* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| public void stepUp(){
for (int i = 0; i < 1; step() ? ++i : --i);
} |
Statistics/Normal distribution | Java 8 | The derive normally distributed random numbers from a uniform generator.
;The task:
# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
# Mention any native language support for the generation of normally distributed random numbers.
;Reference:
* You may refer to code in [[Statistics/Basic]] if available.
| import static java.lang.Math.*;
import static java.util.Arrays.stream;
import java.util.Locale;
import java.util.function.DoubleSupplier;
import static java.util.stream.Collectors.joining;
import java.util.stream.DoubleStream;
import static java.util.stream.IntStream.range;
public class Test implements DoubleSupplier {
private double mu, sigma;
private double[] state = new double[2];
private int index = state.length;
Test(double m, double s) {
mu = m;
sigma = s;
}
static double[] meanStdDev(double[] numbers) {
if (numbers.length == 0)
return new double[]{0.0, 0.0};
double sx = 0.0, sxx = 0.0;
long n = 0;
for (double x : numbers) {
sx += x;
sxx += pow(x, 2);
n++;
}
return new double[]{sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n};
}
static String replicate(int n, String s) {
return range(0, n + 1).mapToObj(i -> s).collect(joining());
}
static void showHistogram01(double[] numbers) {
final int maxWidth = 50;
long[] bins = new long[10];
for (double x : numbers)
bins[(int) (x * bins.length)]++;
double maxFreq = stream(bins).max().getAsLong();
for (int i = 0; i < bins.length; i++)
System.out.printf(" %3.1f: %s%n", i / (double) bins.length,
replicate((int) (bins[i] / maxFreq * maxWidth), "*"));
System.out.println();
}
@Override
public double getAsDouble() {
index++;
if (index >= state.length) {
double r = sqrt(-2 * log(random())) * sigma;
double x = 2 * PI * random();
state = new double[]{mu + r * sin(x), mu + r * cos(x)};
index = 0;
}
return state[index];
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
double[] data = DoubleStream.generate(new Test(0.0, 0.5)).limit(100_000)
.toArray();
double[] res = meanStdDev(data);
System.out.printf("Mean: %8.6f, SD: %8.6f%n", res[0], res[1]);
showHistogram01(stream(data).map(a -> max(0.0, min(0.9999, a / 3 + 0.5)))
.toArray());
}
} |
Stern-Brocot sequence | Java 1.5+ | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#* --- Expanding another loop we get: ---
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#* 1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
;Related tasks:
:* [[Fusc sequence]].
:* [[Continued fraction/Arithmetic]]
;Ref:
* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.
| import java.math.BigInteger;
import java.util.LinkedList;
public class SternBrocot {
static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
add(1); add(1);
}};
private static void genSeq(int n){
for(int conIdx = 1; sequence.size() < n; conIdx++){
int consider = sequence.get(conIdx);
int pre = sequence.get(conIdx - 1);
sequence.add(consider + pre);
sequence.add(consider);
}
}
public static void main(String[] args){
genSeq(1200);
System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
for(int i = 1; i <= 10; i++){
System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
}
System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
boolean failure = false;
for(int i = 0; i < 999; i++){
failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
}
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
} |
Stern-Brocot sequence | Java 8 | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#* --- Expanding another loop we get: ---
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#* 1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
;Related tasks:
:* [[Fusc sequence]].
:* [[Continued fraction/Arithmetic]]
;Ref:
* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.
| import java.awt.*;
import javax.swing.*;
public class SternBrocot extends JPanel {
public SternBrocot() {
setPreferredSize(new Dimension(800, 500));
setFont(new Font("Arial", Font.PLAIN, 18));
setBackground(Color.white);
}
private void drawTree(int n1, int d1, int n2, int d2,
int x, int y, int gap, int lvl, Graphics2D g) {
if (lvl == 0)
return;
// mediant
int numer = n1 + n2;
int denom = d1 + d2;
if (lvl > 1) {
g.drawLine(x + 5, y + 4, x - gap + 5, y + 124);
g.drawLine(x + 5, y + 4, x + gap + 5, y + 124);
}
g.setColor(getBackground());
g.fillRect(x - 10, y - 15, 35, 40);
g.setColor(getForeground());
g.drawString(String.valueOf(numer), x, y);
g.drawString("_", x, y + 2);
g.drawString(String.valueOf(denom), x, y + 22);
drawTree(n1, d1, numer, denom, x - gap, y + 120, gap / 2, lvl - 1, g);
drawTree(numer, denom, n2, d2, x + gap, y + 120, gap / 2, lvl - 1, g);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
drawTree(0, 1, 1, 0, w / 2, 50, w / 4, 4, g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Stern-Brocot Tree");
f.setResizable(false);
f.add(new SternBrocot(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Stirling numbers of the first kind | Java | Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).
They may be defined directly to be the number of permutations of '''n'''
elements with '''k''' disjoint cycles.
Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.
Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.
Stirling numbers of the first kind follow the simple identities:
S1(0, 0) = 1
S1(n, 0) = 0 if n > 0
S1(n, k) = 0 if k > n
S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
''or''
S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed
;Task:
:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. 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 Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.
:* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''.
;See also:
:* '''Wikipedia - Stirling numbers of the first kind'''
:* '''OEIS:A008275 - Signed Stirling numbers of the first kind'''
:* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind'''
;Related Tasks:
:* '''Stirling numbers of the second kind'''
:* '''Lah numbers'''
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersFirstKind {
public static void main(String[] args) {
System.out.println("Unsigned Stirling numbers of the first kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling1(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S1(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling1(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling1(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( n > 0 && k == 0 ) {
return BigInteger.ZERO;
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = sterling1(n-1, k-1).add(BigInteger.valueOf(n-1).multiply(sterling1(n-1, k)));
COMPUTED.put(key, result);
return result;
}
}
|
Stirling numbers of the second kind | Java | Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to [[Bell numbers]], and may be derived from them.
Stirling numbers of the second kind obey the recurrence relation:
S2(n, 0) and S2(0, k) = 0 # for n, k > 0
S2(n, n) = 1
S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)
;Task:
:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. 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 Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).
:* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''.
;See also:
:* '''Wikipedia - Stirling numbers of the second kind'''
:* '''OEIS:A008277 - Stirling numbers of the second kind'''
;Related Tasks:
:* '''Stirling numbers of the first kind'''
:* '''Bell numbers'''
:* '''Lah numbers'''
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
|
Stream merge | Java | 2-stream merge
: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
; ''N''-stream merge
: The same as above, but reading from ''N'' sources.
: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class StreamMerge {
private static <T extends Comparable<T>> void merge2(Iterator<T> i1, Iterator<T> i2) {
T a = null, b = null;
while (i1.hasNext() || i2.hasNext()) {
if (null == a && i1.hasNext()) {
a = i1.next();
}
if (null == b && i2.hasNext()) {
b = i2.next();
}
if (null != a) {
if (null != b) {
if (a.compareTo(b) < 0) {
System.out.print(a);
a = null;
} else {
System.out.print(b);
b = null;
}
} else {
System.out.print(a);
a = null;
}
} else if (null != b) {
System.out.print(b);
b = null;
}
}
if (null != a) {
System.out.print(a);
}
if (null != b) {
System.out.print(b);
}
}
@SuppressWarnings("unchecked")
@SafeVarargs
private static <T extends Comparable<T>> void mergeN(Iterator<T>... iter) {
Objects.requireNonNull(iter);
if (iter.length == 0) {
throw new IllegalArgumentException("Must have at least one iterator");
}
Object[] pa = new Object[iter.length];
boolean done;
do {
done = true;
for (int i = 0; i < iter.length; i++) {
Iterator<T> t = iter[i];
if (null == pa[i] && t.hasNext()) {
pa[i] = t.next();
}
}
T min = null;
int idx = -1;
for (int i = 0; i < pa.length; ++i) {
T t = (T) pa[i];
if (null != t) {
if (null == min) {
min = t;
idx = i;
done = false;
} else if (t.compareTo(min) < 0) {
min = t;
idx = i;
done = false;
}
}
}
if (idx != -1) {
System.out.print(min);
pa[idx] = null;
}
} while (!done);
}
public static void main(String[] args) {
List<Integer> l1 = List.of(1, 4, 7, 10);
List<Integer> l2 = List.of(2, 5, 8, 11);
List<Integer> l3 = List.of(3, 6, 9, 12);
merge2(l1.iterator(), l2.iterator());
System.out.println();
mergeN(l1.iterator(), l2.iterator(), l3.iterator());
System.out.println();
System.out.flush();
}
} |
Strip control codes and extended characters from a string | Java 8+ | Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
:* a string with control codes stripped (but extended characters not stripped)
:* a string with control codes and extended characters stripped
In ASCII, the control codes have decimal codes 0 through to 31 and 127.
On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
| import java.util.function.IntPredicate;
public class StripControlCodes {
public static void main(String[] args) {
String s = "\u0000\n abc\u00E9def\u007F";
System.out.println(stripChars(s, c -> c > '\u001F' && c != '\u007F'));
System.out.println(stripChars(s, c -> c > '\u001F' && c < '\u007F'));
}
static String stripChars(String s, IntPredicate include) {
return s.codePoints().filter(include::test).collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
} |
Subleq | Java | One-Instruction Set Computer (OISC).
It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero.
;Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:
::::* simple numeric values
::::* memory addresses
::::* characters for input or output
Any reasonable word size that accommodates all three of the above uses is fine.
The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:
:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.
:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.
:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.
:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.
:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.
:# If the instruction pointer becomes negative, execution halts.
Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).
For purposes of this task, show the output of your solution when fed the below "Hello, world!" program.
As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.
15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0
The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:
start:
0f 11 ff subleq (zero), (message), -1
11 ff ff subleq (message), -1, -1 ; output character at message
10 01 ff subleq (neg1), (start+1), -1
10 03 ff subleq (neg1), (start+3), -1
0f 0f 00 subleq (zero), (zero), start
; useful constants
zero:
00 .data 0
neg1:
ff .data -1
; the message to print
message: .data "Hello, world!\n\0"
48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
| import java.util.Scanner;
public class Subleq {
public static void main(String[] args) {
int[] mem = {15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0,
-1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0};
Scanner input = new Scanner(System.in);
int instructionPointer = 0;
do {
int a = mem[instructionPointer];
int b = mem[instructionPointer + 1];
if (a == -1) {
mem[b] = input.nextInt();
} else if (b == -1) {
System.out.printf("%c", (char) mem[a]);
} else {
mem[b] -= mem[a];
if (mem[b] < 1) {
instructionPointer = mem[instructionPointer + 2];
continue;
}
}
instructionPointer += 3;
} while (instructionPointer >= 0);
}
} |
Substring/Top and tail | Java | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
* String with first character removed
* String with last character removed
* String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
| public class RM_chars {
public static void main( String[] args ){
System.out.println( "knight".substring( 1 ) );
System.out.println( "socks".substring( 0, 4 ) );
System.out.println( "brooms".substring( 1, 5 ) );
// first, do this by selecting a specific substring
// to exclude the first and last characters
System.out.println( "knight".replaceAll( "^.", "" ) );
System.out.println( "socks".replaceAll( ".$", "" ) );
System.out.println( "brooms".replaceAll( "^.|.$", "" ) );
// then do this using a regular expressions
}
} |
Sum and product puzzle | Java | * Wikipedia: Sum and Product Puzzle
| package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
/**
* This program applies the logic in the Sum and Product Puzzle for the value
* provided by systematically applying each requirement to all number pairs in
* range. Note that the requirements: (x, y different), (x < y), and
* (x, y > MIN_VALUE) are baked into the loops in run(), sumAddends(), and
* productFactors(), so do not need a separate test. Also note that to test a
* solution to this logic puzzle, it is suggested to test the condition with
* maxSum = 1685 to ensure that both the original solution (4, 13) and the
* additional solution (4, 61), and only these solutions, are found. Note
* also that at 1684 only the original solution should be found!
*/
public class SumAndProductPuzzle {
private final long beginning;
private final int maxSum;
private static final int MIN_VALUE = 2;
private List<int[]> firstConditionExcludes = new ArrayList<>();
private List<int[]> secondConditionExcludes = new ArrayList<>();
public static void main(String... args){
if (args.length == 0){
new SumAndProductPuzzle(100).run();
new SumAndProductPuzzle(1684).run();
new SumAndProductPuzzle(1685).run();
} else {
for (String arg : args){
try{
new SumAndProductPuzzle(Integer.valueOf(arg)).run();
} catch (NumberFormatException e){
System.out.println("Please provide only integer arguments. " +
"Provided argument " + arg + " was not an integer. " +
"Alternatively, calling the program with no arguments " +
"will run the puzzle where maximum sum equals 100, 1684, and 1865.");
}
}
}
}
public SumAndProductPuzzle(int maxSum){
this.beginning = System.currentTimeMillis();
this.maxSum = maxSum;
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" started at " + String.valueOf(beginning) + ".");
}
public void run(){
for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){
for (int y = x + 1; y < maxSum - MIN_VALUE; y++){
if (isSumNoGreaterThanMax(x,y) &&
isSKnowsPCannotKnow(x,y) &&
isPKnowsNow(x,y) &&
isSKnowsNow(x,y)
){
System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) +
" in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
}
}
System.out.println("Run with maximum sum of " + String.valueOf(maxSum) +
" ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms.");
}
public boolean isSumNoGreaterThanMax(int x, int y){
return x + y <= maxSum;
}
public boolean isSKnowsPCannotKnow(int x, int y){
if (firstConditionExcludes.contains(new int[] {x, y})){
return false;
}
for (int[] addends : sumAddends(x, y)){
if ( !(productFactors(addends[0], addends[1]).size() > 1) ) {
firstConditionExcludes.add(new int[] {x, y});
return false;
}
}
return true;
}
public boolean isPKnowsNow(int x, int y){
if (secondConditionExcludes.contains(new int[] {x, y})){
return false;
}
int countSolutions = 0;
for (int[] factors : productFactors(x, y)){
if (isSKnowsPCannotKnow(factors[0], factors[1])){
countSolutions++;
}
}
if (countSolutions == 1){
return true;
} else {
secondConditionExcludes.add(new int[] {x, y});
return false;
}
}
public boolean isSKnowsNow(int x, int y){
int countSolutions = 0;
for (int[] addends : sumAddends(x, y)){
if (isPKnowsNow(addends[0], addends[1])){
countSolutions++;
}
}
return countSolutions == 1;
}
public List<int[]> sumAddends(int x, int y){
List<int[]> list = new ArrayList<>();
int sum = x + y;
for (int addend = MIN_VALUE; addend < sum - addend; addend++){
if (isSumNoGreaterThanMax(addend, sum - addend)){
list.add(new int[]{addend, sum - addend});
}
}
return list;
}
public List<int[]> productFactors(int x, int y){
List<int[]> list = new ArrayList<>();
int product = x * y;
for (int factor = MIN_VALUE; factor < product / factor; factor++){
if (product % factor == 0){
if (isSumNoGreaterThanMax(factor, product / factor)){
list.add(new int[]{factor, product / factor});
}
}
}
return list;
}
} |
Sum digits of an integer | Java | Take a Natural Number in a given base and return the sum of its digits:
:* '''1'''10 sums to '''1'''
:* '''1234'''10 sums to '''10'''
:* '''fe'''16 sums to '''29'''
:* '''f0e'''16 sums to '''29'''
| import java.math.BigInteger;
public class SumDigits {
public static int sumDigits(long num) {
return sumDigits(num, 10);
}
public static int sumDigits(long num, int base) {
String s = Long.toString(num, base);
int result = 0;
for (int i = 0; i < s.length(); i++)
result += Character.digit(s.charAt(i), base);
return result;
}
public static int sumDigits(BigInteger num) {
return sumDigits(num, 10);
}
public static int sumDigits(BigInteger num, int base) {
String s = num.toString(base);
int result = 0;
for (int i = 0; i < s.length(); i++)
result += Character.digit(s.charAt(i), base);
return result;
}
public static void main(String[] args) {
System.out.println(sumDigits(1));
System.out.println(sumDigits(12345));
System.out.println(sumDigits(123045));
System.out.println(sumDigits(0xfe, 16));
System.out.println(sumDigits(0xf0e, 16));
System.out.println(sumDigits(new BigInteger("12345678901234567890")));
}
} |
Sum multiples of 3 and 5 | Java | The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''.
Show output for ''n'' = 1000.
This is is the same as Project Euler problem 1.
'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
| class SumMultiples {
public static long getSum(long n) {
long sum = 0;
for (int i = 3; i < n; i++) {
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(getSum(1000));
}
} |
Sum of elements below main diagonal of matrix | Java | Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
::: --- Matrix to be used: ---
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| public static void main(String[] args) {
int[][] matrix = {{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5}};
int sum = 0;
for (int row = 1; row < matrix.length; row++) {
for (int col = 0; col < row; col++) {
sum += matrix[row][col];
}
}
System.out.println(sum);
} |
Sum to 100 | Java from C++ | Find solutions to the ''sum to one hundred'' puzzle.
Add (insert) the mathematical
operators '''+''' or '''-''' (plus
or minus) before any of the digits in the
decimal numeric string '''123456789''' such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, '''100''').
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
:* Show all solutions that sum to '''100'''
:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)
:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task
:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
++ (where ''infinity'' would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: '''5074'''
(which, of course, isn't the lowest positive sum that can't be expressed).
| /*
* RossetaCode: Sum to 100, Java 8.
*
* Find solutions to the "sum to one hundred" puzzle.
*/
package rosettacode;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class SumTo100 implements Runnable {
public static void main(String[] args) {
new SumTo100().run();
}
void print(int givenSum) {
Expression expression = new Expression();
for (int i = 0; i < Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) {
if (expression.toInt() == givenSum) {
expression.print();
}
}
}
void comment(String commentString) {
System.out.println();
System.out.println(commentString);
System.out.println();
}
@Override
public void run() {
final Stat stat = new Stat();
comment("Show all solutions that sum to 100");
final int givenSum = 100;
print(givenSum);
comment("Show the sum that has the maximum number of solutions");
final int maxCount = Collections.max(stat.sumCount.keySet());
int maxSum;
Iterator<Integer> it = stat.sumCount.get(maxCount).iterator();
do {
maxSum = it.next();
} while (maxSum < 0);
System.out.println(maxSum + " has " + maxCount + " solutions");
comment("Show the lowest positive number that can't be expressed");
int value = 0;
while (stat.countSum.containsKey(value)) {
value++;
}
System.out.println(value);
comment("Show the ten highest numbers that can be expressed");
final int n = stat.countSum.keySet().size();
final Integer[] sums = stat.countSum.keySet().toArray(new Integer[n]);
Arrays.sort(sums);
for (int i = n - 1; i >= n - 10; i--) {
print(sums[i]);
}
}
private static class Expression {
private final static int NUMBER_OF_DIGITS = 9;
private final static byte ADD = 0;
private final static byte SUB = 1;
private final static byte JOIN = 2;
final byte[] code = new byte[NUMBER_OF_DIGITS];
final static int NUMBER_OF_EXPRESSIONS = 2 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3;
Expression next() {
for (int i = 0; i < NUMBER_OF_DIGITS; i++) {
if (++code[i] > JOIN) {
code[i] = ADD;
} else {
break;
}
}
return this;
}
int toInt() {
int value = 0;
int number = 0;
int sign = (+1);
for (int digit = 1; digit <= 9; digit++) {
switch (code[NUMBER_OF_DIGITS - digit]) {
case ADD:
value += sign * number;
number = digit;
sign = (+1);
break;
case SUB:
value += sign * number;
number = digit;
sign = (-1);
break;
case JOIN:
number = 10 * number + digit;
break;
}
}
return value + sign * number;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder(2 * NUMBER_OF_DIGITS + 1);
for (int digit = 1; digit <= NUMBER_OF_DIGITS; digit++) {
switch (code[NUMBER_OF_DIGITS - digit]) {
case ADD:
if (digit > 1) {
s.append('+');
}
break;
case SUB:
s.append('-');
break;
}
s.append(digit);
}
return s.toString();
}
void print() {
print(System.out);
}
void print(PrintStream printStream) {
printStream.format("%9d", this.toInt());
printStream.println(" = " + this);
}
}
private static class Stat {
final Map<Integer, Integer> countSum = new HashMap<>();
final Map<Integer, Set<Integer>> sumCount = new HashMap<>();
Stat() {
Expression expression = new Expression();
for (int i = 0; i < Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) {
int sum = expression.toInt();
countSum.put(sum, countSum.getOrDefault(sum, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : countSum.entrySet()) {
Set<Integer> set;
if (sumCount.containsKey(entry.getValue())) {
set = sumCount.get(entry.getValue());
} else {
set = new HashSet<>();
}
set.add(entry.getKey());
sumCount.put(entry.getValue(), set);
}
}
}
} |
Summarize and say sequence | Java 8 | There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
;Task:
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
;Related tasks:
* [[Fours is the number of letters in the ...]]
* [[Look-and-say sequence]]
* [[Number names]]
* [[Self-describing numbers]]
* [[Spelling of ordinal numbers]]
;Also see:
* The On-Line Encyclopedia of Integer Sequences.
| import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
} |
Super-d numbers | Java | A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where
2 <= d <= 9
For instance, 753 is a super-3 number because 3 x 7533 = 1280873331.
'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.
;Task:
:* Write a function/procedure/routine to find super-d numbers.
:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.
;Extra credit:
:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).
;See also:
:* Wolfram MathWorld - Super-d Number.
:* OEIS: A014569 - Super-3 Numbers.
| import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test = "";
for ( int i = 0 ; i < d ; i++ ) {
test += (""+d);
}
int n = 0;
int i = 0;
System.out.printf("First %d super-%d numbers: %n", max, d);
while ( n < max ) {
i++;
BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d));
if ( val.toString().contains(test) ) {
n++;
System.out.printf("%d ", i);
}
}
long end = System.currentTimeMillis();
System.out.printf("%nRun time %d ms%n%n", end-start);
}
}
|
Superellipse | Java 8 | A superellipse is a geometric figure defined as the set of all points (x, y) with
::: \left|\frac{x}{a}\right|^n\! + \left|\frac{y}{b}\right|^n\! = 1,
where ''n'', ''a'', and ''b'' are positive numbers.
;Task
Draw a superellipse with n = 2.5, and a = b = 200
| import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200; // a = b
double[] points = new double[a + 1];
Path2D p = new Path2D.Double();
p.moveTo(a, 0);
// calculate first quadrant
for (int x = a; x >= 0; x--) {
points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); // solve for y
p.lineTo(x, -points[x]);
}
// mirror to others
for (int x = 0; x <= a; x++)
p.lineTo(x, points[x]);
for (int x = a; x >= 0; x--)
p.lineTo(-x, points[x]);
for (int x = 0; x <= a; x++)
p.lineTo(-x, -points[x]);
g.translate(getWidth() / 2, getHeight() / 2);
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0x25B0C4DE, true));
g.fill(p);
g.setColor(new Color(0xB0C4DE)); // LightSteelBlue
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawGrid(g);
drawLegend(g);
drawEllipse(g);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
exp = source.getValue() / 2.0;
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Super Ellipse");
f.setResizable(false);
SuperEllipse panel = new SuperEllipse();
f.add(panel, BorderLayout.CENTER);
JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
exponent.addChangeListener(panel);
exponent.setMajorTickSpacing(1);
exponent.setPaintLabels(true);
exponent.setBackground(Color.white);
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
for (int i = 1; i < 10; i++)
labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));
exponent.setLabelTable(labelTable);
f.add(exponent, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Superpermutation minimisation | Java | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
;Reference:
* The Minimal Superpermutation Problem. by Nathaniel Johnston.
* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
* Superpermutations - Numberphile. A video
* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
* New Superpermutations Discovered! Standupmaths & Numberphile.
| Translation of [[Superpermutation_minimisation#C|C]] via [[Superpermutation_minimisation#D|D]]
|
Superpermutation minimisation | Java 8 | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
;Reference:
* The Minimal Superpermutation Problem. by Nathaniel Johnston.
* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
* Superpermutations - Numberphile. A video
* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
* New Superpermutations Discovered! Standupmaths & Numberphile.
| import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
}
static boolean r(int n) {
if (n == 0)
return false;
char c = superperm[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1))
return false;
}
superperm[pos++] = c;
return true;
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pos = n;
superperm = new char[factSum(n)];
for (int i = 0; i < n + 1; i++)
count[i] = i;
for (int i = 1; i < n + 1; i++)
superperm[i - 1] = chars.charAt(i);
while (r(n)) {
}
}
public static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n);
System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
System.out.println();
}
}
} |
Tarjan | Java | {{wikipedia|Graph}}
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
;References:
* The article on Wikipedia.
See also: [[Kosaraju]]
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public final class TarjanSCC {
public static void main(String[] aArgs) {
Graph graph = new Graph(8);
graph.addDirectedEdge(0, 1);
graph.addDirectedEdge(1, 2); graph.addDirectedEdge(1, 7);
graph.addDirectedEdge(2, 3); graph.addDirectedEdge(2, 6);
graph.addDirectedEdge(3, 4);
graph.addDirectedEdge(4, 2); graph.addDirectedEdge(4, 5);
graph.addDirectedEdge(6, 3); graph.addDirectedEdge(6, 5);
graph.addDirectedEdge(7, 0); graph.addDirectedEdge(7, 6);
System.out.println("The strongly connected components are: ");
for ( Set<Integer> component : graph.getSCC() ) {
System.out.println(component);
}
}
}
final class Graph {
public Graph(int aSize) {
adjacencyLists = new ArrayList<Set<Integer>>(aSize);
for ( int i = 0; i < aSize; i++ ) {
vertices.add(i);
adjacencyLists.add( new HashSet<Integer>() );
}
}
public void addDirectedEdge(int aFrom, int aTo) {
adjacencyLists.get(aFrom).add(aTo);
}
public List<Set<Integer>> getSCC() {
for ( int vertex : vertices ) {
if ( ! numbers.keySet().contains(vertex) ) {
stronglyConnect(vertex);
}
}
return stronglyConnectedComponents;
}
private void stronglyConnect(int aVertex) {
numbers.put(aVertex, index);
lowlinks.put(aVertex, index);
index += 1;
stack.push(aVertex);
for ( int adjacent : adjacencyLists.get(aVertex) ) {
if ( ! numbers.keySet().contains(adjacent) ) {
stronglyConnect(adjacent);
lowlinks.put(aVertex, Math.min(lowlinks.get(aVertex), lowlinks.get(adjacent)));
} else if ( stack.contains(adjacent) ) {
lowlinks.put(aVertex, Math.min(lowlinks.get(aVertex), numbers.get(adjacent)));
}
}
if ( lowlinks.get(aVertex) == numbers.get(aVertex) ) {
Set<Integer> stonglyConnectedComponent = new HashSet<Integer>();
int top;
do {
top = stack.pop();
stonglyConnectedComponent.add(top);
} while ( top != aVertex );
stronglyConnectedComponents.add(stonglyConnectedComponent);
}
}
private List<Set<Integer>> adjacencyLists;
private List<Integer> vertices = new ArrayList<Integer>();
private int index = 0;
private Stack<Integer> stack = new Stack<Integer>();
private Map<Integer, Integer> numbers = new HashMap<Integer, Integer>();
private Map<Integer, Integer> lowlinks = new HashMap<Integer, Integer>();
private List<Set<Integer>> stronglyConnectedComponents = new ArrayList<Set<Integer>>();
}
|
Tau function | Java from D | Given a positive integer, count the number of its positive divisors.
;Task
Show the result for the first '''100''' positive integers.
;Related task
* [[Tau number]]
| public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
public static void main(String[] args) {
final int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
} |
Teacup rim text | Java from C++ | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''.
That got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
;Task:
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.)
Having listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc.
The words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
| import java.io.*;
import java.util.*;
public class Teacup {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Teacup dictionary");
System.exit(1);
}
try {
findTeacupWords(loadDictionary(args[0]));
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
// The file is expected to contain one lowercase word per line
private static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new TreeSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String word;
while ((word = reader.readLine()) != null)
words.add(word);
return words;
}
}
private static void findTeacupWords(Set<String> words) {
List<String> teacupWords = new ArrayList<>();
Set<String> found = new HashSet<>();
for (String word : words) {
int len = word.length();
if (len < 3 || found.contains(word))
continue;
teacupWords.clear();
teacupWords.add(word);
char[] chars = word.toCharArray();
for (int i = 0; i < len - 1; ++i) {
String rotated = new String(rotate(chars));
if (rotated.equals(word) || !words.contains(rotated))
break;
teacupWords.add(rotated);
}
if (teacupWords.size() == len) {
found.addAll(teacupWords);
System.out.print(word);
for (int i = 1; i < len; ++i)
System.out.print(" " + teacupWords.get(i));
System.out.println();
}
}
}
private static char[] rotate(char[] ch) {
char c = ch[0];
System.arraycopy(ch, 1, ch, 0, ch.length - 1);
ch[ch.length - 1] = c;
return ch;
}
} |
Temperature conversion | Java | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
: 0 degrees Celsius corresponds to 273.15 kelvin.
: 0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
: 0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
;Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
;Example:
K 21.00
C -252.15
F -421.87
R 37.80
| public class TemperatureConversion {
public static void main(String args[]) {
if (args.length == 1) {
try {
double kelvin = Double.parseDouble(args[0]);
if (kelvin >= 0) {
System.out.printf("K %2.2f\n", kelvin);
System.out.printf("C %2.2f\n", kelvinToCelsius(kelvin));
System.out.printf("F %2.2f\n", kelvinToFahrenheit(kelvin));
System.out.printf("R %2.2f\n", kelvinToRankine(kelvin));
} else {
System.out.printf("%2.2f K is below absolute zero", kelvin);
}
} catch (NumberFormatException e) {
System.out.println(e);
}
}
}
public static double kelvinToCelsius(double k) {
return k - 273.15;
}
public static double kelvinToFahrenheit(double k) {
return k * 1.8 - 459.67;
}
public static double kelvinToRankine(double k) {
return k * 1.8;
}
} |
Test integerness | Java from Kotlin | {| class="wikitable"
|-
! colspan=2 | Input
! colspan=2 | Output
! rowspan=2 | Comment
|-
! Type
! Value
! exact
! tolerance = 0.00001
|-
| rowspan=3 | decimal
| 25.000000
| colspan=2 | true
|
|-
| 24.999999
| false
| true
|
|-
| 25.000100
| colspan=2 | false
|
|-
| rowspan=4 | floating-point
| -2.1e120
| colspan=2 | true
| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.
|-
| -5e-2
| colspan=2 | false
|
|-
| NaN
| colspan=2 | false
|
|-
| Inf
| colspan=2 | false
| This one is debatable. If your code considers it an integer, that's okay too.
|-
| rowspan=2 | complex
| 5.0+0.0i
| colspan=2 | true
|
|-
| 5-5i
| colspan=2 | false
|
|}
(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s + %si", real, imag);
}
return String.format("%s - %si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of %.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
}
}
} |
Textonyms | Java from c++ | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
;Task:
Write a program that finds textonyms in a list of words such as
[[Textonyms/wordlist]] or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
;Extra credit:
Use a word list and keypad mapping other than English.
| import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
public class RTextonyms {
private static final Map<Character, Character> mapping;
private int total, elements, textonyms, max_found;
private String filename, mappingResult;
private Vector<String> max_strings;
private Map<String, Vector<String>> values;
static {
mapping = new HashMap<Character, Character>();
mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');
mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');
mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');
mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');
mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');
mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');
mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');
mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');
}
public RTextonyms(String filename) {
this.filename = filename;
this.total = this.elements = this.textonyms = this.max_found = 0;
this.values = new HashMap<String, Vector<String>>();
this.max_strings = new Vector<String>();
return;
}
public void add(String line) {
String mapping = "";
total++;
if (!get_mapping(line)) {
return;
}
mapping = mappingResult;
if (values.get(mapping) == null) {
values.put(mapping, new Vector<String>());
}
int num_strings;
num_strings = values.get(mapping).size();
textonyms += num_strings == 1 ? 1 : 0;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.add(mapping);
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.add(mapping);
}
values.get(mapping).add(line);
return;
}
public void results() {
System.out.printf("Read %,d words from %s%n%n", total, filename);
System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements,
filename);
System.out.printf("They require %,d digit combinations to represent them.%n", values.size());
System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms);
System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1);
for (String key : max_strings) {
System.out.printf("%16s maps to: %s%n", key, values.get(key).toString());
}
System.out.println();
return;
}
public void match(String key) {
Vector<String> match;
match = values.get(key);
if (match == null) {
System.out.printf("Key %s not found%n", key);
}
else {
System.out.printf("Key %s matches: %s%n", key, match.toString());
}
return;
}
private boolean get_mapping(String line) {
mappingResult = line;
StringBuilder mappingBuilder = new StringBuilder();
for (char cc : line.toCharArray()) {
if (Character.isAlphabetic(cc)) {
mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));
}
else if (Character.isDigit(cc)) {
mappingBuilder.append(cc);
}
else {
return false;
}
}
mappingResult = mappingBuilder.toString();
return true;
}
public static void main(String[] args) {
String filename;
if (args.length > 0) {
filename = args[0];
}
else {
filename = "./unixdict.txt";
}
RTextonyms tc;
tc = new RTextonyms(filename);
Path fp = Paths.get(filename);
try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {
while (fs.hasNextLine()) {
tc.add(fs.nextLine());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
List<String> numbers = Arrays.asList(
"001", "228", "27484247", "7244967473642",
"."
);
tc.results();
for (String number : numbers) {
if (number.equals(".")) {
System.out.println();
}
else {
tc.match(number);
}
}
return;
}
}
|
The Name Game | Java from Kotlin | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
| import java.util.stream.Stream;
public class NameGame {
private static void printVerse(String name) {
StringBuilder sb = new StringBuilder(name.toLowerCase());
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
String x = sb.toString();
String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1);
String b = "b" + y;
String f = "f" + y;
String m = "m" + y;
switch (x.charAt(0)) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
default:
// no adjustment needed
break;
}
System.out.printf("%s, %s, bo-%s\n", x, x, b);
System.out.printf("Banana-fana fo-%s\n", f);
System.out.printf("Fee-fi-mo-%s\n", m);
System.out.printf("%s!\n\n", x);
}
public static void main(String[] args) {
Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse);
}
} |
The Twelve Days of Christmas | Java | Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
| public class TwelveDaysOfChristmas {
final static String[] gifts = {
"A partridge in a pear tree.", "Two turtle doves and",
"Three french hens", "Four calling birds",
"Five golden rings", "Six geese a-laying",
"Seven swans a-swimming", "Eight maids a-milking",
"Nine ladies dancing", "Ten lords a-leaping",
"Eleven pipers piping", "Twelve drummers drumming",
"And a partridge in a pear tree.", "Two turtle doves"
};
final static String[] days = {
"first", "second", "third", "fourth", "fifth", "sixth", "seventh",
"eighth", "ninth", "tenth", "eleventh", "Twelfth"
};
public static void main(String[] args) {
for (int i = 0; i < days.length; i++) {
System.out.printf("%nOn the %s day of Christmas%n", days[i]);
System.out.println("My true love gave to me:");
for (int j = i; j >= 0; j--)
System.out.println(gifts[i == 11 && j < 2 ? j + 12 : j]);
}
}
} |
Thue-Morse | Java | Create a Thue-Morse sequence.
;See also
* YouTube entry: The Fairest Sharing Sequence Ever
* YouTube entry: Math and OCD - My story with the Thue-Morse sequence
* Task: [[Fairshare between two and more]]
| public class ThueMorse {
public static void main(String[] args) {
sequence(6);
}
public static void sequence(int steps) {
StringBuilder sb1 = new StringBuilder("0");
StringBuilder sb2 = new StringBuilder("1");
for (int i = 0; i < steps; i++) {
String tmp = sb1.toString();
sb1.append(sb2);
sb2.append(tmp);
}
System.out.println(sb1);
}
} |
Tonelli-Shanks algorithm | Java 9 | {{wikipedia}}
In computational number theory, the Tonelli-Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:
:: x2 n (mod p)
where '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n Fp''' where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
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 (mod p)
;Algorithm pseudo-code:
All are taken to mean (mod p) unless stated otherwise.
* Input: '''p''' an odd prime, and an integer '''n''' .
* Step 0: Check that '''n''' is indeed a square: (n | p) must be 1 .
* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .
** If p 3 (mod 4) (i.e. s = 1), output the two solutions r +- n(p+1)/4 .
* Step 2: Select a non-square '''z''' such that (z | p) -1 and set c zq .
* Step 3: Set r n(q+1)/2, t nq, m = s .
* Step 4: Loop the following:
** If t 1, output '''r''' and '''p - r''' .
** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i 1 .
** Let b c2(m - i - 1), and set r rb, t tb2, c b2 and m = i .
;Task:
Implement the above algorithm.
Find solutions (if any) for
* n = 10 p = 13
* n = 56 p = 101
* n = 1030 p = 10009
* n = 1032 p = 10009
* n = 44402 p = 100049
;Extra credit:
* n = 665820697 p = 1000000009
* n = 881398088036 p = 1000000000039
* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
;See also:
* [[Modular exponentiation]]
* [[Cipolla's algorithm]]
| import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TonelliShanks {
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TEN = BigInteger.TEN;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger FOUR = BigInteger.valueOf(4);
private static class Solution {
private BigInteger root1;
private BigInteger root2;
private boolean exists;
Solution(BigInteger root1, BigInteger root2, boolean exists) {
this.root1 = root1;
this.root2 = root2;
this.exists = exists;
}
}
private static Solution ts(Long n, Long p) {
return ts(BigInteger.valueOf(n), BigInteger.valueOf(p));
}
private static Solution ts(BigInteger n, BigInteger p) {
BiFunction<BigInteger, BigInteger, BigInteger> powModP = (BigInteger a, BigInteger e) -> a.modPow(e, p);
Function<BigInteger, BigInteger> ls = (BigInteger a) -> powModP.apply(a, p.subtract(ONE).divide(TWO));
if (!ls.apply(n).equals(ONE)) return new Solution(ZERO, ZERO, false);
BigInteger q = p.subtract(ONE);
BigInteger ss = ZERO;
while (q.and(ONE).equals(ZERO)) {
ss = ss.add(ONE);
q = q.shiftRight(1);
}
if (ss.equals(ONE)) {
BigInteger r1 = powModP.apply(n, p.add(ONE).divide(FOUR));
return new Solution(r1, p.subtract(r1), true);
}
BigInteger z = TWO;
while (!ls.apply(z).equals(p.subtract(ONE))) z = z.add(ONE);
BigInteger c = powModP.apply(z, q);
BigInteger r = powModP.apply(n, q.add(ONE).divide(TWO));
BigInteger t = powModP.apply(n, q);
BigInteger m = ss;
while (true) {
if (t.equals(ONE)) return new Solution(r, p.subtract(r), true);
BigInteger i = ZERO;
BigInteger zz = t;
while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) {
zz = zz.multiply(zz).mod(p);
i = i.add(ONE);
}
BigInteger b = c;
BigInteger e = m.subtract(i).subtract(ONE);
while (e.compareTo(ZERO) > 0) {
b = b.multiply(b).mod(p);
e = e.subtract(ONE);
}
r = r.multiply(b).mod(p);
c = b.multiply(b).mod(p);
t = t.multiply(c).mod(p);
m = i;
}
}
public static void main(String[] args) {
List<Map.Entry<Long, Long>> pairs = List.of(
Map.entry(10L, 13L),
Map.entry(56L, 101L),
Map.entry(1030L, 10009L),
Map.entry(1032L, 10009L),
Map.entry(44402L, 100049L),
Map.entry(665820697L, 1000000009L),
Map.entry(881398088036L, 1000000000039L)
);
for (Map.Entry<Long, Long> pair : pairs) {
Solution sol = ts(pair.getKey(), pair.getValue());
System.out.printf("n = %s\n", pair.getKey());
System.out.printf("p = %s\n", pair.getValue());
if (sol.exists) {
System.out.printf("root1 = %s\n", sol.root1);
System.out.printf("root2 = %s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
System.out.println();
}
BigInteger bn = new BigInteger("41660815127637347468140745042827704103445750172002");
BigInteger bp = TEN.pow(50).add(BigInteger.valueOf(577));
Solution sol = ts(bn, bp);
System.out.printf("n = %s\n", bn);
System.out.printf("p = %s\n", bp);
if (sol.exists) {
System.out.printf("root1 = %s\n", sol.root1);
System.out.printf("root2 = %s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
}
} |
Top rank per group | Java 8 | Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| import java.io.File;
import java.util.*;
public class TopRankPerGroup {
private static class Employee {
final String name;
final String id;
final String department;
final int salary;
Employee(String[] rec) {
name = rec[0];
id = rec[1];
salary = Integer.parseInt(rec[2]);
department = rec[3];
}
@Override
public String toString() {
return String.format("%s %s %d %s", id, name, salary, department);
}
}
public static void main(String[] args) throws Exception {
int N = args.length > 0 ? Integer.parseInt(args[0]) : 3;
Map<String, List<Employee>> records = new TreeMap<>();
try (Scanner sc = new Scanner(new File("data.txt"))) {
while (sc.hasNextLine()) {
String[] rec = sc.nextLine().trim().split(", ");
List<Employee> lst = records.get(rec[3]);
if (lst == null) {
lst = new ArrayList<>();
records.put(rec[3], lst);
}
lst.add(new Employee(rec));
}
}
records.forEach((key, val) -> {
System.out.printf("%nDepartment %s%n", key);
val.stream()
.sorted((a, b) -> Integer.compare(b.salary, a.salary))
.limit(N).forEach(System.out::println);
});
}
} |
Topswops | Java from D | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
;Task:
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
;Note:
Topswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.
;Related tasks:
* [[Number reversal game]]
* [[Sorting algorithms/Pancake sort]]
| public class Topswops {
static final int maxBest = 32;
static int[] best;
static private void trySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
if (d + best[i] <= best[n])
return;
}
int[] deck2 = deck.clone();
for (int i = 1; i < n; i++) {
final int k = 1 << i;
if (deck2[i] == -1) {
if ((f & k) != 0)
continue;
} else if (deck2[i] != i)
continue;
deck2[0] = i;
for (int j = i - 1; j >= 0; j--)
deck2[i - j] = deck[j]; // Reverse copy.
trySwaps(deck2, f | k, d + 1, n);
}
}
static int topswops(int n) {
assert(n > 0 && n < maxBest);
best[n] = 0;
int[] deck0 = new int[n + 1];
for (int i = 1; i < n; i++)
deck0[i] = -1;
trySwaps(deck0, 1, 0, n);
return best[n];
}
public static void main(String[] args) {
best = new int[maxBest];
for (int i = 1; i < 11; i++)
System.out.println(i + ": " + topswops(i));
}
} |
Total circles area | Java | Example circles
Example circles filtered
Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.
One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.
To allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):
xc yc radius
1.6417233788 1.6121789534 0.0848270516
-1.4944608174 1.2077959613 1.1039549836
0.6110294452 -0.6907087527 0.9089162485
0.3844862411 0.2923344616 0.2375743054
-0.2495892950 -0.3832854473 1.0845181219
1.7813504266 1.6178237031 0.8162655711
-0.1985249206 -0.8343333301 0.0538864941
-1.7011985145 -0.1263820964 0.4776976918
-0.4319462812 1.4104420482 0.7886291537
0.2178372997 -0.9499557344 0.0357871187
-0.6294854565 -1.3078893852 0.7653357688
1.7952608455 0.6281269104 0.2727652452
1.4168575317 1.0683357171 1.1016025378
1.4637371396 0.9463877418 1.1846214562
-0.5263668798 1.7315156631 1.4428514068
-1.2197352481 0.9144146579 1.0727263474
-0.1389358881 0.1092805780 0.7350208828
1.5293954595 0.0030278255 1.2472867347
-0.5258728625 1.3782633069 1.3495508831
-0.1403562064 0.2437382535 1.3804956588
0.8055826339 -0.0482092025 0.3327165165
-0.6311979224 0.7184578971 0.2491045282
1.4685857879 -0.8347049536 1.3670667538
-0.6855727502 1.6465021616 1.0593087096
0.0152957411 0.0638919221 0.9771215985
The result is 21.56503660... .
;Related task:
* [[Circles of given radius through two points]].
;See also:
* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/
* http://stackoverflow.com/a/1667789/10562
| public class CirclesTotalArea {
/*
* Rectangles are given as 4-element arrays [tx, ty, w, h].
* Circles are given as 3-element arrays [cx, cy, r].
*/
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {
double r2 = circ[2] * circ[2];
// Every corner point of rectangle must be inside the circle.
return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2;
}
private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) {
// Circle center point inside rectangle?
if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] &&
rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; }
// Otherwise, check that each corner is at least (r + Max(w, h)) away from circle center.
double r2 = circ[2] + Math.max(rect[2], rect[3]);
r2 = r2 * r2;
return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 &&
distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 &&
distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2;
}
private static boolean[] surelyOutside;
private static double totalArea(double[] rect, double[][] circs, int d) {
// Check if we can get a quick certain answer.
int surelyOutsideCount = 0;
for(int i = 0; i < circs.length; i++) {
if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; }
if(rectangleSurelyOutsideCircle(rect, circs[i])) {
surelyOutside[i] = true;
surelyOutsideCount++;
}
else { surelyOutside[i] = false; }
}
// Is this rectangle surely outside all circles?
if(surelyOutsideCount == circs.length) { return 0; }
// Are we deep enough in the recursion?
if(d < 1) {
return rect[2] * rect[3] / 3; // Best guess for overlapping portion
}
// Throw out all circles that are surely outside this rectangle.
if(surelyOutsideCount > 0) {
double[][] newCircs = new double[circs.length - surelyOutsideCount][3];
int loc = 0;
for(int i = 0; i < circs.length; i++) {
if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; }
}
circs = newCircs;
}
// Subdivide this rectangle recursively and add up the recursively computed areas.
double w = rect[2] / 2; // New width
double h = rect[3] / 2; // New height
double[][] pieces = {
{ rect[0], rect[1], w, h }, // NW
{ rect[0] + w, rect[1], w, h }, // NE
{ rect[0], rect[1] - h, w, h }, // SW
{ rect[0] + w, rect[1] - h, w, h } // SE
};
double total = 0;
for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); }
return total;
}
public static double totalArea(double[][] circs, int d) {
double maxx = Double.NEGATIVE_INFINITY;
double minx = Double.POSITIVE_INFINITY;
double maxy = Double.NEGATIVE_INFINITY;
double miny = Double.POSITIVE_INFINITY;
// Find the extremes of x and y for this set of circles.
for(double[] circ: circs) {
if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; }
if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; }
if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; }
if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; }
}
double[] rect = { minx, maxy, maxx - minx, maxy - miny };
surelyOutside = new boolean[circs.length];
return totalArea(rect, circs, d);
}
public static void main(String[] args) {
double[][] circs = {
{ 1.6417233788, 1.6121789534, 0.0848270516 },
{-1.4944608174, 1.2077959613, 1.1039549836 },
{ 0.6110294452, -0.6907087527, 0.9089162485 },
{ 0.3844862411, 0.2923344616, 0.2375743054 },
{-0.2495892950, -0.3832854473, 1.0845181219 },
{1.7813504266, 1.6178237031, 0.8162655711 },
{-0.1985249206, -0.8343333301, 0.0538864941 },
{-1.7011985145, -0.1263820964, 0.4776976918 },
{-0.4319462812, 1.4104420482, 0.7886291537 },
{0.2178372997, -0.9499557344, 0.0357871187 },
{-0.6294854565, -1.3078893852, 0.7653357688 },
{1.7952608455, 0.6281269104, 0.2727652452 },
{1.4168575317, 1.0683357171, 1.1016025378 },
{1.4637371396, 0.9463877418, 1.1846214562 },
{-0.5263668798, 1.7315156631, 1.4428514068 },
{-1.2197352481, 0.9144146579, 1.0727263474 },
{-0.1389358881, 0.1092805780, 0.7350208828 },
{1.5293954595, 0.0030278255, 1.2472867347 },
{-0.5258728625, 1.3782633069, 1.3495508831 },
{-0.1403562064, 0.2437382535, 1.3804956588 },
{0.8055826339, -0.0482092025, 0.3327165165 },
{-0.6311979224, 0.7184578971, 0.2491045282 },
{1.4685857879, -0.8347049536, 1.3670667538 },
{-0.6855727502, 1.6465021616, 1.0593087096 },
{0.0152957411, 0.0638919221, 0.9771215985 }
};
double ans = totalArea(circs, 24);
System.out.println("Approx. area is " + ans);
System.out.println("Error is " + Math.abs(21.56503660 - ans));
}
} |
Trabb Pardo–Knuth algorithm | Java | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
'''ask''' for 11 numbers to be read into a sequence ''S''
'''reverse''' sequence ''S''
'''for each''' ''item'' '''in''' sequence ''S''
''result'' ''':=''' '''call''' a function to do an ''operation''
'''if''' ''result'' overflows
'''alert''' user
'''else'''
'''print''' ''result''
The task is to implement the algorithm:
# Use the function: f(x) = |x|^{0.5} + 5x^3
# The overflow condition is an answer of greater than 400.
# The 'user alert' should not stop processing of other items of the sequence.
# Print a prompt before accepting '''eleven''', textual, numeric inputs.
# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.
# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| /**
* Alexander Alvonellos
*/
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try {
userInput = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.println("You entered invalid input, exiting");
System.exit(1);
}
input[i] = userInput;
}
for(int j = 10; j >= 0; j--) {
double x = input[j]; double y = f(x);
if( y < 400.0) {
System.out.printf("f( %.2f ) = %.2f\n", x, y);
} else {
System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
}
|
Tree from nesting levels | Java | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
* Every int appears, in order, at its depth of nesting.
* If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item
The generated tree data structure should ideally be in a languages nested list format that can
be used for further calculations rather than something just calculated for printing.
An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]]
where 1 is at depth1, 2 is two deep and 4 is nested 4 deep.
[1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1].
All the nesting integers are in the same order but at the correct nesting
levels.
Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1]
;Task:
Generate and show here the results for the following inputs:
:* []
:* [1, 2, 4]
:* [3, 1, 3, 1]
:* [1, 2, 3, 1]
:* [3, 2, 1, 3]
:* [3, 3, 3, 1, 1, 3, 3, 3]
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class TreeNestingLevels {
public static void main(String[] args) {
List<List<Integer>> lists = List.of(
Arrays.asList(),
Arrays.asList( 1, 2, 4 ),
Arrays.asList( 3, 1, 3, 1 ),
Arrays.asList( 1, 2, 3, 1 ),
Arrays.asList( 3, 2, 1, 3 ),
Arrays.asList( 3, 3, 3, 1, 1, 3, 3, 3 )
);
for ( List<Integer> list : lists ) {
List<Object> tree = createTree(list);
System.out.println(list + " --> " + tree);
}
}
private static List<Object> createTree(List<Integer> list) {
return makeTree(list, 0, 1);
}
private static List<Object> makeTree(List<Integer> list, int index, int depth) {
List<Object> tree = new ArrayList<Object>();
int current;
while ( index < list.size() && depth <= ( current = list.get(index) ) ) {
if ( depth == current ) {
tree.add(current);
index += 1;
} else {
tree.add(makeTree(list, index, depth + 1));
final int position = list.subList(index, list.size()).indexOf(depth);
index += ( position == -1 ) ? list.size() : position;
}
}
return tree;
}
}
|
Tropical algebra overloading | Java | In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring
(R -Inf, , ) containing the ring of real numbers R augmented by negative infinity,
the max function (returns the greater of two real numbers), and addition.
In max tropical algebra, x y = max(x, y) and x y = x + y. The identity for
is -Inf (the max of any number with -infinity is that number), and the identity for is 0.
;Task:
* Define functions or, if the language supports the symbols as operators, operators for and that fit the above description. If the language does not support and as operators but allows overloading operators for a new object type, you may instead overload + and * for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose.
Show that 2 -2 is 0, -0.001 -Inf is -0.001, 0 -Inf is -Inf, 1.5 -1 is 1.5, and -0.5 0 is -0.5.
* Define exponentiation as serial , and in general that a to the power of b is a * b, where a is a real number and b must be a positive integer. Use either | or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such "exponentiation" in the language being used. Calculate 5 | 7 using this definition.
* Max tropical algebra is distributive, so that
a (b c) equals a b b c,
where has precedence over . Demonstrate that 5 (8 7) equals 5 8 5 7.
* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).
;See also
:;*[Tropical algebra]
:;*[Tropical geometry review article]
:;*[Operator overloading]
| import java.util.Optional;
public final class TropicalAlgebra {
public static void main(String[] aArgs) {
final Tropical a = new Tropical(-2);
final Tropical b = new Tropical(-1);
final Tropical c = new Tropical(-0.5);
final Tropical d = new Tropical(-0.001);
final Tropical e = new Tropical(0);
final Tropical f = new Tropical(1.5);
final Tropical g = new Tropical(2);
final Tropical h = new Tropical(5);
final Tropical i = new Tropical(7);
final Tropical j = new Tropical(8);
final Tropical k = new Tropical();
System.out.println("2 x -2 = " + g.multiply(a));
System.out.println("-0.001 + -Inf = " + d.add(k));
System.out.println("0 x -Inf = " + e.multiply(k));
System.out.println("1.5 + -1 = " + f.add(b));
System.out.println("-0.5 x 0 = " + c.multiply(e));
System.out.println();
System.out.println("5^7 = " + h.power(7));
System.out.println();
System.out.println("5 * ( 8 + 7 ) = " + h.multiply(j.add(i)));
System.out.println("5 * 8 + 5 * 7 = " + h.multiply(j).add(h.multiply(i)));
}
}
final class Tropical {
public Tropical(Number aNumber) {
if ( aNumber == null ) {
throw new IllegalArgumentException("Number cannot be null");
}
optional = Optional.of(aNumber);
}
public Tropical() {
optional = Optional.empty();
}
@Override
public String toString() {
if ( optional.isEmpty() ) {
return "-Inf";
}
String value = String.valueOf(optional.get());
final int index = value.indexOf(".");
if ( index >= 0 ) {
value = value.substring(0, index);
}
return value;
}
public Tropical add(Tropical aOther) {
if ( aOther.optional.isEmpty() ) {
return this;
}
if ( optional.isEmpty() ) {
return aOther;
}
if ( optional.get().doubleValue() > aOther.optional.get().doubleValue() ) {
return this;
}
return aOther;
}
public Tropical multiply(Tropical aOther) {
if ( optional.isPresent() && aOther.optional.isPresent() ) {
double result = optional.get().doubleValue() + aOther.optional.get().doubleValue();
return new Tropical(result);
}
return new Tropical();
}
public Tropical power(int aExponent) {
if ( aExponent <= 0 ) {
throw new IllegalArgumentException("Power must be positive");
}
Tropical result = this;;
for ( int i = 1; i < aExponent; i++ ) {
result = result.multiply(this);
}
return result;
}
private Optional<Number> optional;
}
|
Truncate a file | Java | Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
//turn on "append" so it doesn't clear the file
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
long newSize = Long.parseLong(args[1]);
outChan.truncate(newSize);
outChan.close();
}
} |
Truth table | Java 1.8+ | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
;Task:
# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).
# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
# Either reverse-polish or infix notation expressions are allowed.
;Related tasks:
* [[Boolean values]]
* [[Ternary logic]]
;See also:
* Wolfram MathWorld entry on truth tables.
* some "truth table" examples from Google.
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class TruthTable {
public static void main( final String... args ) {
System.out.println( new TruthTable( args ) );
}
private interface Operator {
boolean evaluate( Stack<Boolean> s );
}
/**
* Supported operators and what they do. For more ops, add entries here.
*/
private static final Map<String,Operator> operators = new HashMap<String,Operator>() {{
// Can't use && or || because shortcut evaluation may mean the stack is not popped enough
put( "&", stack -> Boolean.logicalAnd( stack.pop(), stack.pop() ) );
put( "|", stack -> Boolean.logicalOr( stack.pop(), stack.pop() ) );
put( "!", stack -> ! stack.pop() );
put( "^", stack -> ! stack.pop().equals ( stack.pop() ) );
}};
private final List<String> variables;
private final String[] symbols;
/**
* Constructs a truth table for the symbols in an expression.
*/
public TruthTable( final String... symbols ) {
final Set<String> variables = new LinkedHashSet<>();
for ( final String symbol : symbols ) {
if ( ! operators.containsKey( symbol ) ) {
variables.add( symbol );
}
}
this.variables = new ArrayList<>( variables );
this.symbols = symbols;
}
@Override
public String toString () {
final StringBuilder result = new StringBuilder();
for ( final String variable : variables ) {
result.append( variable ).append( ' ' );
}
result.append( ' ' );
for ( final String symbol : symbols ) {
result.append( symbol ).append ( ' ' );
}
result.append( '\n' );
for ( final List<Boolean> values : enumerate( variables.size () ) ) {
final Iterator<String> i = variables.iterator();
for ( final Boolean value : values ) {
result.append(
String.format(
"%-" + i.next().length() + "c ",
value ? 'T' : 'F'
)
);
}
result.append( ' ' )
.append( evaluate( values ) ? 'T' : 'F' )
.append( '\n' );
}
return result.toString ();
}
/**
* Recursively generates T/F values
*/
private static List<List<Boolean>> enumerate( final int size ) {
if ( 1 == size )
return new ArrayList<List<Boolean>>() {{
add( new ArrayList<Boolean>() {{ add(false); }} );
add( new ArrayList<Boolean>() {{ add(true); }} );
}};
return new ArrayList<List<Boolean>>() {{
for ( final List<Boolean> head : enumerate( size - 1 ) ) {
add( new ArrayList<Boolean>( head ) {{ add(false); }} );
add( new ArrayList<Boolean>( head ) {{ add(true); }} );
}
}};
}
/**
* Evaluates the expression for a set of values.
*/
private boolean evaluate( final List<Boolean> enumeration ) {
final Iterator<Boolean> i = enumeration.iterator();
final Map<String,Boolean> values = new HashMap<>();
final Stack<Boolean> stack = new Stack<>();
variables.forEach ( v -> values.put( v, i.next() ) );
for ( final String symbol : symbols ) {
final Operator op = operators.get ( symbol );
// Reverse Polish notation makes this bit easy
stack.push(
null == op
? values.get ( symbol )
: op.evaluate ( stack )
);
}
return stack.pop();
}
} |
Two bullet roulette | Java | The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:
A revolver handgun has a revolving cylinder with six chambers for bullets.
It is loaded with the following procedure:
1. Check the first chamber to the right of the trigger for a bullet. If a bullet
is seen, the cylinder is rotated one chamber clockwise and the next chamber
checked until an empty chamber is found.
2. A cartridge containing a bullet is placed in the empty chamber.
3. The cylinder is then rotated one chamber clockwise.
To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take
a random position from 1 to 6 chamber rotations clockwise from its starting position.
When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just
counterclockwise from the loading position.
The gun is unloaded by removing all cartridges from the cylinder.
According to the legend, a suicidal Russian imperial military officer plays a game of Russian
roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.
If the gun fires with a trigger pull, this is considered a successful suicide.
The cylinder is always spun before the first shot, but it may or may not be spun after putting
in the first bullet and may or may not be spun after taking the first shot.
Which of the following situations produces the highest probability of suicide?
A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.
B. Spinning the cylinder after loading the first bullet only.
C. Spinning the cylinder after firing the first shot only.
D. Not spinning the cylinder either after loading the first bullet or after the first shot.
E. The probability is the same for all cases.
;Task:
# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.
# Show the results as a percentage of deaths for each type of scenario.
# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.
;Reference:
Youtube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]
| import java.util.BitSet;
import java.util.concurrent.ThreadLocalRandom;
public class TwoBulletRoulette {
public static void main(String[] aArgs) {
Revolver handgun = new Revolver();
final int simulationCount = 100_000;
for ( Situation situation : Situation.values() ) {
double deaths = 0.0;
for ( int i = 0; i < simulationCount; i++ ) {
ResultState resultState = handgun.operateInMode(situation);
if ( resultState == ResultState.DEAD) {
deaths += 1.0;
}
}
final double deathRate = ( deaths / simulationCount ) * 100;
String percentage = String.format("%4.1f%%", deathRate);
System.out.println("Situation " + situation + " produces " + percentage + " deaths");
}
}
}
enum Situation { A, B, C, D }
enum ResultState { ALIVE, DEAD }
/**
* Representation of a six cylinder revolving chamber pistol.
*/
class Revolver {
public Revolver() {
chambers = new BitSet(chamberCount);
random = ThreadLocalRandom.current();
}
public ResultState operateInMode(Situation aSituation) {
return switch ( aSituation ) {
case A -> useSituationA();
case B -> useSituationB();
case C -> useSituationC();
case D -> useSituationD();
};
}
// PRIVATE //
private void unload() {
chambers.clear();
}
private void load() {
while ( chambers.get(loadingChamber) ) {
rotateClockwise();
}
chambers.set(loadingChamber);
rotateClockwise();
}
private void spin() {
final int spins = random.nextInt(0, chamberCount);
for ( int i = 0; i < spins; i++ ) {
rotateClockwise();
}
}
private boolean fire() {
boolean fire = chambers.get(firingChamber);
chambers.set(firingChamber, false);
rotateClockwise();
return fire;
}
private void rotateClockwise() {
final boolean temp = chambers.get(chamberCount - 1);
for ( int i = chamberCount - 2; i >= 0; i-- ) {
chambers.set(i + 1, chambers.get(i));
}
chambers.set(firingChamber, temp);
}
private ResultState useSituationA() {
unload();
load();
spin();
load();
spin();
if ( fire() ) {
return ResultState.DEAD;
};
spin();
if ( fire() ) {
return ResultState.DEAD;
};
return ResultState.ALIVE;
}
private ResultState useSituationB() {
unload();
load();
spin();
load();
spin();
if ( fire() ) {
return ResultState.DEAD;
};
if ( fire() ) {
return ResultState.DEAD;
};
return ResultState.ALIVE;
}
private ResultState useSituationC() {
unload();
load();
load();
spin();
if ( fire() ) {
return ResultState.DEAD;
};
spin();
if ( fire() ) {
return ResultState.DEAD;
};
return ResultState.ALIVE;
}
private ResultState useSituationD() {
unload();
load();
load();
spin();
if ( fire() ) {
return ResultState.DEAD;
};
if ( fire() ) {
return ResultState.DEAD;
};
return ResultState.ALIVE;
}
private BitSet chambers;
private ThreadLocalRandom random;
private final int firingChamber = 0;
private final int loadingChamber = 1;
private final int chamberCount = 6;
}
|
UPC | Java from Kotlin | Goal:
Convert UPC bar codes to decimal.
Specifically:
The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards...
Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).
;Sample input:
Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:
# # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # #
# # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # #
# # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # #
# # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # #
# # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # #
# # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # #
# # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # #
# # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # #
# # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # #
# # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # #
Some of these were entered upside down, and one entry has a timing error.
;Task:
Implement code to find the corresponding decimal representation of each, rejecting the error.
Extra credit for handling the rows entered upside down (the other option is to reject them).
;Notes:
Each digit is represented by 7 bits:
0: 0 0 0 1 1 0 1
1: 0 0 1 1 0 0 1
2: 0 0 1 0 0 1 1
3: 0 1 1 1 1 0 1
4: 0 1 0 0 0 1 1
5: 0 1 1 0 0 0 1
6: 0 1 0 1 1 1 1
7: 0 1 1 1 0 1 1
8: 0 1 1 0 1 1 1
9: 0 0 0 1 0 1 1
On the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''.
On the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1'''
Alternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.
;The UPC-A bar code structure:
::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly),
::* then has a ''' # # ''' sequence marking the start of the sequence,
::* then has the six "left hand" digits,
::* then has a ''' # # ''' sequence in the middle,
::* then has the six "right hand digits",
::* then has another ''' # # ''' (end sequence), and finally,
::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).
Finally, the last digit is a checksum digit which may be used to help detect errors.
;Verification:
Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.
The sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
} |
URL decoding | Java | This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
;Test cases:
* The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
* The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Baha".
* The encoded string "%25%32%35" should revert to the unencoded form "%25" and '''not''' "%".
| String decode(String string) {
Pattern pattern = Pattern.compile("%([A-Za-z\\d]{2})");
Matcher matcher = pattern.matcher(string);
StringBuilder decoded = new StringBuilder(string);
char character;
int start, end, offset = 0;
while (matcher.find()) {
character = (char) Integer.parseInt(matcher.group(1), 16);
/* offset the matched index since were adjusting the string */
start = matcher.start() - offset;
end = matcher.end() - offset;
decoded.replace(start, end, String.valueOf(character));
offset += 2;
}
return decoded.toString();
}
|
URL encoding | Java | Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
* Extended characters with character codes of 128 decimal (80 hex) and above.
;Example:
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
;Variations:
* Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
* Special characters have different encodings for different standards:
** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~".
** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+".
** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#".
;Options:
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
;Related tasks:
* [[URL decoding]]
* [[URL parser]]
| String encode(String string) {
StringBuilder encoded = new StringBuilder();
for (char character : string.toCharArray()) {
switch (character) {
/* rfc3986 and html5 */
case '-', '.', '_', '~', '*' -> encoded.append(character);
case ' ' -> encoded.append('+');
default -> {
if (alphanumeric(character))
encoded.append(character);
else {
encoded.append("%");
encoded.append("%02x".formatted((int) character));
}
}
}
}
return encoded.toString();
}
boolean alphanumeric(char character) {
return (character >= 'A' && character <= 'Z')
|| (character >= 'a' && character <= 'z')
|| (character >= '0' && character <= '9');
}
|
URL parser | Java | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
;Task:
Parse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...
Note: this task has nothing to do with [[URL encoding]] or [[URL decoding]].
According to the standards, the characters:
:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded ('''%''') in case of possible confusion.
Also note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
* Here is the official standard: https://tools.ietf.org/html/rfc3986,
* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
;Test cases:
According to T. Berners-Lee
'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:
::* scheme = foo
::* domain = example.com
::* port = :8042
::* path = over/there
::* query = name=ferret
::* fragment = nose
'''urn:example:animal:ferret:nose''' should parse into:
::* scheme = urn
::* path = example:animal:ferret:nose
'''other URLs that must be parsed include:'''
:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
:* ftp://ftp.is.co.za/rfc/rfc1808.txt
:* http://www.ietf.org/rfc/rfc2396.txt#header1
:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
:* mailto:[email protected]
:* news:comp.infosystems.www.servers.unix
:* tel:+1-816-555-1212
:* telnet://192.0.2.16:80/
:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class MailTo {
private final To to;
private List<Field> fields;
public MailTo(String string) {
if (string == null)
throw new NullPointerException();
if (string.isBlank() || !string.toLowerCase().startsWith("mailto:"))
throw new IllegalArgumentException("Requires 'mailto' scheme");
string = string.substring(string.indexOf(':') + 1);
/* we can use the 'URLDecoder' class to decode any entities */
string = URLDecoder.decode(string, StandardCharsets.UTF_8);
/* the address and fields are separated by a '?' */
int indexOf = string.indexOf('?');
String[] address;
if (indexOf == -1)
address = string.split("@");
else {
address = string.substring(0, indexOf).split("@");
string = string.substring(indexOf + 1);
/* each field is separated by a '&' */
String[] fields = string.split("&");
String[] field;
this.fields = new ArrayList<>(fields.length);
for (String value : fields) {
field = value.split("=");
this.fields.add(new Field(field[0], field[1]));
}
}
to = new To(address[0], address[1]);
}
record To(String user, String host) { }
record Field(String name, String value) { }
}
|
UTF-8 encode and decode | Java 7+ | As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
o LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Zh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
EUR EURO SIGN U+20AC E2 82 AC
MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s %-43s %7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
} |
Ultra useful primes | Java | An '''ultra-useful prime''' is a member of the sequence where each '''a(n)''' is the smallest positive integer '''k''' such that '''2(2n) - k''' is prime.
'''''k''' must always be an odd number since 2 to any power is always even.''
;Task
* Find and show here, on this page, the first '''10''' elements of the sequence.
;Stretch
* Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)
;See also
* OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
| import java.math.BigInteger;
public final class UltraUsefulPrimes {
public static void main(String[] args) {
for ( int n = 1; n <= 10; n++ ) {
showUltraUsefulPrime(n);
}
}
private static void showUltraUsefulPrime(int n) {
BigInteger prime = BigInteger.ONE.shiftLeft(1 << n);
BigInteger k = BigInteger.ONE;
while ( ! prime.subtract(k).isProbablePrime(20) ) {
k = k.add(BigInteger.TWO);
}
System.out.print(k + " ");
}
}
|
Unbias a random generator | Java | Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.
;Task details:
* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| public class Bias {
public static boolean biased(int n) {
return Math.random() < 1.0 / n;
}
public static boolean unbiased(int n) {
boolean a, b;
do {
a = biased(n);
b = biased(n);
} while (a == b);
return a;
}
public static void main(String[] args) {
final int M = 50000;
for (int n = 3; n < 7; n++) {
int c1 = 0, c2 = 0;
for (int i = 0; i < M; i++) {
c1 += biased(n) ? 1 : 0;
c2 += unbiased(n) ? 1 : 0;
}
System.out.format("%d: %2.2f%% %2.2f%%\n",
n, 100.0*c1/M, 100.0*c2/M);
}
}
} |
Unicode strings | Java | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
;Task:
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
:* How easy is it to present Unicode strings in source code?
:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
:* How well can the language communicate with the rest of the world?
:* Is it good at input/output with Unicode?
:* Is it convenient to manipulate Unicode strings in the language?
:* How broad/deep does the language support Unicode?
:* What encodings (e.g. UTF-8, UTF-16, etc) can be used?
:* Does it support normalization?
;Note:
This task is a bit unusual in that it encourages general discussion rather than clever coding.
;See also:
* [[Unicode variable names]]
* [[Terminal control/Display an extended character]]
| How easy is it to present Unicode strings in source code?
Very easy. It is not specified what encoding the source code must be in, as long as it can be interpreted into a stream of UTF-16 characters. Most compilers probably take UTF-8.
In any case, even using only ASCII characters, any UTF-16 character can be embedded into the source code by using a Unicode escape <code>\uxxxx</code> (where ''xxxx'' is the hex code of the character), which is processed before any other steps by the compiler. This means that it is possible to write an entire program out of Unicode escapes. This also means that a Unicode escape could mess up the language syntax, if it happens to be the escape of a whitespace or quote character (please don't do that).
Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
UTF-16 characters can be written directly in character and string literals and comments (there is no difference between "directly" and using Unicode escapes, since they are processed at the first step). UTF-16 characters can be part of identifiers (either directly or through a Unicode escape).
How well can the language communicate with the rest of the world? Is it good at input/output with Unicode?
Yes
Is it convenient to manipulate Unicode strings in the language?
The <code>String</code> class in Java is basically a sequence of <code>char</code> elements, representing the string encoded in UTF-16. <code>char</code> is a 16-bit type, and thus one <code>char</code> does not necessarily correspond to one Unicode character, since supplementary characters can have code points greater than U+FFFF. However, if your string only consists of characters from the Basic Multilingual Plane (which is most of the time), then one <code>char</code> does correspond to one Unicode character.
Starting in J2SE 5 (1.5), Java has fairly convenient methods for dealing with true Unicode characters, even supplementary ones. Many methods that deal with characters have versions for both <code>char</code> and <code>int</code>. For example, <code>String</code> has the <code>codePointAt</code> method, analogous to the <code>charAt</code> method.
How broad/deep does the language support Unicode? What encodings (e.g. UTF-8, UTF-16, etc) can be used? Normalization?
|
Universal Turing machine | Java 5+ | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936-1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
;Task:
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
'''Simple incrementer'''
* '''States:''' q0, qf
* '''Initial state:''' q0
* '''Terminating states:''' qf
* '''Permissible symbols:''' B, 1
* '''Blank symbol:''' B
* '''Rules:'''
** (q0, 1, 1, right, q0)
** (q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
'''Three-state busy beaver'''
* '''States:''' a, b, c, halt
* '''Initial state:''' a
* '''Terminating states:''' halt
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (a, 0, 1, right, b)
** (a, 1, 1, left, c)
** (b, 0, 1, left, a)
** (b, 1, 1, right, b)
** (c, 0, 1, left, b)
** (c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
'''Bonus:'''
'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''
* '''States:''' A, B, C, D, E, H
* '''Initial state:''' A
* '''Terminating states:''' H
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (A, 0, 1, right, B)
** (A, 1, 1, left, C)
** (B, 0, 1, right, C)
** (B, 1, 1, right, B)
** (C, 0, 1, right, D)
** (C, 1, 0, left, E)
** (D, 0, 1, left, A)
** (D, 1, 1, left, D)
** (E, 0, 1, stay, H)
** (E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
// These methods can be auto-generated by Eclipse.
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
// These methods can be auto-generated by Eclipse.
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction; // -1 left, 0 neutral, 1 right.
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) { // Arbitrary Strings as symbols.
tape = input;
}
public void initializeTape(String input) { // Uses single characters as symbols.
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() { // Returns null if not in terminal state.
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) { // While a matching transition exists.
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol); // Write tape symbol.
tsp.state = trans.to.state; // Change state.
if (trans.direction == -1) { // Go left.
if (!head.hasPrevious()) {
head.add(blankSymbol); // Extend tape.
}
tsp.tapeSymbol = head.previous(); // Memorize tape symbol.
} else if (trans.direction == 1) { // Go right.
head.next();
if (!head.hasNext()) {
head.add(blankSymbol); // Extend tape.
head.previous();
}
tsp.tapeSymbol = head.next(); // Memorize tape symbol.
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
// Simple incrementer.
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
// Busy Beaver (overwrite variables from above).
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
// Change state from "a" to "b" if "0" is read on tape, write "1" and go to the right. (-1 left, 0 nothing, 1 right.)
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
// Sorting test (overwrite variables from above).
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
} |
Unix/ls | Java | Write a program that will list everything in the current folder, similar to:
:::* the Unix utility "ls" [http://man7.org/linux/man-pages/man1/ls.1.html] or
:::* the Windows terminal command "DIR"
The output must be sorted, but printing extended details and producing multi-column output is not required.
;Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| import java.io.File;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
public class Ls {
public static void main(String[] args) throws Exception {
Ls ls = new Ls("/");
System.out.println(ls);
}
private final File directory;
private final List<File> list;
public Ls(String path) throws Exception {
directory = new File(path);
if (!directory.exists())
throw new Exception("Path not found '%s'".formatted(directory));
if (!directory.isDirectory())
throw new Exception("Not a directory '%s'".formatted(directory));
list = new ArrayList<>(List.of(directory.listFiles()));
/* place the directories first */
list.sort((fileA, fileB) -> {
if (fileA.isDirectory() && fileB.isFile()) {
return -1;
} else if (fileA.isFile() && fileB.isDirectory()) {
return 1;
}
return 0;
});
}
private String size(long bytes) {
if (bytes > 1E9) {
return "%.1fG".formatted(bytes / 1E9d);
} else if (bytes > 1E6) {
return "%.1fM".formatted(bytes / 1E6d);
} else if (bytes > 1E3) {
return "%.1fK".formatted(bytes / 1E3d);
} else {
return "%d".formatted(bytes);
}
}
@Override
public String toString() {
StringBuilder string = new StringBuilder();
Formatter formatter = new Formatter(string);
/* add parent and current directory listings */
list.add(0, directory.getParentFile());
list.add(0, directory);
/* generate total used space value */
long total = 0;
for (File file : list) {
if (file == null) continue;
total += file.length();
}
formatter.format("total %s%n", size(total));
/* generate output for each entry */
int index = 0;
for (File file : list) {
if (file == null) continue;
/* generate permission columns */
formatter.format(file.isDirectory() ? "d" : "-");
formatter.format(file.canRead() ? "r" : "-");
formatter.format(file.canWrite() ? "w" : "-");
formatter.format(file.canExecute() ? "x" : "-");
/* include size */
formatter.format("%7s ", size(file.length()));
/* modification timestamp */
formatter.format("%tb %1$td %1$tR ", file.lastModified());
/* file or directory name */
switch (index) {
case 0 -> formatter.format(".");
case 1 -> formatter.format("..");
default -> formatter.format("%s", file.getName());
}
if (file.isDirectory())
formatter.format(File.separator);
formatter.format("%n");
index++;
}
formatter.flush();
return string.toString();
}
}
|
Unix/ls | Java 11 | Write a program that will list everything in the current folder, similar to:
:::* the Unix utility "ls" [http://man7.org/linux/man-pages/man1/ls.1.html] or
:::* the Windows terminal command "DIR"
The output must be sorted, but printing extended details and producing multi-column output is not required.
;Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| package rosetta;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnixLS {
public static void main(String[] args) throws IOException {
Files.list(Path.of("")).sorted().forEach(System.out::println);
}
}
|
Validate International Securities Identification Number | Java | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
;Task:
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, ''and'' the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
;Details:
The format of an ISIN is as follows:
+------------- a 2-character ISO country code (A-Z)
| +----------- a 9-character security code (A-Z, 0-9)
| | +-- a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.
# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)
;Test cases:
:::: {| class="wikitable"
! ISIN
! Validity
! Comment
|-
| US0378331005 || valid ||
|-
| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.
|-
| U50378331005 || not valid || The substitution typo is caught by the format constraint.
|-
| US03378331005 || not valid || The duplication typo is caught by the format constraint.
|-
| AU0000XVGZA3 || valid ||
|-
| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.
|-
| FR0000988040 || valid ||
|}
(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)
Related task:
* [[Luhn test of credit card numbers]]
;Also see:
* Interactive online ISIN validator
* Wikipedia article: International Securities Identification Number
| public class ISIN {
public static void main(String[] args) {
String[] isins = {
"US0378331005",
"US0373831005",
"U50378331005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040"
};
for (String isin : isins)
System.out.printf("%s is %s\n", isin, ISINtest(isin) ? "valid" : "not valid");
}
static boolean ISINtest(String isin) {
isin = isin.trim().toUpperCase();
if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
return false;
StringBuilder sb = new StringBuilder();
for (char c : isin.substring(0, 12).toCharArray())
sb.append(Character.digit(c, 36));
return luhnTest(sb.toString());
}
static boolean luhnTest(String number) {
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for (int i = 0; i < reverse.length(); i++){
int digit = Character.digit(reverse.charAt(i), 10);
//This is for odd digits, they are 1-indexed in the algorithm.
if (i % 2 == 0){
s1 += digit;
} else { // Add 2 * digit for 0-4, add 2 * digit - 9 for 5-9.
s2 += 2 * digit;
if(digit >= 5){
s2 -= 9;
}
}
}
return (s1 + s2) % 10 == 0;
}
} |
Van Eck sequence | Java | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
;Example:
Using A:
:0
Using B:
:0 0
Using C:
:0 0 1
Using B:
:0 0 1 0
Using C: (zero last occurred two steps back - before the one)
:0 0 1 0 2
Using B:
:0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
:0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
:0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
:0 0 1 0 2 0 2 2 1 6
...
;Task:
# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
# Use it to display here, on this page:
:# The first ten terms of the sequence.
:# Terms 991 - to - 1000 of the sequence.
;References:
* Don't Know (the Van Eck Sequence) - Numberphile video.
* Wikipedia Article: Van Eck's Sequence.
* OEIS sequence: A181391.
| import java.util.HashMap;
import java.util.Map;
public class VanEckSequence {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
System.out.println("");
System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] = %d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] = %d%n", n, vanEck);
}
}
}
}
|
Van der Corput sequence | Java from Raku | When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is 1 \times 2^1 + 0 \times 2^0.
You can also have binary digits to the right of the "point", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2.
The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.
If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4.
Monte Carlo simulations.
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
'''Hint'''
A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0.
Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4}
;Task description:
* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.
* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).
* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
;See also:
* The Basic Low Discrepancy Sequences
* [[Non-decimal radices/Convert]]
* Van der Corput sequence
| public class VanDerCorput{
public static double vdc(int n){
double vdc = 0;
int denom = 1;
while(n != 0){
vdc += n % 2.0 / (denom *= 2);
n /= 2;
}
return vdc;
}
public static void main(String[] args){
for(int i = 0; i <= 10; i++){
System.out.println(vdc(i));
}
}
} |
Variable declaration reset | Java | A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.
Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say)
// int prev // crashes with unassigned variable
int prev = -1 // predictably no output
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
| public class VariableDeclarationReset {
public static void main(String[] args) {
int[] s = {1, 2, 2, 3, 4, 4, 5};
// There is no output as 'prev' is created anew each time
// around the loop and set to zero.
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
int prev = 0;
// int prev; // triggers "error: variable prev might not have been initialized"
if (i > 0 && curr == prev) System.out.println(i);
prev = curr;
}
int gprev = 0;
// Now 'gprev' is used and reassigned
// each time around the loop producing the desired output.
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) System.out.println(i);
gprev = curr;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.