title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Compare a list of strings | Java 8 | Given a list of arbitrarily many strings, show how to:
* test if they are all lexically '''equal'''
* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is ''no'' need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
| import java.util.Arrays;
public class CompareListOfStrings {
public static void main(String[] args) {
String[][] arr = {{"AA", "AA", "AA", "AA"}, {"AA", "ACB", "BB", "CC"}};
for (String[] a : arr) {
System.out.println(Arrays.toString(a));
System.out.println(Arrays.stream(a).distinct().count() < 2);
System.out.println(Arrays.equals(Arrays.stream(a).distinct().sorted().toArray(), a));
}
}
} |
Compiler/AST interpreter | Java | The C and Python versions can be considered reference implementations.
;Related Tasks
* Lexical Analyzer task
* Syntax Analyzer task
* Code Generator task
* Virtual Machine Interpreter task
__TOC__
| import java.util.Scanner;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Interpreter {
static Map<String, Integer> globals = new HashMap<>();
static Scanner s;
static List<Node> list = new ArrayList<>();
static Map<String, NodeType> str_to_nodes = new HashMap<>();
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"),
nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"),
nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
}
static String str(String s) {
String result = "";
int i = 0;
s = s.replace("\"", "");
while (i < s.length()) {
if (s.charAt(i) == '\\' && i + 1 < s.length()) {
if (s.charAt(i + 1) == 'n') {
result += '\n';
i += 2;
} else if (s.charAt(i) == '\\') {
result += '\\';
i += 2;
}
} else {
result += s.charAt(i);
i++;
}
}
return result;
}
static boolean itob(int i) {
return i != 0;
}
static int btoi(boolean b) {
return b ? 1 : 0;
}
static int fetch_var(String name) {
int result;
if (globals.containsKey(name)) {
result = globals.get(name);
} else {
globals.put(name, 0);
result = 0;
}
return result;
}
static Integer interpret(Node n) throws Exception {
if (n == null) {
return 0;
}
switch (n.nt) {
case nd_Integer:
return Integer.parseInt(n.value);
case nd_Ident:
return fetch_var(n.value);
case nd_String:
return 1;//n.value;
case nd_Assign:
globals.put(n.left.value, interpret(n.right));
return 0;
case nd_Add:
return interpret(n.left) + interpret(n.right);
case nd_Sub:
return interpret(n.left) - interpret(n.right);
case nd_Mul:
return interpret(n.left) * interpret(n.right);
case nd_Div:
return interpret(n.left) / interpret(n.right);
case nd_Mod:
return interpret(n.left) % interpret(n.right);
case nd_Lss:
return btoi(interpret(n.left) < interpret(n.right));
case nd_Leq:
return btoi(interpret(n.left) <= interpret(n.right));
case nd_Gtr:
return btoi(interpret(n.left) > interpret(n.right));
case nd_Geq:
return btoi(interpret(n.left) >= interpret(n.right));
case nd_Eql:
return btoi(interpret(n.left) == interpret(n.right));
case nd_Neq:
return btoi(interpret(n.left) != interpret(n.right));
case nd_And:
return btoi(itob(interpret(n.left)) && itob(interpret(n.right)));
case nd_Or:
return btoi(itob(interpret(n.left)) || itob(interpret(n.right)));
case nd_Not:
if (interpret(n.left) == 0) {
return 1;
} else {
return 0;
}
case nd_Negate:
return -interpret(n.left);
case nd_If:
if (interpret(n.left) != 0) {
interpret(n.right.left);
} else {
interpret(n.right.right);
}
return 0;
case nd_While:
while (interpret(n.left) != 0) {
interpret(n.right);
}
return 0;
case nd_Prtc:
System.out.printf("%c", interpret(n.left));
return 0;
case nd_Prti:
System.out.printf("%d", interpret(n.left));
return 0;
case nd_Prts:
System.out.print(str(n.left.value));//interpret(n.left));
return 0;
case nd_Sequence:
interpret(n.left);
interpret(n.right);
return 0;
default:
throw new Exception("Error: '" + n.nt + "' found, expecting operator");
}
}
static Node load_ast() throws Exception {
String command, value;
String line;
Node left, right;
while (s.hasNext()) {
line = s.nextLine();
value = null;
if (line.length() > 16) {
command = line.substring(0, 15).trim();
value = line.substring(15).trim();
} else {
command = line.trim();
}
if (command.equals(";")) {
return null;
}
if (!str_to_nodes.containsKey(command)) {
throw new Exception("Command not found: '" + command + "'");
}
if (value != null) {
return Node.make_leaf(str_to_nodes.get(command), value);
}
left = load_ast(); right = load_ast();
return Node.make_node(str_to_nodes.get(command), left, right);
}
return null; // for the compiler, not needed
}
public static void main(String[] args) {
Node n;
str_to_nodes.put(";", NodeType.nd_None);
str_to_nodes.put("Sequence", NodeType.nd_Sequence);
str_to_nodes.put("Identifier", NodeType.nd_Ident);
str_to_nodes.put("String", NodeType.nd_String);
str_to_nodes.put("Integer", NodeType.nd_Integer);
str_to_nodes.put("If", NodeType.nd_If);
str_to_nodes.put("While", NodeType.nd_While);
str_to_nodes.put("Prtc", NodeType.nd_Prtc);
str_to_nodes.put("Prts", NodeType.nd_Prts);
str_to_nodes.put("Prti", NodeType.nd_Prti);
str_to_nodes.put("Assign", NodeType.nd_Assign);
str_to_nodes.put("Negate", NodeType.nd_Negate);
str_to_nodes.put("Not", NodeType.nd_Not);
str_to_nodes.put("Multiply", NodeType.nd_Mul);
str_to_nodes.put("Divide", NodeType.nd_Div);
str_to_nodes.put("Mod", NodeType.nd_Mod);
str_to_nodes.put("Add", NodeType.nd_Add);
str_to_nodes.put("Subtract", NodeType.nd_Sub);
str_to_nodes.put("Less", NodeType.nd_Lss);
str_to_nodes.put("LessEqual", NodeType.nd_Leq);
str_to_nodes.put("Greater", NodeType.nd_Gtr);
str_to_nodes.put("GreaterEqual", NodeType.nd_Geq);
str_to_nodes.put("Equal", NodeType.nd_Eql);
str_to_nodes.put("NotEqual", NodeType.nd_Neq);
str_to_nodes.put("And", NodeType.nd_And);
str_to_nodes.put("Or", NodeType.nd_Or);
if (args.length > 0) {
try {
s = new Scanner(new File(args[0]));
n = load_ast();
interpret(n);
} catch (Exception e) {
System.out.println("Ex: "+e.getMessage());
}
}
}
}
|
Compiler/code generator | Java from Python | The C and Python versions can be considered reference implementations.
;Related Tasks
* Lexical Analyzer task
* Syntax Analyzer task
* Virtual Machine Interpreter task
* AST Interpreter task
__TOC__
| package codegenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class CodeGenerator {
final static int WORDSIZE = 4;
static byte[] code = {};
static Map<String, NodeType> str_to_nodes = new HashMap<>();
static List<String> string_pool = new ArrayList<>();
static List<String> variables = new ArrayList<>();
static int string_count = 0;
static int var_count = 0;
static Scanner s;
static NodeType[] unary_ops = {
NodeType.nd_Negate, NodeType.nd_Not
};
static NodeType[] operators = {
NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub,
NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq,
NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or
};
static enum Mnemonic {
NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT,
JMP, JZ, PRTC, PRTS, PRTI, HALT
}
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE),
nd_If("If", Mnemonic.NONE),
nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE),
nd_Assign("Assign", Mnemonic.NONE),
nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD),
nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE),
nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ),
nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR);
private final String name;
private final Mnemonic m;
NodeType(String name, Mnemonic m) {
this.name = name;
this.m = m;
}
Mnemonic getMnemonic() { return this.m; }
@Override
public String toString() { return this.name; }
}
static void appendToCode(int b) {
code = Arrays.copyOf(code, code.length + 1);
code[code.length - 1] = (byte) b;
}
static void emit_byte(Mnemonic m) {
appendToCode(m.ordinal());
}
static void emit_word(int n) {
appendToCode(n >> 24);
appendToCode(n >> 16);
appendToCode(n >> 8);
appendToCode(n);
}
static void emit_word_at(int pos, int n) {
code[pos] = (byte) (n >> 24);
code[pos + 1] = (byte) (n >> 16);
code[pos + 2] = (byte) (n >> 8);
code[pos + 3] = (byte) n;
}
static int get_word(int pos) {
int result;
result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ;
return result;
}
static int fetch_var_offset(String name) {
int n;
n = variables.indexOf(name);
if (n == -1) {
variables.add(name);
n = var_count++;
}
return n;
}
static int fetch_string_offset(String str) {
int n;
n = string_pool.indexOf(str);
if (n == -1) {
string_pool.add(str);
n = string_count++;
}
return n;
}
static int hole() {
int t = code.length;
emit_word(0);
return t;
}
static boolean arrayContains(NodeType[] a, NodeType n) {
boolean result = false;
for (NodeType test: a) {
if (test.equals(n)) {
result = true;
break;
}
}
return result;
}
static void code_gen(Node x) throws Exception {
int n, p1, p2;
if (x == null) return;
switch (x.nt) {
case nd_None: return;
case nd_Ident:
emit_byte(Mnemonic.FETCH);
n = fetch_var_offset(x.value);
emit_word(n);
break;
case nd_Integer:
emit_byte(Mnemonic.PUSH);
emit_word(Integer.parseInt(x.value));
break;
case nd_String:
emit_byte(Mnemonic.PUSH);
n = fetch_string_offset(x.value);
emit_word(n);
break;
case nd_Assign:
n = fetch_var_offset(x.left.value);
code_gen(x.right);
emit_byte(Mnemonic.STORE);
emit_word(n);
break;
case nd_If:
p2 = 0; // to avoid NetBeans complaining about 'not initialized'
code_gen(x.left);
emit_byte(Mnemonic.JZ);
p1 = hole();
code_gen(x.right.left);
if (x.right.right != null) {
emit_byte(Mnemonic.JMP);
p2 = hole();
}
emit_word_at(p1, code.length - p1);
if (x.right.right != null) {
code_gen(x.right.right);
emit_word_at(p2, code.length - p2);
}
break;
case nd_While:
p1 = code.length;
code_gen(x.left);
emit_byte(Mnemonic.JZ);
p2 = hole();
code_gen(x.right);
emit_byte(Mnemonic.JMP);
emit_word(p1 - code.length);
emit_word_at(p2, code.length - p2);
break;
case nd_Sequence:
code_gen(x.left);
code_gen(x.right);
break;
case nd_Prtc:
code_gen(x.left);
emit_byte(Mnemonic.PRTC);
break;
case nd_Prti:
code_gen(x.left);
emit_byte(Mnemonic.PRTI);
break;
case nd_Prts:
code_gen(x.left);
emit_byte(Mnemonic.PRTS);
break;
default:
if (arrayContains(operators, x.nt)) {
code_gen(x.left);
code_gen(x.right);
emit_byte(x.nt.getMnemonic());
} else if (arrayContains(unary_ops, x.nt)) {
code_gen(x.left);
emit_byte(x.nt.getMnemonic());
} else {
throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator.");
}
}
}
static void list_code() throws Exception {
int pc = 0, x;
Mnemonic op;
System.out.println("Datasize: " + var_count + " Strings: " + string_count);
for (String s: string_pool) {
System.out.println(s);
}
while (pc < code.length) {
System.out.printf("%4d ", pc);
op = Mnemonic.values()[code[pc++]];
switch (op) {
case FETCH:
x = get_word(pc);
System.out.printf("fetch [%d]", x);
pc += WORDSIZE;
break;
case STORE:
x = get_word(pc);
System.out.printf("store [%d]", x);
pc += WORDSIZE;
break;
case PUSH:
x = get_word(pc);
System.out.printf("push %d", x);
pc += WORDSIZE;
break;
case ADD: case SUB: case MUL: case DIV: case MOD:
case LT: case GT: case LE: case GE: case EQ: case NE:
case AND: case OR: case NEG: case NOT:
case PRTC: case PRTI: case PRTS: case HALT:
System.out.print(op.toString().toLowerCase());
break;
case JMP:
x = get_word(pc);
System.out.printf("jmp (%d) %d", x, pc + x);
pc += WORDSIZE;
break;
case JZ:
x = get_word(pc);
System.out.printf("jz (%d) %d", x, pc + x);
pc += WORDSIZE;
break;
default:
throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1));
}
System.out.println();
}
}
static Node load_ast() throws Exception {
String command, value;
String line;
Node left, right;
while (s.hasNext()) {
line = s.nextLine();
value = null;
if (line.length() > 16) {
command = line.substring(0, 15).trim();
value = line.substring(15).trim();
} else {
command = line.trim();
}
if (command.equals(";")) {
return null;
}
if (!str_to_nodes.containsKey(command)) {
throw new Exception("Command not found: '" + command + "'");
}
if (value != null) {
return Node.make_leaf(str_to_nodes.get(command), value);
}
left = load_ast(); right = load_ast();
return Node.make_node(str_to_nodes.get(command), left, right);
}
return null; // for the compiler, not needed
}
public static void main(String[] args) {
Node n;
str_to_nodes.put(";", NodeType.nd_None);
str_to_nodes.put("Sequence", NodeType.nd_Sequence);
str_to_nodes.put("Identifier", NodeType.nd_Ident);
str_to_nodes.put("String", NodeType.nd_String);
str_to_nodes.put("Integer", NodeType.nd_Integer);
str_to_nodes.put("If", NodeType.nd_If);
str_to_nodes.put("While", NodeType.nd_While);
str_to_nodes.put("Prtc", NodeType.nd_Prtc);
str_to_nodes.put("Prts", NodeType.nd_Prts);
str_to_nodes.put("Prti", NodeType.nd_Prti);
str_to_nodes.put("Assign", NodeType.nd_Assign);
str_to_nodes.put("Negate", NodeType.nd_Negate);
str_to_nodes.put("Not", NodeType.nd_Not);
str_to_nodes.put("Multiply", NodeType.nd_Mul);
str_to_nodes.put("Divide", NodeType.nd_Div);
str_to_nodes.put("Mod", NodeType.nd_Mod);
str_to_nodes.put("Add", NodeType.nd_Add);
str_to_nodes.put("Subtract", NodeType.nd_Sub);
str_to_nodes.put("Less", NodeType.nd_Lss);
str_to_nodes.put("LessEqual", NodeType.nd_Leq);
str_to_nodes.put("Greater", NodeType.nd_Gtr);
str_to_nodes.put("GreaterEqual", NodeType.nd_Geq);
str_to_nodes.put("Equal", NodeType.nd_Eql);
str_to_nodes.put("NotEqual", NodeType.nd_Neq);
str_to_nodes.put("And", NodeType.nd_And);
str_to_nodes.put("Or", NodeType.nd_Or);
if (args.length > 0) {
try {
s = new Scanner(new File(args[0]));
n = load_ast();
code_gen(n);
emit_byte(Mnemonic.HALT);
list_code();
} catch (Exception e) {
System.out.println("Ex: "+e);//.getMessage());
}
}
}
}
|
Compiler/lexical analyzer | Java | The C and Python versions can be considered reference implementations.
;Related Tasks
* Syntax Analyzer task
* Code Generator task
* Virtual Machine Interpreter task
* AST Interpreter task
| // Translated from python source
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Lexer {
private int line;
private int pos;
private int position;
private char chr;
private String s;
Map<String, TokenType> keywords = new HashMap<>();
static class Token {
public TokenType tokentype;
public String value;
public int line;
public int pos;
Token(TokenType token, String value, int line, int pos) {
this.tokentype = token; this.value = value; this.line = line; this.pos = pos;
}
@Override
public String toString() {
String result = String.format("%5d %5d %-15s", this.line, this.pos, this.tokentype);
switch (this.tokentype) {
case Integer:
result += String.format(" %4s", value);
break;
case Identifier:
result += String.format(" %s", value);
break;
case String:
result += String.format(" \"%s\"", value);
break;
}
return result;
}
}
static enum TokenType {
End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,
Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,
Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Keyword_if,
Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen,
LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String
}
static void error(int line, int pos, String msg) {
if (line > 0 && pos > 0) {
System.out.printf("%s in line %d, pos %d\n", msg, line, pos);
} else {
System.out.println(msg);
}
System.exit(1);
}
Lexer(String source) {
this.line = 1;
this.pos = 0;
this.position = 0;
this.s = source;
this.chr = this.s.charAt(0);
this.keywords.put("if", TokenType.Keyword_if);
this.keywords.put("else", TokenType.Keyword_else);
this.keywords.put("print", TokenType.Keyword_print);
this.keywords.put("putc", TokenType.Keyword_putc);
this.keywords.put("while", TokenType.Keyword_while);
}
Token follow(char expect, TokenType ifyes, TokenType ifno, int line, int pos) {
if (getNextChar() == expect) {
getNextChar();
return new Token(ifyes, "", line, pos);
}
if (ifno == TokenType.End_of_input) {
error(line, pos, String.format("follow: unrecognized character: (%d) '%c'", (int)this.chr, this.chr));
}
return new Token(ifno, "", line, pos);
}
Token char_lit(int line, int pos) {
char c = getNextChar(); // skip opening quote
int n = (int)c;
if (c == '\'') {
error(line, pos, "empty character constant");
} else if (c == '\\') {
c = getNextChar();
if (c == 'n') {
n = 10;
} else if (c == '\\') {
n = '\\';
} else {
error(line, pos, String.format("unknown escape sequence \\%c", c));
}
}
if (getNextChar() != '\'') {
error(line, pos, "multi-character constant");
}
getNextChar();
return new Token(TokenType.Integer, "" + n, line, pos);
}
Token string_lit(char start, int line, int pos) {
String result = "";
while (getNextChar() != start) {
if (this.chr == '\u0000') {
error(line, pos, "EOF while scanning string literal");
}
if (this.chr == '\n') {
error(line, pos, "EOL while scanning string literal");
}
result += this.chr;
}
getNextChar();
return new Token(TokenType.String, result, line, pos);
}
Token div_or_comment(int line, int pos) {
if (getNextChar() != '*') {
return new Token(TokenType.Op_divide, "", line, pos);
}
getNextChar();
while (true) {
if (this.chr == '\u0000') {
error(line, pos, "EOF in comment");
} else if (this.chr == '*') {
if (getNextChar() == '/') {
getNextChar();
return getToken();
}
} else {
getNextChar();
}
}
}
Token identifier_or_integer(int line, int pos) {
boolean is_number = true;
String text = "";
while (Character.isAlphabetic(this.chr) || Character.isDigit(this.chr) || this.chr == '_') {
text += this.chr;
if (!Character.isDigit(this.chr)) {
is_number = false;
}
getNextChar();
}
if (text.equals("")) {
error(line, pos, String.format("identifer_or_integer unrecognized character: (%d) %c", (int)this.chr, this.chr));
}
if (Character.isDigit(text.charAt(0))) {
if (!is_number) {
error(line, pos, String.format("invalid number: %s", text));
}
return new Token(TokenType.Integer, text, line, pos);
}
if (this.keywords.containsKey(text)) {
return new Token(this.keywords.get(text), "", line, pos);
}
return new Token(TokenType.Identifier, text, line, pos);
}
Token getToken() {
int line, pos;
while (Character.isWhitespace(this.chr)) {
getNextChar();
}
line = this.line;
pos = this.pos;
switch (this.chr) {
case '\u0000': return new Token(TokenType.End_of_input, "", this.line, this.pos);
case '/': return div_or_comment(line, pos);
case '\'': return char_lit(line, pos);
case '<': return follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos);
case '>': return follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos);
case '=': return follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos);
case '!': return follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos);
case '&': return follow('&', TokenType.Op_and, TokenType.End_of_input, line, pos);
case '|': return follow('|', TokenType.Op_or, TokenType.End_of_input, line, pos);
case '"': return string_lit(this.chr, line, pos);
case '{': getNextChar(); return new Token(TokenType.LeftBrace, "", line, pos);
case '}': getNextChar(); return new Token(TokenType.RightBrace, "", line, pos);
case '(': getNextChar(); return new Token(TokenType.LeftParen, "", line, pos);
case ')': getNextChar(); return new Token(TokenType.RightParen, "", line, pos);
case '+': getNextChar(); return new Token(TokenType.Op_add, "", line, pos);
case '-': getNextChar(); return new Token(TokenType.Op_subtract, "", line, pos);
case '*': getNextChar(); return new Token(TokenType.Op_multiply, "", line, pos);
case '%': getNextChar(); return new Token(TokenType.Op_mod, "", line, pos);
case ';': getNextChar(); return new Token(TokenType.Semicolon, "", line, pos);
case ',': getNextChar(); return new Token(TokenType.Comma, "", line, pos);
default: return identifier_or_integer(line, pos);
}
}
char getNextChar() {
this.pos++;
this.position++;
if (this.position >= this.s.length()) {
this.chr = '\u0000';
return this.chr;
}
this.chr = this.s.charAt(this.position);
if (this.chr == '\n') {
this.line++;
this.pos = 0;
}
return this.chr;
}
void printTokens() {
Token t;
while ((t = getToken()).tokentype != TokenType.End_of_input) {
System.out.println(t);
}
System.out.println(t);
}
public static void main(String[] args) {
if (args.length > 0) {
try {
File f = new File(args[0]);
Scanner s = new Scanner(f);
String source = " ";
while (s.hasNext()) {
source += s.nextLine() + "\n";
}
Lexer l = new Lexer(source);
l.printTokens();
} catch(FileNotFoundException e) {
error(-1, -1, "Exception: " + e.getMessage());
}
} else {
error(-1, -1, "No args");
}
}
}
|
Compiler/syntax analyzer | Java from Python | The C and Python versions can be considered reference implementations.
;Related Tasks
* Lexical Analyzer task
* Code Generator task
* Virtual Machine Interpreter task
* AST Interpreter task
__TOC__
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Parser {
private List<Token> source;
private Token token;
private int position;
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static class Token {
public TokenType tokentype;
public String value;
public int line;
public int pos;
Token(TokenType token, String value, int line, int pos) {
this.tokentype = token; this.value = value; this.line = line; this.pos = pos;
}
@Override
public String toString() {
return String.format("%5d %5d %-15s %s", this.line, this.pos, this.tokentype, this.value);
}
}
static enum TokenType {
End_of_input(false, false, false, -1, NodeType.nd_None),
Op_multiply(false, true, false, 13, NodeType.nd_Mul),
Op_divide(false, true, false, 13, NodeType.nd_Div),
Op_mod(false, true, false, 13, NodeType.nd_Mod),
Op_add(false, true, false, 12, NodeType.nd_Add),
Op_subtract(false, true, false, 12, NodeType.nd_Sub),
Op_negate(false, false, true, 14, NodeType.nd_Negate),
Op_not(false, false, true, 14, NodeType.nd_Not),
Op_less(false, true, false, 10, NodeType.nd_Lss),
Op_lessequal(false, true, false, 10, NodeType.nd_Leq),
Op_greater(false, true, false, 10, NodeType.nd_Gtr),
Op_greaterequal(false, true, false, 10, NodeType.nd_Geq),
Op_equal(false, true, true, 9, NodeType.nd_Eql),
Op_notequal(false, true, false, 9, NodeType.nd_Neq),
Op_assign(false, false, false, -1, NodeType.nd_Assign),
Op_and(false, true, false, 5, NodeType.nd_And),
Op_or(false, true, false, 4, NodeType.nd_Or),
Keyword_if(false, false, false, -1, NodeType.nd_If),
Keyword_else(false, false, false, -1, NodeType.nd_None),
Keyword_while(false, false, false, -1, NodeType.nd_While),
Keyword_print(false, false, false, -1, NodeType.nd_None),
Keyword_putc(false, false, false, -1, NodeType.nd_None),
LeftParen(false, false, false, -1, NodeType.nd_None),
RightParen(false, false, false, -1, NodeType.nd_None),
LeftBrace(false, false, false, -1, NodeType.nd_None),
RightBrace(false, false, false, -1, NodeType.nd_None),
Semicolon(false, false, false, -1, NodeType.nd_None),
Comma(false, false, false, -1, NodeType.nd_None),
Identifier(false, false, false, -1, NodeType.nd_Ident),
Integer(false, false, false, -1, NodeType.nd_Integer),
String(false, false, false, -1, NodeType.nd_String);
private final int precedence;
private final boolean right_assoc;
private final boolean is_binary;
private final boolean is_unary;
private final NodeType node_type;
TokenType(boolean right_assoc, boolean is_binary, boolean is_unary, int precedence, NodeType node) {
this.right_assoc = right_assoc;
this.is_binary = is_binary;
this.is_unary = is_unary;
this.precedence = precedence;
this.node_type = node;
}
boolean isRightAssoc() { return this.right_assoc; }
boolean isBinary() { return this.is_binary; }
boolean isUnary() { return this.is_unary; }
int getPrecedence() { return this.precedence; }
NodeType getNodeType() { return this.node_type; }
}
static enum NodeType {
nd_None(""), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) {
this.name = name;
}
@Override
public String toString() { return this.name; }
}
static void error(int line, int pos, String msg) {
if (line > 0 && pos > 0) {
System.out.printf("%s in line %d, pos %d\n", msg, line, pos);
} else {
System.out.println(msg);
}
System.exit(1);
}
Parser(List<Token> source) {
this.source = source;
this.token = null;
this.position = 0;
}
Token getNextToken() {
this.token = this.source.get(this.position++);
return this.token;
}
Node expr(int p) {
Node result = null, node;
TokenType op;
int q;
if (this.token.tokentype == TokenType.LeftParen) {
result = paren_expr();
} else if (this.token.tokentype == TokenType.Op_add || this.token.tokentype == TokenType.Op_subtract) {
op = (this.token.tokentype == TokenType.Op_subtract) ? TokenType.Op_negate : TokenType.Op_add;
getNextToken();
node = expr(TokenType.Op_negate.getPrecedence());
result = (op == TokenType.Op_negate) ? Node.make_node(NodeType.nd_Negate, node) : node;
} else if (this.token.tokentype == TokenType.Op_not) {
getNextToken();
result = Node.make_node(NodeType.nd_Not, expr(TokenType.Op_not.getPrecedence()));
} else if (this.token.tokentype == TokenType.Identifier) {
result = Node.make_leaf(NodeType.nd_Ident, this.token.value);
getNextToken();
} else if (this.token.tokentype == TokenType.Integer) {
result = Node.make_leaf(NodeType.nd_Integer, this.token.value);
getNextToken();
} else {
error(this.token.line, this.token.pos, "Expecting a primary, found: " + this.token.tokentype);
}
while (this.token.tokentype.isBinary() && this.token.tokentype.getPrecedence() >= p) {
op = this.token.tokentype;
getNextToken();
q = op.getPrecedence();
if (!op.isRightAssoc()) {
q++;
}
node = expr(q);
result = Node.make_node(op.getNodeType(), result, node);
}
return result;
}
Node paren_expr() {
expect("paren_expr", TokenType.LeftParen);
Node node = expr(0);
expect("paren_expr", TokenType.RightParen);
return node;
}
void expect(String msg, TokenType s) {
if (this.token.tokentype == s) {
getNextToken();
return;
}
error(this.token.line, this.token.pos, msg + ": Expecting '" + s + "', found: '" + this.token.tokentype + "'");
}
Node stmt() {
Node s, s2, t = null, e, v;
if (this.token.tokentype == TokenType.Keyword_if) {
getNextToken();
e = paren_expr();
s = stmt();
s2 = null;
if (this.token.tokentype == TokenType.Keyword_else) {
getNextToken();
s2 = stmt();
}
t = Node.make_node(NodeType.nd_If, e, Node.make_node(NodeType.nd_If, s, s2));
} else if (this.token.tokentype == TokenType.Keyword_putc) {
getNextToken();
e = paren_expr();
t = Node.make_node(NodeType.nd_Prtc, e);
expect("Putc", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Keyword_print) {
getNextToken();
expect("Print", TokenType.LeftParen);
while (true) {
if (this.token.tokentype == TokenType.String) {
e = Node.make_node(NodeType.nd_Prts, Node.make_leaf(NodeType.nd_String, this.token.value));
getNextToken();
} else {
e = Node.make_node(NodeType.nd_Prti, expr(0), null);
}
t = Node.make_node(NodeType.nd_Sequence, t, e);
if (this.token.tokentype != TokenType.Comma) {
break;
}
getNextToken();
}
expect("Print", TokenType.RightParen);
expect("Print", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Semicolon) {
getNextToken();
} else if (this.token.tokentype == TokenType.Identifier) {
v = Node.make_leaf(NodeType.nd_Ident, this.token.value);
getNextToken();
expect("assign", TokenType.Op_assign);
e = expr(0);
t = Node.make_node(NodeType.nd_Assign, v, e);
expect("assign", TokenType.Semicolon);
} else if (this.token.tokentype == TokenType.Keyword_while) {
getNextToken();
e = paren_expr();
s = stmt();
t = Node.make_node(NodeType.nd_While, e, s);
} else if (this.token.tokentype == TokenType.LeftBrace) {
getNextToken();
while (this.token.tokentype != TokenType.RightBrace && this.token.tokentype != TokenType.End_of_input) {
t = Node.make_node(NodeType.nd_Sequence, t, stmt());
}
expect("LBrace", TokenType.RightBrace);
} else if (this.token.tokentype == TokenType.End_of_input) {
} else {
error(this.token.line, this.token.pos, "Expecting start of statement, found: " + this.token.tokentype);
}
return t;
}
Node parse() {
Node t = null;
getNextToken();
while (this.token.tokentype != TokenType.End_of_input) {
t = Node.make_node(NodeType.nd_Sequence, t, stmt());
}
return t;
}
void printAST(Node t) {
int i = 0;
if (t == null) {
System.out.println(";");
} else {
System.out.printf("%-14s", t.nt);
if (t.nt == NodeType.nd_Ident || t.nt == NodeType.nd_Integer || t.nt == NodeType.nd_String) {
System.out.println(" " + t.value);
} else {
System.out.println();
printAST(t.left);
printAST(t.right);
}
}
}
public static void main(String[] args) {
if (args.length > 0) {
try {
String value, token;
int line, pos;
Token t;
boolean found;
List<Token> list = new ArrayList<>();
Map<String, TokenType> str_to_tokens = new HashMap<>();
str_to_tokens.put("End_of_input", TokenType.End_of_input);
str_to_tokens.put("Op_multiply", TokenType.Op_multiply);
str_to_tokens.put("Op_divide", TokenType.Op_divide);
str_to_tokens.put("Op_mod", TokenType.Op_mod);
str_to_tokens.put("Op_add", TokenType.Op_add);
str_to_tokens.put("Op_subtract", TokenType.Op_subtract);
str_to_tokens.put("Op_negate", TokenType.Op_negate);
str_to_tokens.put("Op_not", TokenType.Op_not);
str_to_tokens.put("Op_less", TokenType.Op_less);
str_to_tokens.put("Op_lessequal", TokenType.Op_lessequal);
str_to_tokens.put("Op_greater", TokenType.Op_greater);
str_to_tokens.put("Op_greaterequal", TokenType.Op_greaterequal);
str_to_tokens.put("Op_equal", TokenType.Op_equal);
str_to_tokens.put("Op_notequal", TokenType.Op_notequal);
str_to_tokens.put("Op_assign", TokenType.Op_assign);
str_to_tokens.put("Op_and", TokenType.Op_and);
str_to_tokens.put("Op_or", TokenType.Op_or);
str_to_tokens.put("Keyword_if", TokenType.Keyword_if);
str_to_tokens.put("Keyword_else", TokenType.Keyword_else);
str_to_tokens.put("Keyword_while", TokenType.Keyword_while);
str_to_tokens.put("Keyword_print", TokenType.Keyword_print);
str_to_tokens.put("Keyword_putc", TokenType.Keyword_putc);
str_to_tokens.put("LeftParen", TokenType.LeftParen);
str_to_tokens.put("RightParen", TokenType.RightParen);
str_to_tokens.put("LeftBrace", TokenType.LeftBrace);
str_to_tokens.put("RightBrace", TokenType.RightBrace);
str_to_tokens.put("Semicolon", TokenType.Semicolon);
str_to_tokens.put("Comma", TokenType.Comma);
str_to_tokens.put("Identifier", TokenType.Identifier);
str_to_tokens.put("Integer", TokenType.Integer);
str_to_tokens.put("String", TokenType.String);
Scanner s = new Scanner(new File(args[0]));
String source = " ";
while (s.hasNext()) {
String str = s.nextLine();
StringTokenizer st = new StringTokenizer(str);
line = Integer.parseInt(st.nextToken());
pos = Integer.parseInt(st.nextToken());
token = st.nextToken();
value = "";
while (st.hasMoreTokens()) {
value += st.nextToken() + " ";
}
found = false;
if (str_to_tokens.containsKey(token)) {
found = true;
list.add(new Token(str_to_tokens.get(token), value, line, pos));
}
if (found == false) {
throw new Exception("Token not found: '" + token + "'");
}
}
Parser p = new Parser(list);
p.printAST(p.parse());
} catch (FileNotFoundException e) {
error(-1, -1, "Exception: " + e.getMessage());
} catch (Exception e) {
error(-1, -1, "Exception: " + e.getMessage());
}
} else {
error(-1, -1, "No args");
}
}
}
|
Conjugate transpose | Java | Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.
::: (M^H)_{ji} = \overline{M_{ij}}
This means that row j, column i of the conjugate transpose equals the
complex conjugate of row i, column j of the original matrix.
In the next list, M must also be a square matrix.
* A Hermitian matrix equals its own conjugate transpose: M^H = M.
* A multiplication with its conjugate transpose: M^HM = MM^H.
* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.
;Task:
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
::* Hermitian matrix,
::* normal matrix, or
::* unitary matrix.
;See also:
* MathWorld entry: conjugate transpose
* MathWorld entry: Hermitian matrix
* MathWorld entry: normal matrix
* MathWorld entry: unitary matrix
| import java.util.Arrays;
import java.util.List;
public final class ConjugateTranspose {
public static void main(String[] aArgs) {
ComplexMatrix one = new ComplexMatrix( new Complex[][] { { new Complex(0, 4), new Complex(-1, 1) },
{ new Complex(1, -1), new Complex(0, 4) } } );
ComplexMatrix two = new ComplexMatrix(
new Complex[][] { { new Complex(1, 0), new Complex(1, 1), new Complex(0, 2) },
{ new Complex(1, -1), new Complex(5, 0), new Complex(-3, 0) },
{ new Complex(0, -2), new Complex(-3, 0), new Complex(0, 0) } } );
final double term = 1.0 / Math.sqrt(2.0);
ComplexMatrix three = new ComplexMatrix( new Complex[][] { { new Complex(term, 0), new Complex(term, 0) },
{ new Complex(0, term), new Complex(0, -term) } } );
List<ComplexMatrix> matricies = List.of( one, two, three );
for ( ComplexMatrix matrix : matricies ) {
System.out.println("Matrix:");
matrix.display();
System.out.println("Conjugate transpose:");
matrix.conjugateTranspose().display();
System.out.println("Hermitian: " + matrix.isHermitian());
System.out.println("Normal: " + matrix.isNormal());
System.out.println("Unitary: " + matrix.isUnitary() + System.lineSeparator());
}
}
}
final class ComplexMatrix {
public ComplexMatrix(Complex[][] aData) {
rowCount = aData.length;
colCount = aData[0].length;
data = Arrays.stream(aData).map( row -> Arrays.copyOf(row, row.length) ).toArray(Complex[][]::new);
}
public ComplexMatrix multiply(ComplexMatrix aOther) {
if ( colCount != aOther.rowCount ) {
throw new RuntimeException("Incompatible matrix dimensions.");
}
Complex[][] newData = new Complex[rowCount][aOther.colCount];
Arrays.stream(newData).forEach( row -> Arrays.fill(row, new Complex(0, 0)) );
for ( int row = 0; row < rowCount; row++ ) {
for ( int col = 0; col < aOther.colCount; col++ ) {
for ( int k = 0; k < colCount; k++ ) {
newData[row][col] = newData[row][col].add(data[row][k].multiply(aOther.data[k][col]));
}
}
}
return new ComplexMatrix(newData);
}
public ComplexMatrix conjugateTranspose() {
if ( rowCount != colCount ) {
throw new IllegalArgumentException("Only applicable to a square matrix");
}
Complex[][] newData = new Complex[colCount][rowCount];
for ( int row = 0; row < rowCount; row++ ) {
for ( int col = 0; col < colCount; col++ ) {
newData[col][row] = data[row][col].conjugate();
}
}
return new ComplexMatrix(newData);
}
public static ComplexMatrix identity(int aSize) {
Complex[][] data = new Complex[aSize][aSize];
for ( int row = 0; row < aSize; row++ ) {
for ( int col = 0; col < aSize; col++ ) {
data[row][col] = ( row == col ) ? new Complex(1, 0) : new Complex(0, 0);
}
}
return new ComplexMatrix(data);
}
public boolean equals(ComplexMatrix aOther) {
if ( aOther.rowCount != rowCount || aOther.colCount != colCount ) {
return false;
}
for ( int row = 0; row < rowCount; row++ ) {
for ( int col = 0; col < colCount; col++ ) {
if ( data[row][col].subtract(aOther.data[row][col]).modulus() > EPSILON ) {
return false;
}
}
}
return true;
}
public void display() {
for ( int row = 0; row < rowCount; row++ ) {
System.out.print("[");
for ( int col = 0; col < colCount - 1; col++ ) {
System.out.print(data[row][col] + ", ");
}
System.out.println(data[row][colCount - 1] + " ]");
}
}
public boolean isHermitian() {
return equals(conjugateTranspose());
}
public boolean isNormal() {
ComplexMatrix conjugateTranspose = conjugateTranspose();
return multiply(conjugateTranspose).equals(conjugateTranspose.multiply(this));
}
public boolean isUnitary() {
ComplexMatrix conjugateTranspose = conjugateTranspose();
return multiply(conjugateTranspose).equals(identity(rowCount)) &&
conjugateTranspose.multiply(this).equals(identity(rowCount));
}
private final int rowCount;
private final int colCount;
private final Complex[][] data;
private static final double EPSILON = 0.000_000_000_001;
}
final class Complex {
public Complex(double aReal, double aImag) {
real = aReal;
imag = aImag;
}
public Complex add(Complex aOther) {
return new Complex(real + aOther.real, imag + aOther.imag);
}
public Complex multiply(Complex aOther) {
return new Complex(real * aOther.real - imag * aOther.imag, real * aOther.imag + imag * aOther.real);
}
public Complex negate() {
return new Complex(-real, -imag);
}
public Complex subtract(Complex aOther) {
return this.add(aOther.negate());
}
public Complex conjugate() {
return new Complex(real, -imag);
}
public double modulus() {
return Math.hypot(real, imag);
}
public boolean equals(Complex aOther) {
return real == aOther.real && imag == aOther.imag;
}
@Override
public String toString() {
String prefix = ( real < 0.0 ) ? "" : " ";
String realPart = prefix + String.format("%.3f", real);
String sign = ( imag < 0.0 ) ? " - " : " + ";
return realPart + sign + String.format("%.3f", Math.abs(imag)) + "i";
}
private final double real;
private final double imag;
}
|
Continued fraction | Java 8 | A number may be represented as a continued fraction (see Mathworld for more information) as follows:
:a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.
:\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}}
For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.
:e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}}
For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.
:\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}
;See also:
:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
| import static java.lang.Math.pow;
import java.util.*;
import java.util.function.Function;
public class Test {
static double calc(Function<Integer, Integer[]> f, int n) {
double temp = 0;
for (int ni = n; ni >= 1; ni--) {
Integer[] p = f.apply(ni);
temp = p[1] / (double) (p[0] + temp);
}
return f.apply(0)[0] + temp;
}
public static void main(String[] args) {
List<Function<Integer, Integer[]>> fList = new ArrayList<>();
fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1});
fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1});
fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)});
for (Function<Integer, Integer[]> f : fList)
System.out.println(calc(f, 200));
}
} |
Continued fraction/Arithmetic/Construct from rational number | Java 9 | To understand this task in context please see [[Continued fraction arithmetic]]
The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming:
:N_1 is the numerator
:N_2 is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero.
Demonstrate the function by outputing the continued fraction for:
: 1/2
: 3
: 23/8
: 13/11
: 22/7
: -151/77
\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you:
: 14142,10000
: 141421,100000
: 1414214,1000000
: 14142136,10000000
Try :
: 31,10
: 314,100
: 3142,1000
: 31428,10000
: 314285,100000
: 3142857,1000000
: 31428571,10000000
: 314285714,100000000
Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
| import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConstructFromRationalNumber {
private static class R2cf implements Iterator<Integer> {
private int num;
private int den;
R2cf(int num, int den) {
this.num = num;
this.den = den;
}
@Override
public boolean hasNext() {
return den != 0;
}
@Override
public Integer next() {
int div = num / den;
int rem = num % den;
num = den;
den = rem;
return div;
}
}
private static void iterate(R2cf generator) {
generator.forEachRemaining(n -> System.out.printf("%d ", n));
System.out.println();
}
public static void main(String[] args) {
List<Map.Entry<Integer, Integer>> fracs = List.of(
Map.entry(1, 2),
Map.entry(3, 1),
Map.entry(23, 8),
Map.entry(13, 11),
Map.entry(22, 7),
Map.entry(-151, 77)
);
for (Map.Entry<Integer, Integer> frac : fracs) {
System.out.printf("%4d / %-2d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
System.out.println("\nSqrt(2) ->");
List<Map.Entry<Integer, Integer>> root2 = List.of(
Map.entry( 14_142, 10_000),
Map.entry( 141_421, 100_000),
Map.entry( 1_414_214, 1_000_000),
Map.entry(14_142_136, 10_000_000)
);
for (Map.Entry<Integer, Integer> frac : root2) {
System.out.printf("%8d / %-8d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
System.out.println("\nPi ->");
List<Map.Entry<Integer, Integer>> pi = List.of(
Map.entry( 31, 10),
Map.entry( 314, 100),
Map.entry( 3_142, 1_000),
Map.entry( 31_428, 10_000),
Map.entry( 314_285, 100_000),
Map.entry( 3_142_857, 1_000_000),
Map.entry( 31_428_571, 10_000_000),
Map.entry(314_285_714, 100_000_000)
);
for (Map.Entry<Integer, Integer> frac : pi) {
System.out.printf("%9d / %-9d = ", frac.getKey(), frac.getValue());
iterate(new R2cf(frac.getKey(), frac.getValue()));
}
}
} |
Convert decimal number to rational | Java | The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...
Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518) = 0.518518...
Acceptable output:
* 0.9054054 - 4527027 / 5000000
* 0.518518 - 259259 / 500000
Finite decimals are of course no problem:
* 0.75 - 3 / 4
| double fractionToDecimal(String string) {
int indexOf = string.indexOf(' ');
int integer = 0;
int numerator, denominator;
if (indexOf != -1) {
integer = Integer.parseInt(string.substring(0, indexOf));
string = string.substring(indexOf + 1);
}
indexOf = string.indexOf('/');
numerator = Integer.parseInt(string.substring(0, indexOf));
denominator = Integer.parseInt(string.substring(indexOf + 1));
return integer + ((double) numerator / denominator);
}
String decimalToFraction(double value) {
String string = String.valueOf(value);
string = string.substring(string.indexOf('.') + 1);
int numerator = Integer.parseInt(string);
int denominator = (int) Math.pow(10, string.length());
int gcf = gcf(numerator, denominator);
if (gcf != 0) {
numerator /= gcf;
denominator /= gcf;
}
int integer = (int) value;
if (integer != 0)
return "%d %d/%d".formatted(integer, numerator, denominator);
return "%d/%d".formatted(numerator, denominator);
}
int gcf(int valueA, int valueB) {
if (valueB == 0) return valueA;
else return gcf(valueB, valueA % valueB);
}
|
Convert seconds to compound duration | Java | Write a function or program which:
* takes a positive integer representing a duration in seconds as input (e.g., 100), and
* returns a string which shows the same duration decomposed into:
:::* weeks,
:::* days,
:::* hours,
:::* minutes, and
:::* seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
'''''Test Cases'''''
:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}
'''''Details'''''
The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}
However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| String duration(int seconds) {
StringBuilder string = new StringBuilder();
if (seconds >= 604_800 /* 1 wk */) {
string.append("%,d wk".formatted(seconds / 604_800));
seconds %= 604_800;
}
if (seconds >= 86_400 /* 1 d */) {
if (!string.isEmpty()) string.append(", ");
string.append("%d d".formatted(seconds / 86_400));
seconds %= 86_400;
}
if (seconds >= 3600 /* 1 hr */) {
if (!string.isEmpty()) string.append(", ");
string.append("%d hr".formatted(seconds / 3600));
seconds %= 3600;
}
if (seconds >= 60 /* 1 min */) {
if (!string.isEmpty()) string.append(", ");
string.append("%d min".formatted(seconds / 60));
seconds %= 60;
}
if (seconds > 0) {
if (!string.isEmpty()) string.append(", ");
string.append("%d sec".formatted(seconds));
}
return string.toString();
}
|
Copy stdin to stdout | Java | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| import java.util.Scanner;
public class CopyStdinToStdout {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in);) {
String s;
while ( (s = scanner.nextLine()).compareTo("") != 0 ) {
System.out.println(s);
}
}
}
}
|
Count the coins | Java 1.5+ | There are four types of common coins in US currency:
:::# quarters (25 cents)
:::# dimes (10 cents)
:::# nickels (5 cents), and
:::# pennies (1 cent)
There are six ways to make change for 15 cents:
:::# A dime and a nickel
:::# A dime and 5 pennies
:::# 3 nickels
:::# 2 nickels and 5 pennies
:::# A nickel and 10 pennies
:::# 15 pennies
;Task:
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
;Optional:
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.
| import java.util.Arrays;
import java.math.BigInteger;
class CountTheCoins {
private static BigInteger countChanges(int amount, int[] coins){
final int n = coins.length;
int cycle = 0;
for (int c : coins)
if (c <= amount && c >= cycle)
cycle = c + 1;
cycle *= n;
BigInteger[] table = new BigInteger[cycle];
Arrays.fill(table, 0, n, BigInteger.ONE);
Arrays.fill(table, n, cycle, BigInteger.ZERO);
int pos = n;
for (int s = 1; s <= amount; s++) {
for (int i = 0; i < n; i++) {
if (i == 0 && pos >= cycle)
pos = 0;
if (coins[i] <= s) {
final int q = pos - (coins[i] * n);
table[pos] = (q >= 0) ? table[q] : table[q + cycle];
}
if (i != 0)
table[pos] = table[pos].add(table[pos - 1]);
pos++;
}
}
return table[pos - 1];
}
public static void main(String[] args) {
final int[][] coinsUsEu = {{100, 50, 25, 10, 5, 1},
{200, 100, 50, 20, 10, 5, 2, 1}};
for (int[] coins : coinsUsEu) {
System.out.println(countChanges( 100,
Arrays.copyOfRange(coins, 2, coins.length)));
System.out.println(countChanges( 100000, coins));
System.out.println(countChanges( 1000000, coins));
System.out.println(countChanges(10000000, coins) + "\n");
}
}
} |
Create an HTML table | Java | Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.
| String generateHTMLTable() {
StringBuilder string = new StringBuilder();
string.append("<table border=\"1\">");
string.append(System.lineSeparator());
string.append("<tr>".indent(2));
string.append("<th width=\"40\"></th>".indent(4));
string.append("<th width=\"50\">X</th>".indent(4));
string.append("<th width=\"50\">Y</th>".indent(4));
string.append("<th width=\"50\">Z</th>".indent(4));
string.append("</tr>".indent(2));
Random random = new Random();
int number;
for (int countA = 0; countA < 10; countA++) {
string.append("<tr>".indent(2));
string.append("<td>%d</td>".formatted(countA).indent(4));
for (int countB = 0; countB < 3; countB++) {
number = random.nextInt(1, 9999);
string.append("<td>%,d</td>".formatted(number).indent(4));
}
string.append("</tr>".indent(2));
}
string.append("</table>");
return string.toString();
}
|
Create an HTML table | Java 1.5+ | Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.
| public class HTML {
public static String array2HTML(Object[][] array){
StringBuilder html = new StringBuilder(
"<table>");
for(Object elem:array[0]){
html.append("<th>" + elem.toString() + "</th>");
}
for(int i = 1; i < array.length; i++){
Object[] row = array[i];
html.append("<tr>");
for(Object elem:row){
html.append("<td>" + elem.toString() + "</td>");
}
html.append("</tr>");
}
html.append("</table>");
return html.toString();
}
public static void main(String[] args){
Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};
System.out.println(array2HTML(ints));
}
} |
Cullen and Woodall numbers | Java | A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.
A Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.
So for each '''n''' the associated Cullen number and Woodall number differ by 2.
''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''
'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.
;Task
* Write procedures to find Cullen numbers and Woodall numbers.
* Use those procedures to find and show here, on this page the first 20 of each.
;Stretch
* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.
* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.
;See also
* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| import java.math.BigInteger;
public final class CullenAndWoodhall {
public static void main(String[] aArgs) {
numberSequence(20, NumberType.Cullen);
numberSequence(20, NumberType.Woodhall);
primeSequence(5, NumberType.Cullen);
primeSequence(12, NumberType.Woodhall);
}
private enum NumberType { Cullen, Woodhall }
private static void numberSequence(int aCount, NumberType aNumberType) {
System.out.println();
System.out.println("The first " + aCount + " " + aNumberType + " numbers are:");
numberInitialise();
for ( int index = 1; index <= aCount; index++ ) {
System.out.print(nextNumber(aNumberType) + " ");
}
System.out.println();
}
private static void primeSequence(int aCount, NumberType aNumberType) {
System.out.println();
System.out.println("The indexes of the first " + aCount + " " + aNumberType + " primes are:");
primeInitialise();
while ( count < aCount ) {
if ( nextNumber(aNumberType).isProbablePrime(CERTAINTY) ) {
System.out.print(primeIndex + " ");
count += 1;
}
primeIndex += 1;
}
System.out.println();
}
private static BigInteger nextNumber(NumberType aNumberType) {
number = number.add(BigInteger.ONE);
power = power.shiftLeft(1);
return switch ( aNumberType ) {
case Cullen -> number.multiply(power).add(BigInteger.ONE);
case Woodhall -> number.multiply(power).subtract(BigInteger.ONE);
};
}
private static void numberInitialise() {
number = BigInteger.ZERO;
power = BigInteger.ONE;
}
private static void primeInitialise() {
count = 0;
primeIndex = 1;
numberInitialise();
}
private static BigInteger number;
private static BigInteger power;
private static int count;
private static int primeIndex;
private static final int CERTAINTY = 20;
}
|
Currency | Java | Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
;Note:
The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16
Dollar signs and thousands separators are optional.
| import java.math.*;
import java.util.*;
public class Currency {
final static String taxrate = "7.65";
enum MenuItem {
Hamburger("5.50"), Milkshake("2.86");
private MenuItem(String p) {
price = new BigDecimal(p);
}
public final BigDecimal price;
}
public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH);
MathContext mc = MathContext.DECIMAL128;
Map<MenuItem, BigDecimal> order = new HashMap<>();
order.put(MenuItem.Hamburger, new BigDecimal("4000000000000000"));
order.put(MenuItem.Milkshake, new BigDecimal("2"));
BigDecimal subtotal = BigDecimal.ZERO;
for (MenuItem it : order.keySet())
subtotal = subtotal.add(it.price.multiply(order.get(it), mc));
BigDecimal tax = new BigDecimal(taxrate, mc);
tax = tax.divide(new BigDecimal("100"), mc);
tax = subtotal.multiply(tax, mc);
System.out.printf("Subtotal: %20.2f%n", subtotal);
System.out.printf(" Tax: %20.2f%n", tax);
System.out.printf(" Total: %20.2f%n", subtotal.add(tax));
}
} |
Currying | Java | {{Wikipedia|Currying}}
;Task:
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| public class Currier<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
}
public interface CurriedFunctor<ARG2, RET> {
RET evaluate(ARG2 arg);
}
final CurriableFunctor<ARG1, ARG2, RET> functor;
public Currier(CurriableFunctor<ARG1, ARG2, RET> fn) { functor = fn; }
public CurriedFunctor<ARG2, RET> curry(final ARG1 arg1) {
return new CurriedFunctor<ARG2, RET>() {
public RET evaluate(ARG2 arg2) {
return functor.evaluate(arg1, arg2);
}
};
}
public static void main(String[] args) {
Currier.CurriableFunctor<Integer, Integer, Integer> add
= new Currier.CurriableFunctor<Integer, Integer, Integer>() {
public Integer evaluate(Integer arg1, Integer arg2) {
return new Integer(arg1.intValue() + arg2.intValue());
}
};
Currier<Integer, Integer, Integer> currier
= new Currier<Integer, Integer, Integer>(add);
Currier.CurriedFunctor<Integer, Integer> add5
= currier.curry(new Integer(5));
System.out.println(add5.evaluate(new Integer(2)));
}
} |
Cut a rectangle | Java 7 | A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.
[[file:rect-cut.svg]]
Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.
Possibly related task: [[Maze generation]] for depth-first search.
| import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
} |
Cyclotomic polynomial | Java | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.
;Task:
* Find and print the first 30 cyclotomic polynomials.
* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.
;See also
* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CyclotomicPolynomial {
@SuppressWarnings("unused")
private static int divisions = 0;
private static int algorithm = 2;
public static void main(String[] args) throws Exception {
System.out.println("Task 1: cyclotomic polynomials for n <= 30:");
for ( int i = 1 ; i <= 30 ; i++ ) {
Polynomial p = cyclotomicPolynomial(i);
System.out.printf("CP[%d] = %s%n", i, p);
}
System.out.println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
int n = 0;
for ( int i = 1 ; i <= 10 ; i++ ) {
while ( true ) {
n++;
Polynomial cyclo = cyclotomicPolynomial(n);
if ( cyclo.hasCoefficientAbs(i) ) {
System.out.printf("CP[%d] has coefficient with magnitude = %d%n", n, i);
n--;
break;
}
}
}
}
private static final Map<Integer, Polynomial> COMPUTED = new HashMap<>();
private static Polynomial cyclotomicPolynomial(int n) {
if ( COMPUTED.containsKey(n) ) {
return COMPUTED.get(n);
}
//System.out.println("COMPUTE: n = " + n);
if ( n == 1 ) {
// Polynomial: x - 1
Polynomial p = new Polynomial(1, 1, -1, 0);
COMPUTED.put(1, p);
return p;
}
Map<Integer,Integer> factors = getFactors(n);
if ( factors.containsKey(n) ) {
// n prime
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < n ; index++ ) {
termList.add(new Term(1, index));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 2 && factors.containsKey(2) && factors.get(2) == 1 && factors.containsKey(n/2) && factors.get(n/2) == 1 ) {
// n = 2p
int prime = n/2;
List<Term> termList = new ArrayList<>();
int coeff = -1;
for ( int index = 0 ; index < prime ; index++ ) {
coeff *= -1;
termList.add(new Term(coeff, index));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 1 && factors.containsKey(2) ) {
// n = 2^h
int h = factors.get(2);
List<Term> termList = new ArrayList<>();
termList.add(new Term(1, (int) Math.pow(2, h-1)));
termList.add(new Term(1, 0));
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 1 && ! factors.containsKey(n) ) {
// n = p^k
int p = 0;
for ( int prime : factors.keySet() ) {
p = prime;
}
int k = factors.get(p);
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < p ; index++ ) {
termList.add(new Term(1, index * (int) Math.pow(p, k-1)));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 2 && factors.containsKey(2) ) {
// n = 2^h * p^k
int p = 0;
for ( int prime : factors.keySet() ) {
if ( prime != 2 ) {
p = prime;
}
}
List<Term> termList = new ArrayList<>();
int coeff = -1;
int twoExp = (int) Math.pow(2, factors.get(2)-1);
int k = factors.get(p);
for ( int index = 0 ; index < p ; index++ ) {
coeff *= -1;
termList.add(new Term(coeff, index * twoExp * (int) Math.pow(p, k-1)));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.containsKey(2) && ((n/2) % 2 == 1) && (n/2) > 1 ) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
Polynomial cycloDiv2 = cyclotomicPolynomial(n/2);
List<Term> termList = new ArrayList<>();
for ( Term term : cycloDiv2.polynomialTerms ) {
termList.add(term.exponent % 2 == 0 ? term : term.negate());
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
// General Case
if ( algorithm == 0 ) {
// Slow - uses basic definition.
List<Integer> divisors = getDivisors(n);
// Polynomial: ( x^n - 1 )
Polynomial cyclo = new Polynomial(1, n, -1, 0);
for ( int i : divisors ) {
Polynomial p = cyclotomicPolynomial(i);
cyclo = cyclo.divide(p);
}
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( algorithm == 1 ) {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
List<Integer> divisors = getDivisors(n);
int maxDivisor = Integer.MIN_VALUE;
for ( int div : divisors ) {
maxDivisor = Math.max(maxDivisor, div);
}
List<Integer> divisorsExceptMax = new ArrayList<Integer>();
for ( int div : divisors ) {
if ( maxDivisor % div != 0 ) {
divisorsExceptMax.add(div);
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
Polynomial cyclo = new Polynomial(1, n, -1, 0).divide(new Polynomial(1, maxDivisor, -1, 0));
for ( int i : divisorsExceptMax ) {
Polynomial p = cyclotomicPolynomial(i);
cyclo = cyclo.divide(p);
}
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( algorithm == 2 ) {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
int m = 1;
Polynomial cyclo = cyclotomicPolynomial(m);
List<Integer> primes = new ArrayList<>(factors.keySet());
Collections.sort(primes);
for ( int prime : primes ) {
// CP(m)[x]
Polynomial cycloM = cyclo;
// Compute CP(m)[x^p].
List<Term> termList = new ArrayList<>();
for ( Term t : cycloM.polynomialTerms ) {
termList.add(new Term(t.coefficient, t.exponent * prime));
}
cyclo = new Polynomial(termList).divide(cycloM);
m = m * prime;
}
// Now, m is the largest square free divisor of n
int s = n / m;
// Compute CP(n)[x] = CP(m)[x^s]
List<Term> termList = new ArrayList<>();
for ( Term t : cyclo.polynomialTerms ) {
termList.add(new Term(t.coefficient, t.exponent * s));
}
cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else {
throw new RuntimeException("ERROR 103: Invalid algorithm.");
}
}
private static final List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i && div != number ) {
divisors.add(div);
}
}
}
return divisors;
}
private static final Map<Integer,Map<Integer,Integer>> allFactors = new TreeMap<Integer,Map<Integer,Integer>>();
static {
Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
factors.put(2, 1);
allFactors.put(2, factors);
}
public static Integer MAX_ALL_FACTORS = 100000;
public static final Map<Integer,Integer> getFactors(Integer number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
if ( number % 2 == 0 ) {
Map<Integer,Integer> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2, 1, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( int i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
return factors;
}
}
if ( prime ) {
factors.put(number, 1);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
}
return factors;
}
private static final class Polynomial {
private List<Term> polynomialTerms;
// Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
public Polynomial(int ... values) {
if ( values.length % 2 != 0 ) {
throw new IllegalArgumentException("ERROR 102: Polynomial constructor. Length must be even. Length = " + values.length);
}
polynomialTerms = new ArrayList<>();
for ( int i = 0 ; i < values.length ; i += 2 ) {
Term t = new Term(values[i], values[i+1]);
polynomialTerms.add(t);
}
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial() {
// zero
polynomialTerms = new ArrayList<>();
polynomialTerms.add(new Term(0,0));
}
private boolean hasCoefficientAbs(int coeff) {
for ( Term term : polynomialTerms ) {
if ( Math.abs(term.coefficient) == coeff ) {
return true;
}
}
return false;
}
private Polynomial(List<Term> termList) {
if ( termList.size() == 0 ) {
// zero
termList.add(new Term(0,0));
}
else {
// Remove zero terms if needed
for ( int i = 0 ; i < termList.size() ; i++ ) {
if ( termList.get(i).coefficient == 0 ) {
termList.remove(i);
}
}
}
if ( termList.size() == 0 ) {
// zero
termList.add(new Term(0,0));
}
polynomialTerms = termList;
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial divide(Polynomial v) {
//long start = System.currentTimeMillis();
divisions++;
Polynomial q = new Polynomial();
Polynomial r = this;
long lcv = v.leadingCoefficient();
long dv = v.degree();
while ( r.degree() >= v.degree() ) {
long lcr = r.leadingCoefficient();
long s = lcr / lcv; // Integer division
Term term = new Term(s, r.degree() - dv);
q = q.add(term);
r = r.add(v.multiply(term.negate()));
}
//long end = System.currentTimeMillis();
//System.out.printf("Divide: Elapsed = %d, Degree 1 = %d, Degree 2 = %d%n", (end-start), this.degree(), v.degree());
return q;
}
public Polynomial add(Polynomial polynomial) {
List<Term> termList = new ArrayList<>();
int thisCount = polynomialTerms.size();
int polyCount = polynomial.polynomialTerms.size();
while ( thisCount > 0 || polyCount > 0 ) {
Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);
Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);
if ( thisTerm == null ) {
termList.add(polyTerm.clone());
polyCount--;
}
else if (polyTerm == null ) {
termList.add(thisTerm.clone());
thisCount--;
}
else if ( thisTerm.degree() == polyTerm.degree() ) {
Term t = thisTerm.add(polyTerm);
if ( t.coefficient != 0 ) {
termList.add(t);
}
thisCount--;
polyCount--;
}
else if ( thisTerm.degree() < polyTerm.degree() ) {
termList.add(thisTerm.clone());
thisCount--;
}
else {
termList.add(polyTerm.clone());
polyCount--;
}
}
return new Polynomial(termList);
}
public Polynomial add(Term term) {
List<Term> termList = new ArrayList<>();
boolean added = false;
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
if ( currentTerm.exponent == term.exponent ) {
added = true;
if ( currentTerm.coefficient + term.coefficient != 0 ) {
termList.add(currentTerm.add(term));
}
}
else {
termList.add(currentTerm.clone());
}
}
if ( ! added ) {
termList.add(term.clone());
}
return new Polynomial(termList);
}
public Polynomial multiply(Term term) {
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
termList.add(currentTerm.clone().multiply(term));
}
return new Polynomial(termList);
}
public Polynomial clone() {
List<Term> clone = new ArrayList<>();
for ( Term t : polynomialTerms ) {
clone.add(new Term(t.coefficient, t.exponent));
}
return new Polynomial(clone);
}
public long leadingCoefficient() {
// long coefficient = 0;
// long degree = Integer.MIN_VALUE;
// for ( Term t : polynomialTerms ) {
// if ( t.degree() > degree ) {
// coefficient = t.coefficient;
// degree = t.degree();
// }
// }
return polynomialTerms.get(0).coefficient;
}
public long degree() {
// long degree = Integer.MIN_VALUE;
// for ( Term t : polynomialTerms ) {
// if ( t.degree() > degree ) {
// degree = t.degree();
// }
// }
return polynomialTerms.get(0).exponent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for ( Term term : polynomialTerms ) {
if ( first ) {
sb.append(term);
first = false;
}
else {
sb.append(" ");
if ( term.coefficient > 0 ) {
sb.append("+ ");
sb.append(term);
}
else {
sb.append("- ");
sb.append(term.negate());
}
}
}
return sb.toString();
}
}
private static final class TermSorter implements Comparator<Term> {
@Override
public int compare(Term o1, Term o2) {
return (int) (o2.exponent - o1.exponent);
}
}
// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
private static final class Term {
long coefficient;
long exponent;
public Term(long c, long e) {
coefficient = c;
exponent = e;
}
public Term clone() {
return new Term(coefficient, exponent);
}
public Term multiply(Term term) {
return new Term(coefficient * term.coefficient, exponent + term.exponent);
}
public Term add(Term term) {
if ( exponent != term.exponent ) {
throw new RuntimeException("ERROR 102: Exponents not equal.");
}
return new Term(coefficient + term.coefficient, exponent);
}
public Term negate() {
return new Term(-coefficient, exponent);
}
public long degree() {
return exponent;
}
@Override
public String toString() {
if ( coefficient == 0 ) {
return "0";
}
if ( exponent == 0 ) {
return "" + coefficient;
}
if ( coefficient == 1 ) {
if ( exponent == 1 ) {
return "x";
}
else {
return "x^" + exponent;
}
}
if ( exponent == 1 ) {
return coefficient + "x";
}
return coefficient + "x^" + exponent;
}
}
}
|
Damm algorithm | Java from Kotlin | The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
;Task:
Verify the checksum, stored as last digit of an input.
| public class DammAlgorithm {
private static final int[][] table = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
};
private static boolean damm(String s) {
int interim = 0;
for (char c : s.toCharArray()) interim = table[interim][c - '0'];
return interim == 0;
}
public static void main(String[] args) {
int[] numbers = {5724, 5727, 112946, 112949};
for (Integer number : numbers) {
boolean isValid = damm(number.toString());
if (isValid) {
System.out.printf("%6d is valid\n", number);
} else {
System.out.printf("%6d is invalid\n", number);
}
}
}
} |
De Bruijn sequences | Java from C++ | {{DISPLAYTITLE:de Bruijn sequences}}
The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on
a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every
possible length-''n'' string (computer science, formal theory) on ''A'' occurs
exactly once as a contiguous substring.
Such a sequence is denoted by ''B''(''k'', ''n'') and has
length ''k''''n'', which is also the number of distinct substrings of
length ''n'' on ''A'';
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) / kn
distinct de Bruijn sequences ''B''(''k'', ''n'').
;Task:
For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last ''n'' digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
;Example:
A digital door lock with a 4-digit code would
have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).
Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to
open the lock.
Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.
;Task requirements:
:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
:::* Show the length of the generated de Bruijn sequence.
:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).
:::* Show the first and last '''130''' digits of the de Bruijn sequence.
:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.
:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
:* Reverse the de Bruijn sequence.
:* Again, perform the (above) verification test.
:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
:::* Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
;References:
:* Wikipedia entry: de Bruijn sequence.
:* MathWorld entry: de Bruijn sequence.
:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
public class DeBruijn {
public interface Recursable<T, U> {
void apply(T t, U u, Recursable<T, U> r);
}
public static <T, U> BiConsumer<T, U> recurse(Recursable<T, U> f) {
return (t, u) -> f.apply(t, u, f);
}
private static String deBruijn(int k, int n) {
byte[] a = new byte[k * n];
Arrays.fill(a, (byte) 0);
List<Byte> seq = new ArrayList<>();
BiConsumer<Integer, Integer> db = recurse((t, p, f) -> {
if (t > n) {
if (n % p == 0) {
for (int i = 1; i < p + 1; ++i) {
seq.add(a[i]);
}
}
} else {
a[t] = a[t - p];
f.apply(t + 1, p, f);
int j = a[t - p] + 1;
while (j < k) {
a[t] = (byte) (j & 0xFF);
f.apply(t + 1, t, f);
j++;
}
}
});
db.accept(1, 1);
StringBuilder sb = new StringBuilder();
for (Byte i : seq) {
sb.append("0123456789".charAt(i));
}
sb.append(sb.subSequence(0, n - 1));
return sb.toString();
}
private static boolean allDigits(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
private static void validate(String db) {
int le = db.length();
int[] found = new int[10_000];
Arrays.fill(found, 0);
List<String> errs = new ArrayList<>();
// Check all strings of 4 consecutive digits within 'db'
// to see if all 10,000 combinations occur without duplication.
for (int i = 0; i < le - 3; ++i) {
String s = db.substring(i, i + 4);
if (allDigits(s)) {
int n = Integer.parseInt(s);
found[n]++;
}
}
for (int i = 0; i < 10_000; ++i) {
if (found[i] == 0) {
errs.add(String.format(" PIN number %d is missing", i));
} else if (found[i] > 1) {
errs.add(String.format(" PIN number %d occurs %d times", i, found[i]));
}
}
if (errs.isEmpty()) {
System.out.println(" No errors found");
} else {
String pl = (errs.size() == 1) ? "" : "s";
System.out.printf(" %d error%s found:\n", errs.size(), pl);
errs.forEach(System.out::println);
}
}
public static void main(String[] args) {
String db = deBruijn(10, 4);
System.out.printf("The length of the de Bruijn sequence is %d\n\n", db.length());
System.out.printf("The first 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(0, 130));
System.out.printf("The last 130 digits of the de Bruijn sequence are: %s\n\n", db.substring(db.length() - 130));
System.out.println("Validating the de Bruijn sequence:");
validate(db);
StringBuilder sb = new StringBuilder(db);
String rdb = sb.reverse().toString();
System.out.println();
System.out.println("Validating the de Bruijn sequence:");
validate(rdb);
sb = new StringBuilder(db);
sb.setCharAt(4443, '.');
System.out.println();
System.out.println("Validating the overlaid de Bruijn sequence:");
validate(sb.toString());
}
} |
Deepcopy | Java | Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.
This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.
If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.
The task should show:
* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.
* Any limitations of the method.
* That the structure and its copy are different.
* Suitable links to external documentation for common libraries.
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class DeepCopy {
public static void main(String[] args) {
Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
Person p2 = p1;
System.out.printf("Demonstrate shallow copy. Both are the same object.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on both objects is changed.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
p2 = new Person(p1);
System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
p2 = (Person) deepCopy(p1);
System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
p2 = (Person) p1.clone();
System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
}
/**
* Makes a deep copy of any Java object that is passed.
*/
private static Object deepCopy(Object object) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream);
outputStrm.writeObject(object);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
return objInputStream.readObject();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static class Address implements Serializable, Cloneable {
private static final long serialVersionUID = -7073778041809445593L;
private String street;
private String city;
private String state;
private String postalCode;
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]";
}
public Address(String s, String c, String st, String p) {
street = s;
city = c;
state = st;
postalCode = p;
}
// Copy constructor
public Address(Address add) {
street = add.street;
city = add.city;
state = add.state;
postalCode = add.postalCode;
}
// Support Cloneable
@Override
public Object clone() {
return new Address(this);
}
}
public static class Person implements Serializable, Cloneable {
private static final long serialVersionUID = -521810583786595050L;
private String firstName;
private String lastName;
private Address address;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Address getAddress() {
return address;
}
@Override
public String toString() {
return "[first name=" + firstName + ", last name=" + lastName + ", address=" + address + "]";
}
public Person(String fn, String ln, Address add) {
firstName = fn;
lastName = ln;
address = add;
}
// Copy Constructor
public Person(Person person) {
firstName = person.firstName;
lastName = person.lastName;
address = new Address(person.address); // Invoke copy constructor of mutable sub-objects.
}
// Support Cloneable
@Override
public Object clone() {
return new Person(this);
}
}
}
|
Deming's funnel | Java | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
'''Stretch goal 2''': Show scatter plots of all four results.
;Further information:
* Further explanation and interpretation
* Video demonstration of the funnel experiment at the Mayo Clinic.
| Translation of [[Deming's_Funnel#Python|Python]] via [[Deming's_Funnel#D|D]]
|
Deming's funnel | Java 8 | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
'''Stretch goal 2''': Show scatter plots of all four results.
;Further information:
* Further explanation and interpretation
* Video demonstration of the funnel experiment at the Mayo Clinic.
| import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
} |
Department numbers | Java from Kotlin | There is a highly organized city that has decided to assign a number to each of their departments:
::* police department
::* sanitation department
::* fire department
Each department can have a number between '''1''' and '''7''' (inclusive).
The three department numbers are to be unique (different from each other) and must add up to '''12'''.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
;Task:
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| public class DepartmentNumbers {
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
System.out.println("------ ---------- ----");
int count = 0;
for (int i = 2; i <= 6; i += 2) {
for (int j = 1; j <= 7; ++j) {
if (j == i) continue;
for (int k = 1; k <= 7; ++k) {
if (k == i || k == j) continue;
if (i + j + k != 12) continue;
System.out.printf(" %d %d %d\n", i, j, k);
count++;
}
}
}
System.out.printf("\n%d valid combinations", count);
}
} |
Detect division by zero | Java | Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
| public static boolean except(double numer, double denom){
try{
int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math
return false;
}catch(ArithmeticException e){return true;}
} |
Determinant and permanent | Java | permanent of the matrix.
The determinant is given by
:: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i}
while the permanent is given by
:: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i}
In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.
;Related task:
* [[Permutations by swapping]]
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{ //i>x && j>y
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
} |
Determine if a string has all the same characters | Java | Given a character string (which may be empty, or have a length of zero characters):
::* create a function/procedure/routine to:
::::* determine if all the characters in the string are the same
::::* indicate if or which character is different from the previous character
::* display each string and its length (as the strings are being examined)
::* a zero-length (empty) string shall be considered as all the same character(s)
::* process the strings from left-to-right
::* if all the same character, display a message saying such
::* if not all the same character, then:
::::* display a message saying such
::::* display what character is different
::::* only the 1st different character need be displayed
::::* display where the different character is in the string
::::* the above messages can be part of a single message
::::* display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
:::* a string of length 0 (an empty string)
:::* a string of length 3 which contains three blanks
:::* a string of length 1 which contains: '''2'''
:::* a string of length 3 which contains: '''333'''
:::* a string of length 3 which contains: '''.55'''
:::* a string of length 6 which contains: '''tttTTT'''
:::* a string of length 9 with a blank in the middle: '''4444 444k'''
Show all output here on this page.
| public static void main(String[] args) {
String[] strings = {
"", " ", "2", "333", ".55", "tttTTT", "5", "4444 444k"
};
for (String string : strings)
System.out.println(printCompare(string));
}
static String printCompare(String string) {
String stringA = "'%s' %d".formatted(string, string.length());
Pattern pattern = Pattern.compile("(.)\\1*");
Matcher matcher = pattern.matcher(string);
StringBuilder stringB = new StringBuilder();
/* 'Matcher' works dynamically, so we'll have to denote a change */
boolean difference = false;
char character;
String newline = System.lineSeparator();
while (matcher.find()) {
if (matcher.start() != 0) {
character = matcher.group(1).charAt(0);
stringB.append(newline);
stringB.append(" Char '%s' (0x%x)".formatted(character, (int) character));
stringB.append(" @ index %d".formatted(matcher.start()));
difference = true;
}
}
if (!difference)
stringB.append(newline).append(" All characters are the same");
return stringA + stringB;
}
|
Determine if a string has all unique characters | Java | Given a character string (which may be empty, or have a length of zero characters):
::* create a function/procedure/routine to:
::::* determine if all the characters in the string are unique
::::* indicate if or which character is duplicated and where
::* display each string and its length (as the strings are being examined)
::* a zero-length (empty) string shall be considered as unique
::* process the strings from left-to-right
::* if unique, display a message saying such
::* if not unique, then:
::::* display a message saying such
::::* display what character is duplicated
::::* only the 1st non-unique character need be displayed
::::* display where "both" duplicated characters are in the string
::::* the above messages can be part of a single message
::::* display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
:::* a string of length 0 (an empty string)
:::* a string of length 1 which is a single period ('''.''')
:::* a string of length 6 which contains: '''abcABC'''
:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''
:::* a string of length 36 which ''doesn't'' contain the letter "oh":
:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''
Show all output here on this page.
| import java.util.HashMap;
import java.util.Map;
// Title: Determine if a string has all unique characters
public class StringUniqueCharacters {
public static void main(String[] args) {
System.out.printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions");
System.out.printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------");
for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) {
processString(s);
}
}
private static void processString(String input) {
Map<Character,Integer> charMap = new HashMap<>();
char dup = 0;
int index = 0;
int pos1 = -1;
int pos2 = -1;
for ( char key : input.toCharArray() ) {
index++;
if ( charMap.containsKey(key) ) {
dup = key;
pos1 = charMap.get(key);
pos2 = index;
break;
}
charMap.put(key, index);
}
String unique = dup == 0 ? "yes" : "no";
String diff = dup == 0 ? "" : "'" + dup + "'";
String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase();
String position = dup == 0 ? "" : pos1 + " " + pos2;
System.out.printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length(), unique, diff, hex, position);
}
}
|
Determine if a string is collapsible | Java | Determine if a character string is ''collapsible''.
And if so, collapse the string (by removing ''immediately repeated'' characters).
If a character string has ''immediately repeated'' character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An ''immediately repeated'' character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been ''duplicated character'', but that
might have ruled out (to some readers) triplicated characters *** or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}
;Examples:
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after ''collapsing'' the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
;Task:
Write a subroutine/function/procedure/routine*** to
locate ''repeated'' characters and ''collapse'' (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
:* the original string and its length
:* the resultant string and its length
:* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks)
;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>>
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
++
1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)
2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |
3 |..1111111111111111111111111111111111111111111111111111111111111117777888|
4 |I never give 'em hell, I just tell the truth, and they think it's hell. |
5 | --- Harry S Truman | <###### has many repeated blanks
+------------------------------------------------------------------------+
| // Title: Determine if a string is collapsible
public class StringCollapsible {
public static void main(String[] args) {
for ( String s : new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"}) {
String result = collapse(s);
System.out.printf("old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", s.length(), s, result.length(), result);
}
}
private static String collapse(String in) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) ) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Determine if a string is squeezable | Java | Determine if a character string is ''squeezable''.
And if so, squeeze the string (by removing any number of
a ''specified'' ''immediately repeated'' character).
This task is very similar to the task '''Determine if a character string is collapsible''' except
that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.
If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified ''immediately repeated'' character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been ''duplicated
character'', but that might have ruled out (to some readers) triplicated characters *** or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) '''PL/I''' BIF: '''squeeze'''.}
;Examples:
In the following character string with a specified ''immediately repeated'' character of '''e''':
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd '''e''' is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after ''squeezing'' the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character '''s''':
headmistressship
The "squeezed" string would be:
headmistreship
;Task:
Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character
and ''squeeze'' (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
:* the specified repeated character (to be searched for and possibly ''squeezed''):
:* the original string and its length
:* the resultant string and its length
:* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks)
;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>>
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( | a blank, a minus, a seven, a period)
++
1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)
2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-'
3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'
4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'
5 | --- Harry S Truman | (below) <###### has many repeated blanks
+------------------------------------------------------------------------+ |
|
|
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
* a blank
* a minus
* a lowercase '''r'''
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
| // Title: Determine if a string is squeezable
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"};
String[] testChar = new String[] {
" ",
"-",
"7",
".",
" -r",
"5",
"e",
"s"};
for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
String s = testStrings[testNum];
for ( char c : testChar[testNum].toCharArray() ) {
String result = squeeze(s, c);
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
}
}
}
private static String squeeze(String in, char include) {
StringBuilder sb = new StringBuilder();
for ( int i = 0 ; i < in.length() ; i++ ) {
if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
sb.append(in.charAt(i));
}
}
return sb.toString();
}
}
|
Determine if two triangles overlap | Java 8 | Determining if two triangles in the same plane overlap is an important topic in collision detection.
;Task:
Determine which of these pairs of triangles overlap in 2D:
:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| import java.util.function.BiFunction;
public class TriangleOverlap {
private static class Pair {
double first;
double second;
Pair(double first, double second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return String.format("(%s, %s)", first, second);
}
}
private static class Triangle {
Pair p1, p2, p3;
Triangle(Pair p1, Pair p2, Pair p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
@Override
public String toString() {
return String.format("Triangle: %s, %s, %s", p1, p2, p3);
}
}
private static double det2D(Triangle t) {
Pair p1 = t.p1;
Pair p2 = t.p2;
Pair p3 = t.p3;
return p1.first * (p2.second - p3.second)
+ p2.first * (p3.second - p1.second)
+ p3.first * (p1.second - p2.second);
}
private static void checkTriWinding(Triangle t, boolean allowReversed) {
double detTri = det2D(t);
if (detTri < 0.0) {
if (allowReversed) {
Pair a = t.p3;
t.p3 = t.p2;
t.p2 = a;
} else throw new RuntimeException("Triangle has wrong winding direction");
}
}
private static boolean boundaryCollideChk(Triangle t, double eps) {
return det2D(t) < eps;
}
private static boolean boundaryDoesntCollideChk(Triangle t, double eps) {
return det2D(t) <= eps;
}
private static boolean triTri2D(Triangle t1, Triangle t2) {
return triTri2D(t1, t2, 0.0, false, true);
}
private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) {
return triTri2D(t1, t2, eps, allowedReversed, true);
}
private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {
// Triangles must be expressed anti-clockwise
checkTriWinding(t1, allowedReversed);
checkTriWinding(t2, allowedReversed);
// 'onBoundary' determines whether points on boundary are considered as colliding or not
BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk;
Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3};
Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3};
// for each edge E of t1
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false;
}
// for each edge E of t2
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false;
}
// The triangles overlap
return true;
}
public static void main(String[] args) {
Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));
Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0));
System.out.printf("%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
// need to allow reversed for this pair to avoid exception
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0));
t2 = t1;
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2, 0.0, true)) {
System.out.println("overlap (reversed)");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));
t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1.p3 = new Pair(2.5, 5.0);
t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0));
t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0));
t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1));
System.out.printf("\n%s and\n%s\n", t1, t2);
System.out.println("which have only a single corner in contact, if boundary points collide");
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
System.out.printf("\n%s and\n%s\n", t1, t2);
System.out.println("which have only a single corner in contact, if boundary points do not collide");
if (triTri2D(t1, t2, 0.0, false, false)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
}
} |
Dice game probabilities | Java | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| import java.util.Random;
public class Dice{
private static int roll(int nDice, int nSides){
int sum = 0;
Random rand = new Random();
for(int i = 0; i < nDice; i++){
sum += rand.nextInt(nSides) + 1;
}
return sum;
}
private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){
int p1Wins = 0;
for(int i = 0; i < rolls; i++){
int p1Roll = roll(p1Dice, p1Sides);
int p2Roll = roll(p2Dice, p2Sides);
if(p1Roll > p2Roll) p1Wins++;
}
return p1Wins;
}
public static void main(String[] args){
int p1Dice = 9; int p1Sides = 4;
int p2Dice = 6; int p2Sides = 6;
int rolls = 10000;
int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 10000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 9; p1Sides = 4;
p2Dice = 6; p2Sides = 6;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
} |
Digital root | Java | The digital root, X, of a number, n, is calculated:
: find X as the sum of the digits of n
: find a new X by summing the digits of X, repeating until X has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
:627615 has additive persistence 2 and digital root of 9;
:39390 has additive persistence 2 and digital root of 6;
:588225 has additive persistence 2 and digital root of 3;
:393900588225 has additive persistence 2 and digital root of 9;
The digital root may be calculated in bases other than 10.
;See:
* [[Casting out nines]] for this wiki's use of this procedure.
* [[Digital root/Multiplicative digital root]]
* [[Sum digits of an integer]]
* Digital root sequence on OEIS
* Additive persistence sequence on OEIS
* [[Iterated digits squaring]]
| import java.math.BigInteger;
class DigitalRoot
{
public static int[] calcDigitalRoot(String number, int base)
{
BigInteger bi = new BigInteger(number, base);
int additivePersistence = 0;
if (bi.signum() < 0)
bi = bi.negate();
BigInteger biBase = BigInteger.valueOf(base);
while (bi.compareTo(biBase) >= 0)
{
number = bi.toString(base);
bi = BigInteger.ZERO;
for (int i = 0; i < number.length(); i++)
bi = bi.add(new BigInteger(number.substring(i, i + 1), base));
additivePersistence++;
}
return new int[] { additivePersistence, bi.intValue() };
}
public static void main(String[] args)
{
for (String arg : args)
{
int[] results = calcDigitalRoot(arg, 10);
System.out.println(arg + " has additive persistence " + results[0] + " and digital root of " + results[1]);
}
}
} |
Disarium numbers | Java | A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
;E.G.
'''135''' is a '''Disarium number''':
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of '''Disarium numbers'''.
;Task
* Find and display the first 18 '''Disarium numbers'''.
;Stretch
* Find and display all 20 '''Disarium numbers'''.
;See also
;* Geeks for Geeks - Disarium numbers
;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
;* Related task: Narcissistic decimal number
;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
| import java.lang.Math;
public class DisariumNumbers {
public static boolean is_disarium(int num) {
int n = num;
int len = Integer.toString(n).length();
int sum = 0;
int i = 1;
while (n > 0) {
sum += Math.pow(n % 10, len - i + 1);
n /= 10;
i ++;
}
return sum == num;
}
public static void main(String[] args) {
int i = 0;
int count = 0;
while (count <= 18) {
if (is_disarium(i)) {
System.out.printf("%d ", i);
count++;
}
i++;
}
System.out.printf("%s", "\n");
}
}
|
Display a linear combination | Java from Kotlin | Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots).
Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is:
:\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots
where \alpha^{i_k}\neq 0
The output must comply to the following rules:
* don't show null terms, unless the whole combination is null.
::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.
* don't show scalars when they are equal to one or minus one.
::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.
* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| import java.util.Arrays;
public class LinearCombination {
private static String linearCombo(int[] c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.length; ++i) {
if (c[i] == 0) continue;
String op;
if (c[i] < 0 && sb.length() == 0) {
op = "-";
} else if (c[i] < 0) {
op = " - ";
} else if (c[i] > 0 && sb.length() == 0) {
op = "";
} else {
op = " + ";
}
int av = Math.abs(c[i]);
String coeff = av == 1 ? "" : "" + av + "*";
sb.append(op).append(coeff).append("e(").append(i + 1).append(')');
}
if (sb.length() == 0) {
return "0";
}
return sb.toString();
}
public static void main(String[] args) {
int[][] combos = new int[][]{
new int[]{1, 2, 3},
new int[]{0, 1, 2, 3},
new int[]{1, 0, 3, 4},
new int[]{1, 2, 0},
new int[]{0, 0, 0},
new int[]{0},
new int[]{1, 1, 1},
new int[]{-1, -1, -1},
new int[]{-1, -2, 0, -3},
new int[]{-1},
};
for (int[] c : combos) {
System.out.printf("%-15s -> %s\n", Arrays.toString(c), linearCombo(c));
}
}
} |
Distance and Bearing | Java | It is very important in aviation to have knowledge of the nearby airports at any time in flight.
;Task:
Determine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.
Use the non-commercial data from openflights.org airports.dat as reference.
A request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ).
Your report should contain the following information from table airports.dat (column shown in brackets):
Name(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8).
Distance is measured in nautical miles (NM). Resolution is 0.1 NM.
Bearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg.
;See:
:* openflights.org/data: Airport, airline and route data
:* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points
| // The Airport class holds each airport object
package distanceAndBearing;
public class Airport {
private String airport;
private String country;
private String icao;
private double lat;
private double lon;
public String getAirportName() { return this.airport; }
public void setAirportName(String airport) { this.airport = airport; }
public String getCountry() { return this.country; }
public void setCountry(String country) { this.country = country; }
public String getIcao() { return this.icao; }
public void setIcao(String icao) { this.icao = icao; }
public double getLat() { return this.lat; }
public void setLat(double lat) { this.lat = lat; }
public double getLon() { return this.lon; }
public void setLon(double lon) { this.lon = lon; }
@Override
public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();}
}
// The DistanceAndBearing class does all the work.
package distanceAndBearing;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class DistanceAndBearing {
private final double earthRadius = 6371;
private File datFile;
private List<Airport> airports;
public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }
public boolean readFile(String filename) {
this.datFile = new File(filename);
try {
Scanner fileScanner = new Scanner(datFile);
String line;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
line = line.replace(", ", "; "); // There are some commas in airport names in the dat
// file
line = line.replace(",\",\"", "\",\""); // There are some airport names that
// end in a comma in the dat file
String[] parts = line.split(",");
Airport airport = new Airport();
airport.setAirportName(parts[1].replace("\"", "")); // Remove the double quotes from the string
airport.setCountry(parts[3].replace("\"", "")); // Remove the double quotes from the string
airport.setIcao(parts[5].replace("\"", "")); // Remove the double quotes from the string
airport.setLat(Double.valueOf(parts[6]));
airport.setLon(Double.valueOf(parts[7]));
this.airports.add(airport);
}
fileScanner.close();
return true; // Return true if the read was successful
} catch (Exception e) {
e.printStackTrace();
return false; // Return false if the read was not successful
}}
public double[] calculate(double lat1, double lon1, double lat2, double lon2) {
double[] results = new double[2];
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double rlat1 = Math.toRadians(lat1);
double rlat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2)
+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);
double c = 2 * Math.asin(Math.sqrt(a));
double distance = earthRadius * c;
DecimalFormat df = new DecimalFormat("#0.00");
distance = Double.valueOf(df.format(distance));
results[0] = distance;
double X = Math.cos(rlat2) * Math.sin(dLon);
double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);
double heading = Math.atan2(X, Y);
heading = Math.toDegrees(heading);
results[1] = heading;
return results;
}
public Airport searchByName(final String name) {
Airport airport = new Airport();
List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))
.collect(Collectors.toList());
airport = results.get(0);
return airport;
}
public List<Airport> findClosestAirports(double lat, double lon) {
// TODO Auto-generated method stub
Map<Double, Airport> airportDistances = new HashMap<>();
Map<Double, Airport> airportHeading = new HashMap<>();
List<Airport> closestAirports = new ArrayList<Airport>();
// This loop finds the distance and heading for every airport and saves them
// into two separate Maps
for (Airport ap : this.airports) {
double[] result = calculate(lat, lon, ap.getLat(), ap.getLon());
airportDistances.put(result[0], ap);
airportHeading.put(result[1], ap);
}
// Get the keyset from the distance map and sort it.
ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());
Collections.sort(distances);
// Get the first 20 airports by finding the value in the distance map for
// each distance in the sorted Arraylist. Then get the airport name, and
// use that to search for the airport in the airports List.
// Save that into a new List
for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}
// Find the distance and heading for each of the top 20 airports.
Map<String, Double> distanceMap = new HashMap<>();
for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);}
Map<String, Double> headingMap = new HashMap<>();
for (Double d : airportHeading.keySet()) {
double d2 = d;
if(d2<0){d2+=360'}
headingMap.put(airportHeading.get(d).getAirportName(), d2); }
// Print the results.
System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing");
System.out.println("-----------------------------------------------------------------------------------------------------------");
int i = 0;
for (Airport a : closestAirports) {
System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));
}
return closestAirports;
}
}
|
Diversity prediction theorem | Java from Kotlin | The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''.
Therefore, when the diversity in a group is large, the error of the crowd is small.
;Definitions:
::* Average Individual Error: Average of the individual squared errors
::* Collective Error: Squared error of the collective prediction
::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then
:::::: Collective Error = Average Individual Error - Prediction Diversity
;Task:
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
:::* the true value and the crowd estimates
:::* the average error
:::* the crowd error
:::* the prediction diversity
Use (at least) these two examples:
:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''
:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''
;Also see:
:* Wikipedia entry: Wisdom of the crowd
:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
| import java.util.Arrays;
public class DiversityPredictionTheorem {
private static double square(double d) {
return d * d;
}
private static double averageSquareDiff(double d, double[] predictions) {
return Arrays.stream(predictions)
.map(it -> square(it - d))
.average()
.orElseThrow();
}
private static String diversityTheorem(double truth, double[] predictions) {
double average = Arrays.stream(predictions)
.average()
.orElseThrow();
return String.format("average-error : %6.3f%n", averageSquareDiff(truth, predictions))
+ String.format("crowd-error : %6.3f%n", square(truth - average))
+ String.format("diversity : %6.3f%n", averageSquareDiff(average, predictions));
}
public static void main(String[] args) {
System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0}));
System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0}));
}
} |
Doomsday rule | Java | About the task
John Conway (1937-2020), was a mathematician who also invented several mathematically
oriented computer pastimes, such as the famous Game of Life cellular automaton program.
Dr. Conway invented a simple algorithm for finding the day of the week, given any date.
The algorithm was based on calculating the distance of a given date from certain
"anchor days" which follow a pattern for the day of the week upon which they fall.
; Algorithm
The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and
doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7
which, for 2021, is 0 (Sunday).
To calculate the day of the week, we then count days from a close doomsday,
with these as charted here by month, then add the doomsday for the year,
then get the remainder after dividing by 7. This should give us the number
corresponding to the day of the week for that date.
Month Doomsday Dates for Month
--------------------------------------------
January (common years) 3, 10, 17, 24, 31
January (leap years) 4, 11, 18, 25
February (common years) 7, 14, 21, 28
February (leap years) 1, 8, 15, 22, 29
March 7, 14, 21, 28
April 4, 11, 18, 25
May 2, 9, 16, 23, 30
June 6, 13, 20, 27
July 4, 11, 18, 25
August 1, 8, 15, 22, 29
September 5, 12, 19, 26
October 3, 10, 17, 24, 31
November 7, 14, 21, 28
December 5, 12, 19, 26
; Task
Given the following dates:
* 1800-01-06 (January 6, 1800)
* 1875-03-29 (March 29, 1875)
* 1915-12-07 (December 7, 1915)
* 1970-12-23 (December 23, 1970)
* 2043-05-14 (May 14, 2043)
* 2077-02-12 (February 12, 2077)
* 2101-04-02 (April 2, 2101)
Use Conway's Doomsday rule to calculate the day of the week for each date.
; see also
* Doomsday rule
* Tomorrow is the Day After Doomsday (p.28)
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
} |
Dot product | Java | Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
:::: [1, 3, -5] and
:::: [4, -2, -1]
If implementing the dot product of two vectors directly:
:::* each vector must be the same length
:::* multiply corresponding terms from each vector
:::* sum the products (to produce the answer)
;Related task:
* [[Vector products]]
| public class DotProduct {
public static void main(String[] args) {
double[] a = {1, 3, -5};
double[] b = {4, -2, -1};
System.out.println(dotProd(a,b));
}
public static double dotProd(double[] a, double[] b){
if(a.length != b.length){
throw new IllegalArgumentException("The dimensions have to be equal!");
}
double sum = 0;
for(int i = 0; i < a.length; i++){
sum += a[i] * b[i];
}
return sum;
}
} |
Draw a clock | Java 8 | Draw a clock.
More specific:
# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
;Key points
* animate simple object
* timed event
* polling system resources
* code clarity
| import java.awt.*;
import java.awt.event.*;
import static java.lang.Math.*;
import java.time.LocalTime;
import javax.swing.*;
class Clock extends JPanel {
final float degrees06 = (float) (PI / 30);
final float degrees30 = degrees06 * 5;
final float degrees90 = degrees30 * 3;
final int size = 590;
final int spacing = 40;
final int diameter = size - 2 * spacing;
final int cx = diameter / 2 + spacing;
final int cy = diameter / 2 + spacing;
public Clock() {
setPreferredSize(new Dimension(size, size));
setBackground(Color.white);
new Timer(1000, (ActionEvent e) -> {
repaint();
}).start();
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawFace(g);
final LocalTime time = LocalTime.now();
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
float angle = degrees90 - (degrees06 * second);
drawHand(g, angle, diameter / 2 - 30, Color.red);
float minsecs = (minute + second / 60.0F);
angle = degrees90 - (degrees06 * minsecs);
drawHand(g, angle, diameter / 3 + 10, Color.black);
float hourmins = (hour + minsecs / 60.0F);
angle = degrees90 - (degrees30 * hourmins);
drawHand(g, angle, diameter / 4 + 10, Color.black);
}
private void drawFace(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(Color.white);
g.fillOval(spacing, spacing, diameter, diameter);
g.setColor(Color.black);
g.drawOval(spacing, spacing, diameter, diameter);
}
private void drawHand(Graphics2D g, float angle, int radius, Color color) {
int x = cx + (int) (radius * cos(angle));
int y = cy - (int) (radius * sin(angle));
g.setColor(color);
g.drawLine(cx, cy, x, y);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Clock");
f.setResizable(false);
f.add(new Clock(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Draw a rotating cube | Java | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
;Related tasks
* Draw a cuboid
* write language name in 3D ASCII
| import java.awt.*;
import java.awt.event.ActionEvent;
import static java.lang.Math.*;
import javax.swing.*;
public class RotatingCube extends JPanel {
double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
{1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};
int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};
public RotatingCube() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
scale(100);
rotateCube(PI / 4, atan(sqrt(2)));
new Timer(17, (ActionEvent e) -> {
rotateCube(PI / 180, 0);
repaint();
}).start();
}
final void scale(double s) {
for (double[] node : nodes) {
node[0] *= s;
node[1] *= s;
node[2] *= s;
}
}
final void rotateCube(double angleX, double angleY) {
double sinX = sin(angleX);
double cosX = cos(angleX);
double sinY = sin(angleY);
double cosY = cos(angleY);
for (double[] node : nodes) {
double x = node[0];
double y = node[1];
double z = node[2];
node[0] = x * cosX - z * sinX;
node[2] = z * cosX + x * sinX;
z = node[2];
node[1] = y * cosY - z * sinY;
node[2] = z * cosY + y * sinY;
}
}
void drawCube(Graphics2D g) {
g.translate(getWidth() / 2, getHeight() / 2);
for (int[] edge : edges) {
double[] xy1 = nodes[edge[0]];
double[] xy2 = nodes[edge[1]];
g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
(int) round(xy2[0]), (int) round(xy2[1]));
}
for (double[] node : nodes)
g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawCube(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Rotating Cube");
f.setResizable(false);
f.add(new RotatingCube(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Draw a sphere | Java from C | {{requires|Graphics}}
;Task:
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
;Related tasks:
* draw a cuboid
* draw a rotating cube
* write language name in 3D ASCII
* draw a Deathstar
| public class Sphere{
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
static double[] light = { 30, 30, -50 };
private static void normalize(double[] v){
double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
private static double dot(double[] x, double[] y){
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
public static void drawSphere(double R, double k, double ambient){
double[] vec = new double[3];
for(int i = (int)Math.floor(-R); i <= (int)Math.ceil(R); i++){
double x = i + .5;
for(int j = (int)Math.floor(-2 * R); j <= (int)Math.ceil(2 * R); j++){
double y = j / 2. + .5;
if(x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = Math.sqrt(R * R - x * x - y * y);
normalize(vec);
double b = Math.pow(dot(light, vec), k) + ambient;
int intensity = (b <= 0) ?
shades.length - 2 :
(int)Math.max((1 - b) * (shades.length - 1), 0);
System.out.print(shades[intensity]);
} else
System.out.print(' ');
}
System.out.println();
}
}
public static void main(String[] args){
normalize(light);
drawSphere(20, 4, .1);
drawSphere(10, 2, .4);
}
} |
Dutch national flag problem | Java | The Dutch national flag is composed of three coloured bands in the order:
::* red (top)
::* then white, and
::* lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
;Task
# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.
# Sort the balls in a way idiomatic to your language.
# Check the sorted balls ''are'' in the order of the Dutch national flag.
;C.f.:
* Dutch national flag problem
* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| import java.util.Arrays;
import java.util.Random;
public class DutchNationalFlag {
enum DutchColors {
RED, WHITE, BLUE
}
public static void main(String[] args){
DutchColors[] balls = new DutchColors[12];
DutchColors[] values = DutchColors.values();
Random rand = new Random();
for (int i = 0; i < balls.length; i++)
balls[i]=values[rand.nextInt(values.length)];
System.out.println("Before: " + Arrays.toString(balls));
Arrays.sort(balls);
System.out.println("After: " + Arrays.toString(balls));
boolean sorted = true;
for (int i = 1; i < balls.length; i++ ){
if (balls[i-1].compareTo(balls[i]) > 0){
sorted=false;
break;
}
}
System.out.println("Correctly sorted: " + sorted);
}
} |
EKG sequence convergence | Java | The sequence is from the natural numbers and is defined by:
* a(1) = 1;
* a(2) = Start = 2;
* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).
Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call:
* The sequence described above , starting 1, 2, ... the EKG(2) sequence;
* the sequence starting 1, 3, ... the EKG(3) sequence;
* ... the sequence starting 1, N, ... the EKG(N) sequence.
;Convergence
If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.
EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).
;Task:
# Calculate and show here the first 10 members of EKG(2).
# Calculate and show here the first 10 members of EKG(5).
# Calculate and show here the first 10 members of EKG(7).
# Calculate and show here the first 10 members of EKG(9).
# Calculate and show here the first 10 members of EKG(10).
# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').
;Related Tasks:
# [[Greatest common divisor]]
# [[Sieve of Eratosthenes]]
;Reference:
* The EKG Sequence and the Tree of Numbers. (Video).
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EKGSequenceConvergence {
public static void main(String[] args) {
System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10].");
for ( int i : new int[] {2, 5, 7, 9, 10} ) {
System.out.printf("EKG[%d] = %s%n", i, ekg(i, 10));
}
System.out.println("Calculate and show here at which term EKG[5] and EKG[7] converge.");
List<Integer> ekg5 = ekg(5, 100);
List<Integer> ekg7 = ekg(7, 100);
for ( int i = 1 ; i < ekg5.size() ; i++ ) {
if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) {
System.out.printf("EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n", 5, i+1, 7, i+1, ekg5.get(i));
break;
}
}
}
// Same last element, and all elements in sequence are identical
private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) {
List<Integer> list1 = new ArrayList<>(seq1.subList(0, n));
Collections.sort(list1);
List<Integer> list2 = new ArrayList<>(seq2.subList(0, n));
Collections.sort(list2);
for ( int i = 0 ; i < n ; i++ ) {
if ( list1.get(i) != list2.get(i) ) {
return false;
}
}
return true;
}
// Without HashMap to identify seen terms, need to examine list.
// Calculating 3000 terms in this manner takes 10 seconds
// With HashMap to identify the seen terms, calculating 3000 terms takes .1 sec.
private static List<Integer> ekg(int two, int maxN) {
List<Integer> result = new ArrayList<>();
result.add(1);
result.add(two);
Map<Integer,Integer> seen = new HashMap<>();
seen.put(1, 1);
seen.put(two, 1);
int minUnseen = two == 2 ? 3 : 2;
int prev = two;
for ( int n = 3 ; n <= maxN ; n++ ) {
int test = minUnseen - 1;
while ( true ) {
test++;
if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) {
result.add(test);
seen.put(test, n);
prev = test;
if ( minUnseen == test ) {
do {
minUnseen++;
} while ( seen.containsKey(minUnseen) );
}
break;
}
}
}
return result;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Earliest difference between prime gaps | Java | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer.
{|class="wikitable"
!gap!!minimalstartingprime!!endingprime
|-
|2||3||5
|-
|4||7||11
|-
|6||23||29
|-
|8||89||97
|-
|10||139||149
|-
|12||199||211
|-
|14||113||127
|-
|16||1831||1847
|-
|18||523||541
|-
|20||887||907
|-
|22||1129||1151
|-
|24||1669||1693
|-
|26||2477||2503
|-
|28||2971||2999
|-
|30||4297||4327
|}
This task involves locating the minimal primes corresponding to those gaps.
Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30:
For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent.
;Task
For each order of magnitude '''m''' from '''101''' through '''106''':
* Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than '''m'''.
;E.G.
For an '''m''' of '''101''';
The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < '''101''' so keep going.
The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > '''101''' so this the earliest adjacent gap difference > '''101'''.
;Stretch goal
* Do the same for '''107''' and '''108''' (and higher?) orders of magnitude
Note: the earliest value found for each order of magnitude may not be unique, in fact, ''is'' not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
| import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference > %,d between adjacent prime gap starting primes:\n"
+ "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
} |
Eban numbers | Java from Kotlin | Definition:
An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter '''e''' are banned.
The American version of spelling numbers will be used here (as opposed to the British).
'''2,000,000,000''' is two billion, ''not'' two milliard.
Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.
This will allow optimizations to be used.
;Task:
:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count
:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count
:::* show a count of all eban numbers up and including '''10,000'''
:::* show a count of all eban numbers up and including '''100,000'''
:::* show a count of all eban numbers up and including '''1,000,000'''
:::* show a count of all eban numbers up and including '''10,000,000'''
:::* show all output here.
;See also:
:* The MathWorld entry: eban numbers.
:* The OEIS entry: A6933, eban numbers.
:* [[Number names]].
| import java.util.List;
public class Main {
private static class Range {
int start;
int end;
boolean print;
public Range(int s, int e, boolean p) {
start = s;
end = e;
print = p;
}
}
public static void main(String[] args) {
List<Range> rgs = List.of(
new Range(2, 1000, true),
new Range(1000, 4000, true),
new Range(2, 10_000, false),
new Range(2, 100_000, false),
new Range(2, 1_000_000, false),
new Range(2, 10_000_000, false),
new Range(2, 100_000_000, false),
new Range(2, 1_000_000_000, false)
);
for (Range rg : rgs) {
if (rg.start == 2) {
System.out.printf("eban numbers up to and including %d\n", rg.end);
} else {
System.out.printf("eban numbers between %d and %d\n", rg.start, rg.end);
}
int count = 0;
for (int i = rg.start; i <= rg.end; ++i) {
int b = i / 1_000_000_000;
int r = i % 1_000_000_000;
int m = r / 1_000_000;
r = i % 1_000_000;
int t = r / 1_000;
r %= 1_000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (rg.print) System.out.printf("%d ", i);
count++;
}
}
}
}
}
if (rg.print) {
System.out.println();
}
System.out.printf("count = %d\n\n", count);
}
}
} |
Eertree | Java from D | An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both ''tries'' and ''suffix trees''.
See links below.
;Task:
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
;See also:
* Wikipedia entry: trie.
* Wikipedia entry: suffix tree
* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
// nested methods are a pain, even if lambdas make that possible for Java
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
} |
Egyptian division | Java | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of [[Ethiopian multiplication]]
'''Algorithm:'''
Given two numbers where the '''dividend''' is to be divided by the '''divisor''':
# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
# Continue with successive i'th rows of 2^i and 2^i * divisor.
# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''
# Consider each row of the table, in the ''reverse'' order of its construction.
# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).
'''Example: 580 / 34'''
''' Table creation: '''
::: {| class="wikitable"
! powers_of_2
! doublings
|-
| 1
| 34
|-
| 2
| 68
|-
| 4
| 136
|-
| 8
| 272
|-
| 16
| 544
|}
''' Initialization of sums: '''
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| 16
| 544
|
|
|-
|
|
| 0
| 0
|}
''' Considering table rows, bottom-up: '''
When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
| 16
| 544
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
| 16
| 544
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
| 16
| 544
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
| 16
| 544
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| '''1'''
| '''34'''
| 17
| 578
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
;Answer:
So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.
;Task:
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.
;Related tasks:
:* Egyptian fractions
;References:
:* Egyptian Number System
| import java.util.ArrayList;
import java.util.List;
public class EgyptianDivision {
/**
* Runs the method and divides 580 by 34
*
* @param args not used
*/
public static void main(String[] args) {
divide(580, 34);
}
/**
* Divides <code>dividend</code> by <code>divisor</code> using the Egyptian Division-Algorithm and prints the
* result to the console
*
* @param dividend
* @param divisor
*/
public static void divide(int dividend, int divisor) {
List<Integer> powersOf2 = new ArrayList<>();
List<Integer> doublings = new ArrayList<>();
//populate the powersof2- and doublings-columns
int line = 0;
while ((Math.pow(2, line) * divisor) <= dividend) { //<- could also be done with a for-loop
int powerOf2 = (int) Math.pow(2, line);
powersOf2.add(powerOf2);
doublings.add(powerOf2 * divisor);
line++;
}
int answer = 0;
int accumulator = 0;
//Consider the rows in reverse order of their construction (from back to front of the List<>s)
for (int i = powersOf2.size() - 1; i >= 0; i--) {
if (accumulator + doublings.get(i) <= dividend) {
accumulator += doublings.get(i);
answer += powersOf2.get(i);
}
}
System.out.println(String.format("%d, remainder %d", answer, dividend - accumulator));
}
}
|
Elementary cellular automaton | Java 8 | An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
;Task:
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of [[one-dimensional cellular automata]].
;See also
* Cellular automata (natureofcode.com)
| import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.Timer;
public class WolframCA extends JPanel {
final int[] ruleSet = {30, 45, 50, 57, 62, 70, 73, 75, 86, 89, 90, 99,
101, 105, 109, 110, 124, 129, 133, 135, 137, 139, 141, 164,170, 232};
byte[][] cells;
int rule = 0;
public WolframCA() {
Dimension dim = new Dimension(900, 450);
setPreferredSize(dim);
setBackground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, 28));
cells = new byte[dim.height][dim.width];
cells[0][dim.width / 2] = 1;
new Timer(5000, (ActionEvent e) -> {
rule++;
if (rule == ruleSet.length)
rule = 0;
repaint();
}).start();
}
private byte rules(int lhs, int mid, int rhs) {
int idx = (lhs << 2 | mid << 1 | rhs);
return (byte) (ruleSet[rule] >> idx & 1);
}
void drawCa(Graphics2D g) {
g.setColor(Color.black);
for (int r = 0; r < cells.length - 1; r++) {
for (int c = 1; c < cells[r].length - 1; c++) {
byte lhs = cells[r][c - 1];
byte mid = cells[r][c];
byte rhs = cells[r][c + 1];
cells[r + 1][c] = rules(lhs, mid, rhs); // next generation
if (cells[r][c] == 1) {
g.fillRect(c, r, 1, 1);
}
}
}
}
void drawLegend(Graphics2D g) {
String s = String.valueOf(ruleSet[rule]);
int sw = g.getFontMetrics().stringWidth(s);
g.setColor(Color.white);
g.fillRect(16, 5, 55, 30);
g.setColor(Color.darkGray);
g.drawString(s, 16 + (55 - sw) / 2, 30);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawCa(g);
drawLegend(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Wolfram CA");
f.setResizable(false);
f.add(new WolframCA(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Elliptic curve arithmetic | Java from D | digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:
:::: y^2 = x^3 + a x + b
'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
:::: a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:
:::: P + Q + R = 0
Here '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.
''Hint'': You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''.
''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).
| import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b = %s%n", c);
Pt d = c.neg();
System.out.printf("d = -c = %s%n", d);
System.out.printf("c + d = %s%n", c.plus(d));
System.out.printf("a + b + d = %s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 = %s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
} |
Empty directory | Java 7+ | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
| import java.nio.file.Paths;
//... other class code here
public static boolean isEmptyDir(String dirName){
return Paths.get(dirName).toFile().listFiles().length == 0;
} |
Empty string | Java | Languages may have features for dealing specifically with empty strings
(those containing no characters).
;Task:
::* Demonstrate how to assign an empty string to a variable.
::* Demonstrate how to check that a string is empty.
::* Demonstrate how to check that a string is not empty.
| String s = "";
if(s != null && s.isEmpty()){//optionally, instead of "s.isEmpty()": "s.length() == 0" or "s.equals("")"
System.out.println("s is empty");
}else{
System.out.println("s is not empty");
} |
Entropy/Narcissist | Java | Write a computer program that computes and shows its own [[entropy]].
;Related Tasks:
:* [[Fibonacci_word]]
:* [[Entropy]]
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
|
Equilibrium index | Java 1.5+ | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence A:
::::: A_0 = -7
::::: A_1 = 1
::::: A_2 = 5
::::: A_3 = 2
::::: A_4 = -4
::::: A_5 = 3
::::: A_6 = 0
3 is an equilibrium index, because:
::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6
6 is also an equilibrium index, because:
::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence A.
;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| public class Equlibrium {
public static void main(String[] args) {
int[] sequence = {-7, 1, 5, 2, -4, 3, 0};
equlibrium_indices(sequence);
}
public static void equlibrium_indices(int[] sequence){
//find total sum
int totalSum = 0;
for (int n : sequence) {
totalSum += n;
}
//compare running sum to remaining sum to find equlibrium indices
int runningSum = 0;
for (int i = 0; i < sequence.length; i++) {
int n = sequence[i];
if (totalSum - runningSum - n == runningSum) {
System.out.println(i);
}
runningSum += n;
}
}
}
|
Erdös-Selfridge categorization of primes | Java | A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.
The task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category.
| import java.util.*;
public class ErdosSelfridge {
private int[] primes;
private int[] category;
public static void main(String[] args) {
ErdosSelfridge es = new ErdosSelfridge(1000000);
System.out.println("First 200 primes:");
for (var e : es.getPrimesByCategory(200).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %d:\n", category);
for (int i = 0, n = primes.size(); i != n; ++i)
System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' ');
System.out.printf("\n\n");
}
System.out.println("First 1,000,000 primes:");
for (var e : es.getPrimesByCategory(1000000).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category,
primes.get(0), primes.get(primes.size() - 1), primes.size());
}
}
private ErdosSelfridge(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);
List<Integer> primeList = new ArrayList<>();
for (int i = 0; i < limit; ++i)
primeList.add(primeGen.nextPrime());
primes = new int[primeList.size()];
for (int i = 0; i < primes.length; ++i)
primes[i] = primeList.get(i);
category = new int[primes.length];
}
private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {
Map<Integer, List<Integer>> result = new TreeMap<>();
for (int i = 0; i < limit; ++i) {
var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());
p.add(primes[i]);
}
return result;
}
private int getCategory(int index) {
if (category[index] != 0)
return category[index];
int maxCategory = 0;
int n = primes[index] + 1;
for (int i = 0; n > 1; ++i) {
int p = primes[i];
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + getCategory(i);
maxCategory = Math.max(maxCategory, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));
maxCategory = Math.max(maxCategory, category);
}
category[index] = maxCategory;
return maxCategory;
}
private int getIndex(int prime) {
return Arrays.binarySearch(primes, prime);
}
} |
Erdős-Nicolas numbers | Java | Definition
An perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.
;Examples
24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.
6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).
48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.
;Task
Find and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.
;Stretch
Do the same for any further Erdos-Nicolas numbers which you have the patience for.
;Note
As all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.
;Reference
* OEIS:A194472 - Erdos-Nicolas numbers
| import java.util.Arrays;
public final class ErdosNicolasNumbers {
public static void main(String[] aArgs) {
final int limit = 100_000_000;
int[] divisorSum = new int[limit + 1];
int[] divisorCount = new int[limit + 1];
Arrays.fill(divisorSum, 1);
Arrays.fill(divisorCount, 1);
for ( int index = 2; index <= limit / 2; index++ ) {
for ( int number = 2 * index; number <= limit; number += index ) {
if ( divisorSum[number] == number ) {
System.out.println(String.format("%8d", number) + " equals the sum of its first "
+ String.format("%3d", divisorCount[number]) + " divisors");
}
divisorSum[number] += index;
divisorCount[number]++;
}
}
}
}
|
Esthetic numbers | Java from Kotlin | An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.
;E.G.
:* '''12''' is an esthetic number. One and two differ by 1.
:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.
:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
;Task
:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.
:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.
;Related task:
* numbers with equal rises and falls
;See also:
:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
:;*Numbers Aplenty - Esthetic numbers
:;*Geeks for Geeks - Stepping numbers
| import java.util.ArrayList;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class EstheticNumbers {
interface RecTriConsumer<A, B, C> {
void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);
}
private static boolean isEsthetic(long n, long b) {
if (n == 0) {
return false;
}
var i = n % b;
var n2 = n / b;
while (n2 > 0) {
var j = n2 % b;
if (Math.abs(i - j) != 1) {
return false;
}
n2 /= b;
i = j;
}
return true;
}
private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {
var esths = new ArrayList<Long>();
var dfs = new RecTriConsumer<Long, Long, Long>() {
public void accept(Long n, Long m, Long i) {
accept(this, n, m, i);
}
@Override
public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {
if (n <= i && i <= m) {
esths.add(i);
}
if (i == 0 || i > m) {
return;
}
var d = i % 10;
var i1 = i * 10 + d - 1;
var i2 = i1 + 2;
if (d == 0) {
f.accept(f, n, m, i2);
} else if (d == 9) {
f.accept(f, n, m, i1);
} else {
f.accept(f, n, m, i1);
f.accept(f, n, m, i2);
}
}
};
LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));
var le = esths.size();
System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m);
if (all) {
for (int i = 0; i < esths.size(); i++) {
System.out.printf("%d ", esths.get(i));
if ((i + 1) % perLine == 0) {
System.out.println();
}
}
} else {
for (int i = 0; i < perLine; i++) {
System.out.printf("%d ", esths.get(i));
}
System.out.println();
System.out.println("............");
for (int i = le - perLine; i < le; i++) {
System.out.printf("%d ", esths.get(i));
}
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
IntStream.rangeClosed(2, 16).forEach(b -> {
System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b);
var n = 1L;
var c = 0L;
while (c < 6 * b) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
System.out.printf("%s ", Long.toString(n, b));
}
}
n++;
}
System.out.println();
});
System.out.println();
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);
listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);
listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);
listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);
}
} |
Euclid-Mullin sequence | Java | Definition
The Euclid-Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements.
The first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.
Although intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.
;Task
Compute and show here the first '''16''' elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.
;Stretch goal
Compute the next '''11''' elements of the sequence.
;Reference
OEIS sequence A000945
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class EulerMullinSequence {
public static void main(String[] aArgs) {
primes = listPrimesUpTo(1_000_000);
System.out.println("The first 27 terms of the Euler-Mullin sequence:");
System.out.println(2);
for ( int i = 1; i < 27; i++ ) {
System.out.println(nextEulerMullin());
}
}
private static BigInteger nextEulerMullin() {
BigInteger smallestPrime = smallestPrimeFactor(product.add(BigInteger.ONE));
product = product.multiply(smallestPrime);
return smallestPrime;
}
private static BigInteger smallestPrimeFactor(BigInteger aNumber) {
if ( aNumber.isProbablePrime(probabilityLevel) ) {
return aNumber;
}
for ( BigInteger prime : primes ) {
if ( aNumber.mod(prime).signum() == 0 ) {
return prime;
}
}
BigInteger factor = pollardsRho(aNumber);
return smallestPrimeFactor(factor);
}
private static BigInteger pollardsRho(BigInteger aN) {
if ( aN.equals(BigInteger.ONE) ) {
return BigInteger.ONE;
}
if ( aN.mod(BigInteger.TWO).signum() == 0 ) {
return BigInteger.TWO;
}
final BigInteger core = new BigInteger(aN.bitLength(), random);
BigInteger x = new BigInteger(aN.bitLength(), random);
BigInteger xx = x;
BigInteger divisor = null;
do {
x = x.multiply(x).mod(aN).add(core).mod(aN);
xx = xx.multiply(xx).mod(aN).add(core).mod(aN);
xx = xx.multiply(xx).mod(aN).add(core).mod(aN);
divisor = x.subtract(xx).gcd(aN);
} while ( divisor.equals(BigInteger.ONE) );
return divisor;
}
private static List<BigInteger> listPrimesUpTo(int aLimit) {
BitSet sieve = new BitSet(aLimit + 1);
sieve.set(2, aLimit + 1);
final int squareRoot = (int) Math.sqrt(aLimit);
for ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) {
for ( int j = i * i; j <= aLimit; j = j + i ) {
sieve.clear(j);
}
}
List<BigInteger> result = new ArrayList<BigInteger>(sieve.cardinality());
for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {
result.add(BigInteger.valueOf(i));
}
return result;
}
private static List<BigInteger> primes;
private static BigInteger product = BigInteger.TWO;
private static ThreadLocalRandom random = ThreadLocalRandom.current();
private static final int probabilityLevel = 20;
}
|
Euler's identity | Java | {{Wikipedia|Euler's_identity}}
In mathematics, ''Euler's identity'' is the equality:
ei\pi + 1 = 0
where
e is Euler's number, the base of natural logarithms,
''i'' is the imaginary unit, which satisfies ''i''2 = -1, and
\pi is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number \pi (\pi = 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number ''i'', the imaginary unit of the complex numbers.
;Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei\pi + 1 is ''approximately'' equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
| public class EulerIdentity {
public static void main(String[] args) {
System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0)));
}
public static class Complex {
private double x, y;
public Complex(double re, double im) {
x = re;
y = im;
}
public Complex exp() {
double exp = Math.exp(x);
return new Complex(exp * Math.cos(y), exp * Math.sin(y));
}
public Complex add(Complex a) {
return new Complex(x + a.x, y + a.y);
}
@Override
public String toString() {
return x + " + " + y + "i";
}
}
}
|
Euler's sum of powers conjecture | Java from ALGOL 68 | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
This conjecture is called Euler's sum of powers conjecture and can be stated as such:
:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.
Related tasks are:
* [[Pythagorean quadruples]].
* [[Pythagorean triples]].
| public class eulerSopConjecture
{
static final int MAX_NUMBER = 250;
public static void main( String[] args )
{
boolean found = false;
long[] fifth = new long[ MAX_NUMBER ];
for( int i = 1; i <= MAX_NUMBER; i ++ )
{
long i2 = i * i;
fifth[ i - 1 ] = i2 * i2 * i;
} // for i
for( int a = 0; a < MAX_NUMBER && ! found ; a ++ )
{
for( int b = a; b < MAX_NUMBER && ! found ; b ++ )
{
for( int c = b; c < MAX_NUMBER && ! found ; c ++ )
{
for( int d = c; d < MAX_NUMBER && ! found ; d ++ )
{
long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d];
int e = java.util.Arrays.binarySearch( fifth, sum );
found = ( e >= 0 );
if( found )
{
// the value at e is a fifth power
System.out.print( (a+1) + "^5 + "
+ (b+1) + "^5 + "
+ (c+1) + "^5 + "
+ (d+1) + "^5 = "
+ (e+1) + "^5"
);
} // if found;;
} // for d
} // for c
} // for b
} // for a
} // main
} // eulerSopConjecture |
Even or odd | Java | Test whether an integer is even or odd.
There is more than one way to solve this task:
* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.
* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.
* Use modular congruences:
** ''i'' 0 (mod 2) iff ''i'' is even.
** ''i'' 1 (mod 2) iff ''i'' is odd.
| public static boolean isEven(BigInteger i){
return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);
} |
Evolutionary algorithm | Java 1.5+ | Starting with:
* The target string: "METHINKS IT IS LIKE A WEASEL".
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
* A fitness function that computes the 'closeness' of its argument to the target string.
* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
:* repeat until the parent converges, (hopefully), to the target.
;See also:
* Wikipedia entry: Weasel algorithm.
* Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, '''changing randomly any characters which
don't already match the target''':
''NOTE:'' this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| import java.util.Random;
public class EvoAlgo {
static final String target = "METHINKS IT IS LIKE A WEASEL";
static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
static int C = 100; //number of spawn per generation
static double minMutateRate = 0.09;
static int perfectFitness = target.length();
private static String parent;
static Random rand = new Random();
private static int fitness(String trial){
int retVal = 0;
for(int i = 0;i < trial.length(); i++){
if (trial.charAt(i) == target.charAt(i)) retVal++;
}
return retVal;
}
private static double newMutateRate(){
return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));
}
private static String mutate(String parent, double rate){
String retVal = "";
for(int i = 0;i < parent.length(); i++){
retVal += (rand.nextDouble() <= rate) ?
possibilities[rand.nextInt(possibilities.length)]:
parent.charAt(i);
}
return retVal;
}
public static void main(String[] args){
parent = mutate(target, 1);
int iter = 0;
while(!target.equals(parent)){
double rate = newMutateRate();
iter++;
if(iter % 100 == 0){
System.out.println(iter +": "+parent+ ", fitness: "+fitness(parent)+", rate: "+rate);
}
String bestSpawn = null;
int bestFit = 0;
for(int i = 0; i < C; i++){
String spawn = mutate(parent, rate);
int fitness = fitness(spawn);
if(fitness > bestFit){
bestSpawn = spawn;
bestFit = fitness;
}
}
parent = bestFit > fitness(parent) ? bestSpawn : parent;
}
System.out.println(parent+", "+iter);
}
} |
Executable library | Java | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
'''Task detail'''
* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.
* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:
:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
* Create a second executable to calculate the following:
** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.
* Explain any extra setup/run steps needed to complete the task.
'''Notes:'''
* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.
* Interpreters are present in the runtime environment.
| import java.util.ArrayList;
import java.util.List;
// task 1
public class HailstoneSequence {
public static void main(String[] args) {
// task 2
int n = 27;
List<Long> sequence27 = hailstoneSequence(n);
System.out.printf("Hailstone sequence for %d has a length of %d:%nhailstone(%d) = %s%n", n, sequence27.size(), n, sequence27);
// task 3
int maxN = 0;
int maxLength = 0;
for ( int i = 1 ; i < 100_000 ; i++ ) {
int seqLength = hailstoneSequence(i).size();
if ( seqLength > maxLength ) {
maxLength = seqLength;
maxN = i;
}
}
System.out.printf("Longest hailstone sequence less than 100,000: hailstone(%d).length() = %d", maxN, maxLength);
}
public static List<Long> hailstoneSequence(long n) {
if ( n <= 0 ) {
throw new IllegalArgumentException("Must be grater than or equal to zero.");
}
List<Long> sequence = new ArrayList<>();
sequence.add(n);
while ( n > 1 ) {
if ( (n & 1) == 0 ) {
n /= 2;
}
else {
n = 3 * n + 1;
}
sequence.add(n);
}
return sequence;
}
}
|
Execute Brain**** | Java | Brainf***}}
RCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
{| class="wikitable"
!Command
!Description
|-
| style="text-align:center"| > || Move the pointer to the right
|-
| style="text-align:center"| < || Move the pointer to the left
|-
| style="text-align:center"| + || Increment the memory cell under the pointer
|-
| style="text-align:center"| - || Decrement the memory cell under the pointer
|-
| style="text-align:center"| . || Output the character signified by the cell at the pointer
|-
| style="text-align:center"| , || Input a character and store it in the cell at the pointer
|-
| style="text-align:center"| [ || Jump past the matching ] if the cell under the pointer is 0
|-
| style="text-align:center"| ] || Jump back to the matching [ if the cell under the pointer is nonzero
|}
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
// memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
// border into the program area.
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
// Only works for one byte characters.
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
}
} |
Execute Computer/Zero | Java 8 | Computer/zero Assembly}}
;Task:
Create a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.
:* The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.
:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.
;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.
| import static java.lang.Math.floorMod;
import static java.lang.Math.min;
import static java.util.stream.Collectors.toMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class ComputerZero {
private static final int MEM = 32;
private static final int NOP = 0;
private static final int LDA = 1;
private static final int STA = 2;
private static final int ADD = 3;
private static final int SUB = 4;
private static final int BRZ = 5;
private static final int JMP = 6;
private static final int STP = 7;
private static final Map<String, Integer> OPCODES = Stream.of(
new SimpleEntry<>("NOP", NOP),
new SimpleEntry<>("LDA", LDA),
new SimpleEntry<>("STA", STA),
new SimpleEntry<>("ADD", ADD),
new SimpleEntry<>("SUB", SUB),
new SimpleEntry<>("BRZ", BRZ),
new SimpleEntry<>("JMP", JMP),
new SimpleEntry<>("STP", STP))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
private static final Pattern RE_INSTRUCTION = Pattern.compile(
"\\s*" +
"(?:(?<label>\\w+):)?" +
"\\s*" +
String.format("(?<opcode>%s)?", String.join("|", OPCODES.keySet())) +
"\\s*" +
"(?<argument>\\w+)?" +
"\\s*" +
"(?:;(?<comment>.+))?");
public static class ComputerZeroException extends RuntimeException {
public ComputerZeroException(String msg) {
super(msg);
}
}
private static class Instruction {
String opcode;
String argument;
public Instruction(String opcode, String argument) {
this.opcode = opcode;
this.argument = argument;
}
}
private static class Assembly {
public Iterable<Instruction> instructions;
public Map<String, Integer> labels;
public Assembly(Iterable<Instruction> instructions, Map<String, Integer> labels) {
this.instructions = instructions;
this.labels = labels;
}
}
public static Assembly parse(String assembly) {
ArrayList<Instruction> instructions = new ArrayList<Instruction>();
HashMap<String, Integer> labels = new HashMap<String, Integer>();
int lineNumber = 0;
for (String line : assembly.split("\\R")) {
Matcher matcher = RE_INSTRUCTION.matcher(line);
if (!matcher.matches()) {
throw new ComputerZeroException(String.format("%s %d", line, lineNumber));
}
if (matcher.group("label") != null) {
labels.put(matcher.group("label"), lineNumber);
}
instructions.add(new Instruction(matcher.group("opcode"), matcher.group("argument")));
lineNumber++;
}
return new Assembly(instructions, labels);
}
public static Integer[] compile(Assembly assembly) {
ArrayList<Integer> bytecode = new ArrayList<Integer>();
for (Instruction instruction : assembly.instructions) {
int argument;
if (instruction.argument == null) {
argument = 0;
} else if (instruction.argument.matches("\\d+")) {
argument = Integer.parseInt(instruction.argument);
} else {
argument = assembly.labels.getOrDefault(instruction.argument, 0);
}
if (instruction.opcode != null) {
bytecode.add(OPCODES.get(instruction.opcode) << 5 | argument);
} else {
bytecode.add(argument);
}
}
return bytecode.toArray(new Integer[0]);
}
public static int run(Integer[] bytecode) {
int accumulator = 0;
int instruction_pointer = 0;
Integer[] memory = new Integer[MEM];
Arrays.fill(memory, 0);
System.arraycopy(bytecode, 0, memory, 0, min(MEM, bytecode.length));
vm: while (instruction_pointer < MEM) {
int operation = memory[instruction_pointer] >> 5;
int argument = memory[instruction_pointer] & 0b11111;
instruction_pointer++;
switch (operation) {
case NOP:
continue;
case LDA:
accumulator = memory[argument];
break;
case STA:
memory[argument] = accumulator;
break;
case ADD:
accumulator = floorMod(accumulator + memory[argument], 256);
break;
case SUB:
accumulator = floorMod(accumulator - memory[argument], 256);
break;
case BRZ:
if (accumulator == 0) {
instruction_pointer = argument;
}
break;
case JMP:
instruction_pointer = argument;
break;
case STP:
break vm;
default:
throw new ComputerZeroException(
String.format("error: %d %d", operation, argument));
}
}
return accumulator;
}
public static int run(String source) {
return run(compile(parse(source)));
}
public static final List<String> TEST_CASES = Arrays.asList(
String.join("\n",
" LDA x",
" ADD y ; accumulator = x + y",
" STP",
"x: 2",
"y: 2"),
String.join("\n",
"loop: LDA prodt",
" ADD x",
" STA prodt",
" LDA y",
" SUB one",
" STA y",
" BRZ done",
" JMP loop",
"done: LDA prodt ; to display it",
" STP",
"x: 8",
"y: 7",
"prodt: 0",
"one: 1"),
String.join("\n",
"loop: LDA n",
" STA temp",
" ADD m",
" STA n",
" LDA temp",
" STA m",
" LDA count",
" SUB one",
" BRZ done",
" STA count",
" JMP loop",
"done: LDA n ; to display it",
" STP",
"m: 1",
"n: 1",
"temp: 0",
"count: 8 ; valid range: 1-11",
"one: 1"),
String.join("\n",
"start: LDA load",
" ADD car ; head of list",
" STA ldcar",
" ADD one",
" STA ldcdr ; next CONS cell",
"ldcar: NOP",
" STA value",
"ldcdr: NOP",
" BRZ done ; 0 stands for NIL",
" STA car",
" JMP start",
"done: LDA value ; CAR of last CONS",
" STP",
"load: LDA 0",
"value: 0",
"car: 28",
"one: 1",
" ; order of CONS cells",
" ; in memory",
" ; does not matter",
" 6",
" 0 ; 0 stands for NIL",
" 2 ; (CADR ls)",
" 26 ; (CDDR ls) -- etc.",
" 5",
" 20",
" 3",
" 30",
" 1 ; value of (CAR ls)",
" 22 ; points to (CDR ls)",
" 4",
" 24"),
String.join("\n",
"p: 0 ; NOP in first round",
"c: 0",
"start: STP ; wait for p's move",
"pmove: NOP",
" LDA pmove",
" SUB cmove",
" BRZ same",
" LDA pmove",
" STA cmove ; tit for tat",
" BRZ cdeft",
" LDA c ; p defected, c did not",
" ADD three",
" STA c",
" JMP start",
"cdeft: LDA p",
" ADD three",
" STA p",
" JMP start",
"same: LDA pmove",
" STA cmove ; tit for tat",
" LDA p",
" ADD one",
" ADD pmove",
" STA p",
" LDA c",
" ADD one",
" ADD pmove",
" STA c",
" JMP start",
"cmove: 0 ; co-operate initially",
"one: 1",
"three: 3 "),
String.join("\n",
"LDA 3",
"SUB 4",
"STP 0",
" 0",
" 255"),
String.join("\n",
"LDA 3",
"SUB 4",
"STP 0",
" 0",
" 1"),
String.join("\n",
"LDA 3",
"ADD 4",
"STP 0",
" 1",
" 255")
);
public static void main(String[] args) {
for (String source : TEST_CASES) {
System.out.println(run(source));
}
}
}
|
Exponentiation order | Java | This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.
(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)
;Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
::::* 5**3**2
::::* (5**3)**2
::::* 5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
;See also:
* MathWorld entry: exponentiation
;Related tasks:
* exponentiation operator
* arbitrary-precision integers (included)
* [[Exponentiation with infix operators in (or operating on) the base]]
| Java has no exponentiation operator, but uses the static method java.lang.Math.pow(double a, double b). There are no associativity issues.
|
Extend your language | Java | {{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| public class If2 {
private final boolean firstCondition;
private final boolean secondCondition;
public If2(boolean firstCondition, boolean secondCondition) {
this.firstCondition = firstCondition;
this.secondCondition = secondCondition;
}
public static If2 if2(boolean firstCondition, boolean secondCondition) {
return new If2(firstCondition, secondCondition);
}
public If2 then(Runnable runnable) {
if (firstCondition && secondCondition) {
runnable.run();
}
return this;
}
public If2 elseNone(Runnable runnable) {
if (!firstCondition && !secondCondition) {
runnable.run();
}
return this;
}
public If2 elseIfFirst(Runnable runnable) {
if (firstCondition && !secondCondition) {
runnable.run();
}
return this;
}
public If2 elseIfSecond(Runnable runnable) {
if (!firstCondition && secondCondition) {
runnable.run();
}
return this;
}
}
|
Extreme floating point values | Java | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
;See also:
* What Every Computer Scientist Should Know About Floating-Point Arithmetic
;Related tasks:
* [[Infinity]]
* [[Detect division by zero]]
* [[Literals/Floating point]]
| public class Extreme {
public static void main(String[] args) {
double negInf = -1.0 / 0.0; //also Double.NEGATIVE_INFINITY
double inf = 1.0 / 0.0; //also Double.POSITIVE_INFINITY
double nan = 0.0 / 0.0; //also Double.NaN
double negZero = -2.0 / inf;
System.out.println("Negative inf: " + negInf);
System.out.println("Positive inf: " + inf);
System.out.println("NaN: " + nan);
System.out.println("Negative 0: " + negZero);
System.out.println("inf + -inf: " + (inf + negInf));
System.out.println("0 * NaN: " + (0 * nan));
System.out.println("NaN == NaN: " + (nan == nan));
}
} |
FASTA format | Java | In FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
;Task:
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
| public static void main(String[] args) throws IOException {
List<FASTA> fastas = readFile("fastas.txt");
for (FASTA fasta : fastas)
System.out.println(fasta);
}
static List<FASTA> readFile(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
List<FASTA> list = new ArrayList<>();
StringBuilder lines = null;
String newline = System.lineSeparator();
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(">")) {
if (lines != null)
list.add(parseFASTA(lines.toString()));
lines = new StringBuilder();
lines.append(line).append(newline);
} else {
lines.append(line);
}
}
list.add(parseFASTA(lines.toString()));
return list;
}
}
static FASTA parseFASTA(String string) {
String description;
char[] sequence;
int indexOf = string.indexOf(System.lineSeparator());
description = string.substring(1, indexOf);
/* using 'stripLeading' will remove any additional line-separators */
sequence = string.substring(indexOf + 1).stripLeading().toCharArray();
return new FASTA(description, sequence);
}
/* using a 'char' array seems more logical */
record FASTA(String description, char[] sequence) {
@Override
public String toString() {
return "%s: %s".formatted(description, new String(sequence));
}
}
|
FASTA format | Java 7 | In FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
;Task:
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
| import java.io.*;
import java.util.Scanner;
public class ReadFastaFile {
public static void main(String[] args) throws FileNotFoundException {
boolean first = true;
try (Scanner sc = new Scanner(new File("test.fasta"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.charAt(0) == '>') {
if (first)
first = false;
else
System.out.println();
System.out.printf("%s: ", line.substring(1));
} else {
System.out.print(line);
}
}
}
System.out.println();
}
} |
Factorial primes | Java | Definition
A factorial.
In other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime.
;Examples
4 corresponds to the factorial prime 4! - 1 = 23.
5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.
;Task
Find and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted.
As 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.
;Stretch
If your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.
As it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.
If a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.
;Reference
* OEIS:A088054 - Factorial primes
;Related task
* Sequence of primorial primes
| import java.math.BigInteger;
public class MainApp {
public static void main(String[] args) {
//Used to measure total runtime of program.
long starttime = System.nanoTime();
//How many primes found, how many primes wanted, loop counter.
int countOfPrimes = 0;
final int targetCountOfPrimes = 30;
long f = 1;
//Starting BigInteger at 1.
BigInteger biFactorial = BigInteger.ONE;
while (countOfPrimes < targetCountOfPrimes) {
//Each loop, multiply the number by the loop
//counter (f) to increase factorial much more quickly.
biFactorial = biFactorial.multiply(BigInteger.valueOf(f));
// one less than the factorial.
BigInteger biMinusOne = biFactorial.subtract(BigInteger.ONE);
// one more than the factorial.
BigInteger biPlusOne = biFactorial.add(BigInteger.ONE);
//Determine if the numbers are prime with a probability of 100
boolean primeMinus = biMinusOne.isProbablePrime(100);
boolean primePlus = biPlusOne.isProbablePrime(100);
//Make the big number look like a pretty string for output.
String biMinusOneString = convert(biMinusOne);
String biPlusOneString = convert(biPlusOne);
//If the number was prime, output and increment the primt counter.
if (primeMinus) {
countOfPrimes++;
System.out.println(
countOfPrimes + ": " + f + "! - 1 = " + biMinusOneString);
}
if (primePlus) {
countOfPrimes++;
System.out.println(countOfPrimes + ": " + f + "! + 1 = " + biPlusOneString);
}
//Increment loop counter.
f++;
}
//Calculate and display program runtime.
long stoptime = System.nanoTime();
long runtime = stoptime - starttime;
System.out.println("Program runtime: " + runtime + " ns (~" + runtime/1_000_000_000 + " seconds)");
}
//Method to make output pretty
private static String convert(BigInteger bi) {
String s = bi.toString();
int l = s.length();
String s2 = "";
if (l >= 40) {
s2 = s.substring(0, 19);
s2 += "..." + s.substring(s.length() - 20, s.length());
s2 += " : " + l + " digits";
} else {s2 = s;}
return s2;
}
}
|
Factorions | Java | Definition:
A factorion is a natural number that equals the sum of the factorials of its digits.
;Example:
'''145''' is a factorion in base '''10''' because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.
;Task:
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
:* There are '''3''' factorions in base '''9'''
:* There are '''4''' factorions in base '''10'''
:* There are '''5''' factorions in base '''11'''
:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')
;See also:
:* '''Wikipedia article'''
:* '''OEIS:A014080 - Factorions in base 10'''
:* '''OEIS:A193163 - Factorions in base n'''
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
// Ln 57-71 from Geeks for Geeks @ https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Fairshare between two and more | Java | The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''
;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''
;Task
Counting from zero; using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.
Show the first 25 terms of the fairshare sequence:
:* For two people:
:* For three people
:* For five people
:* For eleven people
;Related tasks:
:* [[Non-decimal radices/Convert]]
:* [[Thue-Morse]]
;See also:
:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FairshareBetweenTwoAndMore {
public static void main(String[] args) {
for ( int base : Arrays.asList(2, 3, 5, 11) ) {
System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base));
}
}
private static List<Integer> thueMorseSequence(int terms, int base) {
List<Integer> sequence = new ArrayList<Integer>();
for ( int i = 0 ; i < terms ; i++ ) {
int sum = 0;
int n = i;
while ( n > 0 ) {
// Compute the digit sum
sum += n % base;
n /= base;
}
// Compute the digit sum module base.
sequence.add(sum % base);
}
return sequence;
}
}
|
Farey sequence | Java 1.5+ | The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.
The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''.
Each Farey sequence:
:::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1}
:::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}.
The Farey sequences of orders '''1''' to '''5''' are:
:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}
;Task
* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).
* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.
* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
::::::::::: 3 x n2 / \pi2
;See also:
* OEIS sequence A006842 numerators of Farey series of order 1, 2, ***
* OEIS sequence A006843 denominators of Farey series of order 1, 2, ***
* OEIS sequence A005728 number of fractions in Farey series of order n
* MathWorld entry Farey sequence
* Wikipedia entry Farey sequence
| import java.util.TreeSet;
public class Farey{
private static class Frac implements Comparable<Frac>{
int num;
int den;
public Frac(int num, int den){
this.num = num;
this.den = den;
}
@Override
public String toString(){
return num + "/" + den;
}
@Override
public int compareTo(Frac o){
return Double.compare((double)num / den, (double)o.num / o.den);
}
}
public static TreeSet<Frac> genFarey(int i){
TreeSet<Frac> farey = new TreeSet<Frac>();
for(int den = 1; den <= i; den++){
for(int num = 0; num <= den; num++){
farey.add(new Frac(num, den));
}
}
return farey;
}
public static void main(String[] args){
for(int i = 1; i <= 11; i++){
System.out.println("F" + i + ": " + genFarey(i));
}
for(int i = 100; i <= 1000; i += 100){
System.out.println("F" + i + ": " + genFarey(i).size() + " members");
}
}
} |
Fast Fourier transform | Java from C sharp | Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result.
The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| import static java.lang.Math.*;
public class FastFourierTransform {
public static int bitReverse(int n, int bits) {
int reversedN = n;
int count = bits - 1;
n >>= 1;
while (n > 0) {
reversedN = (reversedN << 1) | (n & 1);
count--;
n >>= 1;
}
return ((reversedN << count) & ((1 << bits) - 1));
}
static void fft(Complex[] buffer) {
int bits = (int) (log(buffer.length) / log(2));
for (int j = 1; j < buffer.length / 2; j++) {
int swapPos = bitReverse(j, bits);
Complex temp = buffer[j];
buffer[j] = buffer[swapPos];
buffer[swapPos] = temp;
}
for (int N = 2; N <= buffer.length; N <<= 1) {
for (int i = 0; i < buffer.length; i += N) {
for (int k = 0; k < N / 2; k++) {
int evenIndex = i + k;
int oddIndex = i + k + (N / 2);
Complex even = buffer[evenIndex];
Complex odd = buffer[oddIndex];
double term = (-2 * PI * k) / (double) N;
Complex exp = (new Complex(cos(term), sin(term)).mult(odd));
buffer[evenIndex] = even.add(exp);
buffer[oddIndex] = even.sub(exp);
}
}
}
}
public static void main(String[] args) {
double[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};
Complex[] cinput = new Complex[input.length];
for (int i = 0; i < input.length; i++)
cinput[i] = new Complex(input[i], 0.0);
fft(cinput);
System.out.println("Results:");
for (Complex c : cinput) {
System.out.println(c);
}
}
}
class Complex {
public final double re;
public final double im;
public Complex() {
this(0, 0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public Complex add(Complex b) {
return new Complex(this.re + b.re, this.im + b.im);
}
public Complex sub(Complex b) {
return new Complex(this.re - b.re, this.im - b.im);
}
public Complex mult(Complex b) {
return new Complex(this.re * b.re - this.im * b.im,
this.re * b.im + this.im * b.re);
}
@Override
public String toString() {
return String.format("(%f,%f)", re, im);
}
} |
Feigenbaum constant calculation | Java from Kotlin | Calculate the Feigenbaum constant.
;See:
:* Details in the Wikipedia article: Feigenbaum constant.
| public class Feigenbaum {
public static void main(String[] args) {
int max_it = 13;
int max_it_j = 10;
double a1 = 1.0;
double a2 = 0.0;
double d1 = 3.2;
double a;
System.out.println(" i d");
for (int i = 2; i <= max_it; i++) {
a = a1 + (a1 - a2) / d1;
for (int j = 0; j < max_it_j; j++) {
double x = 0.0;
double y = 0.0;
for (int k = 0; k < 1 << i; k++) {
y = 1.0 - 2.0 * y * x;
x = a - x * x;
}
a -= x / y;
}
double d = (a1 - a2) / (a - a1);
System.out.printf("%2d %.8f\n", i, d);
d1 = d;
a2 = a1;
a1 = a;
}
}
} |
Fibonacci n-step number sequences | Java | These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}
For small values of n, Greek numeric prefixes are sometimes used to individually name each series.
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}
Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.
;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
;Related tasks:
* [[Fibonacci sequence]]
* Wolfram Mathworld
* [[Hofstadter Q sequence]]
* [[Leonardo numbers]]
;Also see:
* Lucas Numbers - Numberphile (Video)
* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
* Wikipedia, Lucas number
* MathWorld, Fibonacci Number
* Some identities for r-Fibonacci numbers
* OEIS Fibonacci numbers
* OEIS Lucas numbers
| class Fibonacci
{
public static int[] lucas(int n, int numRequested)
{
if (n < 2)
throw new IllegalArgumentException("Fibonacci value must be at least 2");
return fibonacci((n == 2) ? new int[] { 2, 1 } : lucas(n - 1, n), numRequested);
}
public static int[] fibonacci(int n, int numRequested)
{
if (n < 2)
throw new IllegalArgumentException("Fibonacci value must be at least 2");
return fibonacci((n == 2) ? new int[] { 1, 1 } : fibonacci(n - 1, n), numRequested);
}
public static int[] fibonacci(int[] startingValues, int numRequested)
{
int[] output = new int[numRequested];
int n = startingValues.length;
System.arraycopy(startingValues, 0, output, 0, n);
for (int i = n; i < numRequested; i++)
for (int j = 1; j <= n; j++)
output[i] += output[i - j];
return output;
}
public static void main(String[] args)
{
for (int n = 2; n <= 10; n++)
{
System.out.print("nacci(" + n + "):");
for (int value : fibonacci(n, 15))
System.out.print(" " + value);
System.out.println();
}
for (int n = 2; n <= 10; n++)
{
System.out.print("lucas(" + n + "):");
for (int value : lucas(n, 15))
System.out.print(" " + value);
System.out.println();
}
}
} |
Fibonacci word | Java | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as '''1'''
Define F_Word2 as '''0'''
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
;Task:
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words '''1''' to '''37''' which shows:
::* The number of characters in the word
::* The word's [[Entropy]]
;Related tasks:
* Fibonacci word/fractal
* [[Entropy]]
* [[Entropy/Narcissist]]
| import java.util.*;
public class FWord {
private /*v*/ String fWord0 = "";
private /*v*/ String fWord1 = "";
private String nextFWord () {
final String result;
if ( "".equals ( fWord1 ) ) result = "1";
else if ( "".equals ( fWord0 ) ) result = "0";
else result = fWord1 + fWord0;
fWord0 = fWord1;
fWord1 = result;
return result;
}
public static double entropy ( final String source ) {
final int length = source.length ();
final Map < Character, Integer > counts = new HashMap < Character, Integer > ();
/*v*/ double result = 0.0;
for ( int i = 0; i < length; i++ ) {
final char c = source.charAt ( i );
if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );
else counts.put ( c, 1 );
}
for ( final int count : counts.values () ) {
final double proportion = ( double ) count / length;
result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );
}
return result;
}
public static void main ( final String [] args ) {
final FWord fWord = new FWord ();
for ( int i = 0; i < 37; ) {
final String word = fWord.nextFWord ();
System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) );
}
}
} |
File extension is in extensions list | Java 1.5+ | Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the [[Extract file extension]] task.
;Related tasks:
* [[Extract file extension]]
* [[String matching]]
| import java.util.Arrays;
import java.util.Comparator;
public class FileExt{
public static void main(String[] args){
String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"};
String[] exts = {".txt",".gz","",".bat"};
System.out.println("Extensions: " + Arrays.toString(exts) + "\n");
for(String test:tests){
System.out.println(test +": " + extIsIn(test, exts));
}
}
public static boolean extIsIn(String test, String... exts){
int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); //whichever one they decide to use today
String filename = test.substring(lastSlash + 1);//+1 to get rid of the slash or move to index 0 if there's no slash
//end of the name if no dot, last dot index otherwise
int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');
String ext = filename.substring(lastDot);//everything at the last dot and after is the extension
Arrays.sort(exts);//sort for the binary search
return Arrays.binarySearch(exts, ext, new Comparator<String>() { //just use the built-in binary search method
@Override //it will let us specify a Comparator and it's fast enough
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}) >= 0;//binarySearch returns negative numbers when it's not found
}
}
|
File extension is in extensions list | Java 6+ | Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the [[Extract file extension]] task.
;Related tasks:
* [[Extract file extension]]
* [[String matching]]
| public static boolean extIsIn(String test, String... exts){
for(int i = 0; i < exts.length; i++){
exts[i] = exts[i].replaceAll("\\.", "");
}
return (new FileNameExtensionFilter("extension test", exts)).accept(new File(test));
} |
Find Chess960 starting position identifier | Java | Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
;Task:
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
;Algorithm:
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''
2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').
4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518.
Note that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.
RQNBBKRN = 601
RNQBBKRN = 617
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
public final class Chess960SPID {
public static void main(String[] aArgs) {
String[] positions = { "QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN" };
createKnightsTable();
for ( String position : positions ) {
validate("RQNBBKRN");
System.out.println("Position " + position + " has Chess960 SP-ID = " + calculateSPID(position));
}
}
private static void validate(String aPosition) {
if ( aPosition.length() != 8 ) {
throw new AssertionError("Chess position has invalid length: " + aPosition.length() + ".");
}
Map<Character, Integer> pieces = new HashMap<Character, Integer>();
for ( char ch : aPosition.toCharArray() ) {
pieces.merge(ch, 1, (oldV, newV) -> oldV + 1);
}
Set<Map.Entry<Character, Integer>> correctPieces =
Set.of(Map.entry('R', 2), Map.entry('N', 2), Map.entry('B', 2), Map.entry('Q', 1), Map.entry('K', 1));
if ( ! pieces.entrySet().equals(correctPieces) ) {
throw new AssertionError("Chess position contains incorrect pieces.");
}
List<Integer> bishops = List.of(aPosition.indexOf('B'), aPosition.lastIndexOf('B'));
if ( ( bishops.get(1) - bishops.get(0) ) % 2 == 0 ) {
throw new AssertionError("Bishops must be on different coloured squares.");
}
List<Integer> rookKing = List.of(aPosition.indexOf('R'), aPosition.indexOf('K'), aPosition.lastIndexOf('R'));
if ( ! ( rookKing.get(0) < rookKing.get(1) && rookKing.get(1) < rookKing.get(2) ) ) {
throw new AssertionError("The king must be between the two rooks.");
}
}
private static int calculateSPID(String aPosition) {
String noBishopsOrQueen = retainIf(aPosition, s -> s != 'B' && s != 'Q');
final int N = knightsTable.get(List.of(noBishopsOrQueen.indexOf('N'), noBishopsOrQueen.lastIndexOf('N')));
String noBishops = retainIf(aPosition, s -> s != 'B');
final int Q = noBishops.indexOf('Q');
final int indexOne = aPosition.indexOf('B');
final int indexTwo = aPosition.lastIndexOf('B');
final int D = ( indexOne % 2 == 0 ) ? indexOne / 2 : indexTwo / 2;
final int L = ( indexOne % 2 == 0 ) ? indexTwo / 2 : indexOne / 2;
return 96 * N + 16 * Q + 4 * D + L;
}
private static String retainIf(String aText, Predicate<Character> aPredicate) {
return aText.chars()
.mapToObj( i -> (char) i )
.filter(aPredicate)
.map(String::valueOf)
.reduce("", String::concat);
}
private static void createKnightsTable() {
knightsTable = new HashMap<List<Integer>, Integer>();
knightsTable.put(List.of(0, 1), 0);
knightsTable.put(List.of(0, 2), 1);
knightsTable.put(List.of(0, 3), 2);
knightsTable.put(List.of(0, 4), 3);
knightsTable.put(List.of(1, 2), 4);
knightsTable.put(List.of(1, 3), 5);
knightsTable.put(List.of(1, 4), 6);
knightsTable.put(List.of(2, 3), 7);
knightsTable.put(List.of(2, 4), 8);
knightsTable.put(List.of(3, 4), 9);
}
private static Map<List<Integer>, Integer> knightsTable;
}
|
Find duplicate files | Java | In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
;Task:
Create a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
| import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;
public class DuplicateFiles {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Directory name and minimum file size are required.");
System.exit(1);
}
try {
findDuplicateFiles(args[0], Long.parseLong(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findDuplicateFiles(String directory, long minimumSize)
throws IOException, NoSuchAlgorithmException {
System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
Path path = FileSystems.getDefault().getPath(directory);
FileVisitor visitor = new FileVisitor(path, minimumSize);
Files.walkFileTree(path, visitor);
System.out.println("The following sets of files have the same size and checksum:");
for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
Map<Object, List<String>> map = e.getValue();
if (!containsDuplicates(map))
continue;
List<List<String>> fileSets = new ArrayList<>(map.values());
for (List<String> files : fileSets)
Collections.sort(files);
Collections.sort(fileSets, new StringListComparator());
FileKey key = e.getKey();
System.out.println();
System.out.println("Size: " + key.size_ + " bytes");
for (List<String> files : fileSets) {
for (int i = 0, n = files.size(); i < n; ++i) {
if (i > 0)
System.out.print(" = ");
System.out.print(files.get(i));
}
System.out.println();
}
}
}
private static class StringListComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
int len1 = a.size(), len2 = b.size();
for (int i = 0; i < len1 && i < len2; ++i) {
int c = a.get(i).compareTo(b.get(i));
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
private static boolean containsDuplicates(Map<Object, List<String>> map) {
if (map.size() > 1)
return true;
for (List<String> files : map.values()) {
if (files.size() > 1)
return true;
}
return false;
}
private static class FileVisitor extends SimpleFileVisitor<Path> {
private MessageDigest digest_;
private Path directory_;
private long minimumSize_;
private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();
private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
directory_ = directory;
minimumSize_ = minimumSize;
digest_ = MessageDigest.getInstance("MD5");
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.size() >= minimumSize_) {
FileKey key = new FileKey(file, attrs, getMD5Sum(file));
Map<Object, List<String>> map = fileMap_.get(key);
if (map == null)
fileMap_.put(key, map = new HashMap<>());
List<String> files = map.get(attrs.fileKey());
if (files == null)
map.put(attrs.fileKey(), files = new ArrayList<>());
Path relative = directory_.relativize(file);
files.add(relative.toString());
}
return FileVisitResult.CONTINUE;
}
private byte[] getMD5Sum(Path file) throws IOException {
digest_.reset();
try (InputStream in = new FileInputStream(file.toString())) {
byte[] buffer = new byte[8192];
int bytes;
while ((bytes = in.read(buffer)) != -1) {
digest_.update(buffer, 0, bytes);
}
}
return digest_.digest();
}
}
private static class FileKey implements Comparable<FileKey> {
private byte[] hash_;
private long size_;
private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
size_ = attrs.size();
hash_ = hash;
}
public int compareTo(FileKey other) {
int c = Long.compare(other.size_, size_);
if (c == 0)
c = hashCompare(hash_, other.hash_);
return c;
}
}
private static int hashCompare(byte[] a, byte[] b) {
int len1 = a.length, len2 = b.length;
for (int i = 0; i < len1 && i < len2; ++i) {
int c = Byte.compare(a[i], b[i]);
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
} |
Find if a point is within a triangle | Java from Go | Find if a point is within a triangle.
;Task:
::* Assume points are on a plane defined by (x, y) real number coordinates.
::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
::* You may use any algorithm.
::* Bonus: explain why the algorithm you chose works.
;Related tasks:
* [[Determine_if_two_triangles_overlap]]
;Also see:
:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]
:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]
:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]
:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
} |
Find limit of recursion | Java | {{selection|Short Circuit|Console Program Basics}}
;Task:
Find the limit of recursion.
| public class RecursionTest {
private static void recurse(int i) {
try {
recurse(i+1);
} catch (StackOverflowError e) {
System.out.print("Recursion depth on this system is " + i + ".");
}
}
public static void main(String[] args) {
recurse(0);
}
}
|
Find palindromic numbers in both binary and ternary bases | Java | * Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':
:::* base 2
:::* base 3
* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.
* Optionally, show the decimal number found in its binary and ternary form.
* Show all output here.
It's permissible to assume the first two numbers and simply list them.
;See also
* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
| public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue; //skip non-zero evens, nothing that ends in 0 in binary can be in this sequence
//maybe speed things up through short-circuit evaluation by putting toString in the if
//testing up to 10M, base 2 has slightly fewer palindromes so do that one first
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
} |
Find the intersection of a line with a plane | Java from Kotlin | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
;Task:
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
| public class LinePlaneIntersection {
private static class Vector3D {
private double x, y, z;
Vector3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector3D plus(Vector3D v) {
return new Vector3D(x + v.x, y + v.y, z + v.z);
}
Vector3D minus(Vector3D v) {
return new Vector3D(x - v.x, y - v.y, z - v.z);
}
Vector3D times(double s) {
return new Vector3D(s * x, s * y, s * z);
}
double dot(Vector3D v) {
return x * v.x + y * v.y + z * v.z;
}
@Override
public String toString() {
return String.format("(%f, %f, %f)", x, y, z);
}
}
private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) {
Vector3D diff = rayPoint.minus(planePoint);
double prod1 = diff.dot(planeNormal);
double prod2 = rayVector.dot(planeNormal);
double prod3 = prod1 / prod2;
return rayPoint.minus(rayVector.times(prod3));
}
public static void main(String[] args) {
Vector3D rv = new Vector3D(0.0, -1.0, -1.0);
Vector3D rp = new Vector3D(0.0, 0.0, 10.0);
Vector3D pn = new Vector3D(0.0, 0.0, 1.0);
Vector3D pp = new Vector3D(0.0, 0.0, 5.0);
Vector3D ip = intersectPoint(rv, rp, pn, pp);
System.out.println("The ray intersects the plane at " + ip);
}
} |
Find the intersection of two lines | Java from Kotlin | Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]
;Task:
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| public class Intersection {
private static class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("{%f, %f}", x, y);
}
}
private static class Line {
Point s, e;
Line(Point s, Point e) {
this.s = s;
this.e = e;
}
}
private static Point findIntersection(Line l1, Line l2) {
double a1 = l1.e.y - l1.s.y;
double b1 = l1.s.x - l1.e.x;
double c1 = a1 * l1.s.x + b1 * l1.s.y;
double a2 = l2.e.y - l2.s.y;
double b2 = l2.s.x - l2.e.x;
double c2 = a2 * l2.s.x + b2 * l2.s.y;
double delta = a1 * b2 - a2 * b1;
return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta);
}
public static void main(String[] args) {
Line l1 = new Line(new Point(4, 0), new Point(6, 10));
Line l2 = new Line(new Point(0, 3), new Point(10, 7));
System.out.println(findIntersection(l1, l2));
l1 = new Line(new Point(0, 0), new Point(1, 1));
l2 = new Line(new Point(1, 2), new Point(4, 5));
System.out.println(findIntersection(l1, l2));
}
} |
Find the last Sunday of each month | Java | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]
| import java.util.Scanner;
public class LastSunday
{
static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};
public static int[] findLastSunday(int year)
{
boolean isLeap = isLeapYear(year);
int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31};
int[] lastDay=new int[12];
for(int m=0;i<12;i++)
{
int d;
for(d=days[m]; getWeekDay(year,m,d)!=0; d--)
;
lastDay[m]=d;
}
return lastDay;
}
private static boolean isLeapYear(int year)
{
if(year%4==0)
{
if(year%100!=0)
return true;
else if (year%400==0)
return true;
}
return false;
}
private static int getWeekDay(int y, int m, int d)
{
int f=y+d+3*m-1;
m++;
if(m<3)
y--;
else
f-=(int)(0.4*m+2.3);
f+=(int)(y/4)-(int)((y/100+1)*0.75);
f%=7;
return f;
}
private static void display(int year, int[] lastDay)
{
System.out.println("\nYEAR: "+year);
for(int m=0;i<12;i++)
System.out.println(months[m]+": "+lastDay[m]);
}
public static void main(String[] args) throws Exception
{
System.out.print("Enter year: ");
Scanner s=new Scanner(System.in);
int y=Integer.parseInt(s.next());
int[] lastDay = findLastSunday(y);
display(y, lastDay);
s.close();
}
} |
Find the missing permutation | Java | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| import java.util.ArrayList;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
public class FindMissingPermutation {
public static void main(String[] args) {
Joiner joiner = Joiner.on("").skipNulls();
ImmutableSet<String> s = ImmutableSet.of("ABCD", "CABD", "ACDB",
"DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB",
"CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC",
"BDAC", "CBDA", "DBCA", "DCAB");
for (ArrayList<Character> cs : Utils.Permutations(Lists.newArrayList(
'A', 'B', 'C', 'D')))
if (!s.contains(joiner.join(cs)))
System.out.println(joiner.join(cs));
}
} |
First perfect square in base n with n unique digits | Java from C# | Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.
E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
;Task
* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.
* (optional) Do the same for bases '''13''' through '''16'''.
* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)
;See also:
;* OEIS A260182: smallest square that is pandigital in base n.
;Related task
;* [[Casting out nines]]
| import java.math.BigInteger;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Program {
static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|";
static byte base, bmo, blim, ic;
static long st0;
static BigInteger bllim, threshold;
static Set<Byte> hs = new HashSet<>();
static Set<Byte> o = new HashSet<>();
static final char[] chars = ALPHABET.toCharArray();
static List<BigInteger> limits;
static String ms;
static int indexOf(char c) {
for (int i = 0; i < chars.length; ++i) {
if (chars[i] == c) {
return i;
}
}
return -1;
}
// convert BigInteger to string using current base
static String toStr(BigInteger b) {
BigInteger bigBase = BigInteger.valueOf(base);
StringBuilder res = new StringBuilder();
while (b.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divRem = b.divideAndRemainder(bigBase);
res.append(chars[divRem[1].intValue()]);
b = divRem[0];
}
return res.toString();
}
// check for a portion of digits, bailing if uneven
static boolean allInQS(BigInteger b) {
BigInteger bigBase = BigInteger.valueOf(base);
int c = ic;
hs.clear();
hs.addAll(o);
while (b.compareTo(bllim) > 0) {
BigInteger[] divRem = b.divideAndRemainder(bigBase);
hs.add(divRem[1].byteValue());
c++;
if (c > hs.size()) {
return false;
}
b = divRem[0];
}
return true;
}
// check for a portion of digits, all the way to the end
static boolean allInS(BigInteger b) {
BigInteger bigBase = BigInteger.valueOf(base);
hs.clear();
hs.addAll(o);
while (b.compareTo(bllim) > 0) {
BigInteger[] divRem = b.divideAndRemainder(bigBase);
hs.add(divRem[1].byteValue());
b = divRem[0];
}
return hs.size() == base;
}
// check for all digits, bailing if uneven
static boolean allInQ(BigInteger b) {
BigInteger bigBase = BigInteger.valueOf(base);
int c = 0;
hs.clear();
while (b.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divRem = b.divideAndRemainder(bigBase);
hs.add(divRem[1].byteValue());
c++;
if (c > hs.size()) {
return false;
}
b = divRem[0];
}
return true;
}
// check for all digits, all the way to the end
static boolean allIn(BigInteger b) {
BigInteger bigBase = BigInteger.valueOf(base);
hs.clear();
while (b.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divRem = b.divideAndRemainder(bigBase);
hs.add(divRem[1].byteValue());
b = divRem[0];
}
return hs.size() == base;
}
// parse a string into a BigInteger, using current base
static BigInteger to10(String s) {
BigInteger bigBase = BigInteger.valueOf(base);
BigInteger res = BigInteger.ZERO;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
int idx = indexOf(c);
BigInteger bigIdx = BigInteger.valueOf(idx);
res = res.multiply(bigBase).add(bigIdx);
}
return res;
}
// returns the minimum value string, optionally inserting extra digit
static String fixup(int n) {
String res = ALPHABET.substring(0, base);
if (n > 0) {
StringBuilder sb = new StringBuilder(res);
sb.insert(n, n);
res = sb.toString();
}
return "10" + res.substring(2);
}
// checks the square against the threshold, advances various limits when needed
static void check(BigInteger sq) {
if (sq.compareTo(threshold) > 0) {
o.remove((byte) indexOf(ms.charAt(blim)));
blim--;
ic--;
threshold = limits.get(bmo - blim - 1);
bllim = to10(ms.substring(0, blim + 1));
}
}
// performs all the calculations for the current base
static void doOne() {
limits = new ArrayList<>();
bmo = (byte) (base - 1);
byte dr = 0;
if ((base & 1) == 1) {
dr = (byte) (base >> 1);
}
o.clear();
blim = 0;
byte id = 0;
int inc = 1;
long st = System.nanoTime();
byte[] sdr = new byte[bmo];
byte rc = 0;
for (int i = 0; i < bmo; i++) {
sdr[i] = (byte) ((i * i) % bmo);
rc += sdr[i] == dr ? (byte) 1 : (byte) 0;
sdr[i] += sdr[i] == 0 ? bmo : (byte) 0;
}
long i = 0;
if (dr > 0) {
id = base;
for (i = 1; i <= dr; i++) {
if (sdr[(int) i] >= dr) {
if (id > sdr[(int) i]) {
id = sdr[(int) i];
}
}
}
id -= dr;
i = 0;
}
ms = fixup(id);
BigInteger sq = to10(ms);
BigInteger rt = BigInteger.valueOf((long) (Math.sqrt(sq.doubleValue()) + 1));
sq = rt.multiply(rt);
if (base > 9) {
for (int j = 1; j < base; j++) {
limits.add(to10(ms.substring(0, j) + String.valueOf(chars[bmo]).repeat(base - j + (rc > 0 ? 0 : 1))));
}
Collections.reverse(limits);
while (sq.compareTo(limits.get(0)) < 0) {
rt = rt.add(BigInteger.ONE);
sq = rt.multiply(rt);
}
}
BigInteger dn = rt.shiftLeft(1).add(BigInteger.ONE);
BigInteger d = BigInteger.ONE;
if (base > 3 && rc > 0) {
while (sq.remainder(BigInteger.valueOf(bmo)).compareTo(BigInteger.valueOf(dr)) != 0) {
rt = rt.add(BigInteger.ONE);
sq = sq.add(dn);
dn = dn.add(BigInteger.TWO);
} // aligns sq to dr
inc = bmo / rc;
if (inc > 1) {
dn = dn.add(rt.multiply(BigInteger.valueOf(inc - 2)).subtract(BigInteger.ONE));
d = BigInteger.valueOf(inc * inc);
}
dn = dn.add(dn).add(d);
}
d = d.shiftLeft(1);
if (base > 9) {
blim = 0;
while (sq.compareTo(limits.get(bmo - blim - 1)) < 0) {
blim++;
}
ic = (byte) (blim + 1);
threshold = limits.get(bmo - blim - 1);
if (blim > 0) {
for (byte j = 0; j <= blim; j++) {
o.add((byte) indexOf(ms.charAt(j)));
}
}
if (blim > 0) {
bllim = to10(ms.substring(0, blim + 1));
} else {
bllim = BigInteger.ZERO;
}
if (base > 5 && rc > 0)
while (!allInQS(sq)) {
sq = sq.add(dn);
dn = dn.add(d);
i += 1;
check(sq);
}
else {
while (!allInS(sq)) {
sq = sq.add(dn);
dn = dn.add(d);
i += 1;
check(sq);
}
}
} else {
if (base > 5 && rc > 0) {
while (!allInQ(sq)) {
sq = sq.add(dn);
dn = dn.add(d);
i += 1;
}
} else {
while (!allIn(sq)) {
sq = sq.add(dn);
dn = dn.add(d);
i += 1;
}
}
}
rt = rt.add(BigInteger.valueOf(i * inc));
long delta1 = System.nanoTime() - st;
Duration dur1 = Duration.ofNanos(delta1);
long delta2 = System.nanoTime() - st0;
Duration dur2 = Duration.ofNanos(delta2);
System.out.printf(
"%3d %2d %2s %20s -> %-40s %10d %9s %9s\n",
base, inc, (id > 0 ? ALPHABET.substring(id, id + 1) : " "), toStr(rt), toStr(sq), i, format(dur1), format(dur2)
);
}
private static String format(Duration d) {
int minP = d.toMinutesPart();
int secP = d.toSecondsPart();
int milP = d.toMillisPart();
return String.format("%02d:%02d.%03d", minP, secP, milP);
}
public static void main(String[] args) {
System.out.println("base inc id root square test count time total");
st0 = System.nanoTime();
for (base = 2; base < 28; ++base) {
doOne();
}
}
} |
First power of 2 that has leading decimal digits of 12 | Java | (This task is taken from a ''Project Euler'' problem.)
(All numbers herein are expressed in base ten.)
'''27 = 128''' and '''7''' is
the first power of '''2''' whose leading decimal digits are '''12'''.
The next power of '''2''' whose leading decimal digits
are '''12''' is '''80''',
'''280 = 1208925819614629174706176'''.
Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest
value of ''' ''j'' ''' such that the base ten representation
of '''2''j''''' begins with the digits of ''' ''L'' '''.
So ''p''(12, 1) = 7 and
''p''(12, 2) = 80
You are also given that:
''p''(123, 45) = 12710
;Task:
::* find:
:::::* ''' ''p''(12, 1) '''
:::::* ''' ''p''(12, 2) '''
:::::* ''' ''p''(123, 45) '''
:::::* ''' ''p''(123, 12345) '''
:::::* ''' ''p''(123, 678910) '''
::* display the results here, on this page.
| public class FirstPowerOfTwo {
public static void main(String[] args) {
runTest(12, 1);
runTest(12, 2);
runTest(123, 45);
runTest(123, 12345);
runTest(123, 678910);
}
private static void runTest(int l, int n) {
System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n));
}
public static int p(int l, int n) {
int test = 0;
double log = Math.log(2) / Math.log(10);
int factor = 1;
int loop = l;
while ( loop > 10 ) {
factor *= 10;
loop /= 10;
}
while ( n > 0) {
test++;
int val = (int) (factor * Math.pow(10, test * log % 1));
if ( val == l ) {
n--;
}
}
return test;
}
}
|
Fivenum | Java from Kotlin | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.
;Task:
Given an array of numbers, compute the five-number summary.
;Note:
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
| import java.util.Arrays;
public class Fivenum {
static double median(double[] x, int start, int endInclusive) {
int size = endInclusive - start + 1;
if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty");
int m = start + size / 2;
return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;
}
static double[] fivenum(double[] x) {
for (Double d : x) {
if (d.isNaN())
throw new IllegalArgumentException("Unable to deal with arrays containing NaN");
}
double[] result = new double[5];
Arrays.sort(x);
result[0] = x[0];
result[2] = median(x, 0, x.length - 1);
result[4] = x[x.length - 1];
int m = x.length / 2;
int lowerEnd = (x.length % 2 == 1) ? m : m - 1;
result[1] = median(x, 0, lowerEnd);
result[3] = median(x, m, x.length - 1);
return result;
}
public static void main(String[] args) {
double xl[][] = {
{15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
{36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
{
0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,
-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,
-0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,
0.75775634, 0.32566578
}
};
for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x)));
}
} |
Flatten a list | Java 1.5+ | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| import java.util.LinkedList;
import java.util.List;
public final class FlattenUtil {
public static List<Object> flatten(List<?> list) {
List<Object> retVal = new LinkedList<Object>();
flatten(list, retVal);
return retVal;
}
public static void flatten(List<?> fromTreeList, List<Object> toFlatList) {
for (Object item : fromTreeList) {
if (item instanceof List<?>) {
flatten((List<?>) item, toFlatList);
} else {
toFlatList.add(item);
}
}
}
} |
Flatten a list | Java 8+ | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;
public final class FlattenUtil {
public static Stream<Object> flattenToStream(List<?> list) {
return list.stream().flatMap(item ->
item instanceof List<?> ?
flattenToStream((List<?>)item) :
Stream.of(item));
}
public static List<Object> flatten(List<?> list) {
return flattenToStream(list).collect(Collectors.toList());
}
} |
Flipping bits game | Java 8 | The game:
Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.
;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
# The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a '''3x3''' array of bits.
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLevel;
private boolean solved = true;
FlippingBitsGame() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.PLAIN, 18));
box = new Rectangle(120, 90, 400, 400);
startNewGame();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (solved) {
startNewGame();
} else {
int x = e.getX();
int y = e.getY();
if (box.contains(x, y))
return;
if (x > box.x && x < box.x + box.width) {
flipCol((x - box.x) / (box.width / n));
} else if (y > box.y && y < box.y + box.height)
flipRow((y - box.y) / (box.height / n));
if (solved(grid, target))
solved = true;
printGrid(solved ? "Solved!" : "The board", grid);
}
repaint();
}
});
}
void startNewGame() {
if (solved) {
n = (n == maxLevel) ? minLevel : n + 1;
grid = new int[n][n];
target = new int[n][n];
do {
shuffle();
for (int i = 0; i < n; i++)
target[i] = Arrays.copyOf(grid[i], n);
shuffle();
} while (solved(grid, target));
solved = false;
printGrid("The target", target);
printGrid("The board", grid);
}
}
void printGrid(String msg, int[][] g) {
System.out.println(msg);
for (int[] row : g)
System.out.println(Arrays.toString(row));
System.out.println();
}
boolean solved(int[][] a, int[][] b) {
for (int i = 0; i < n; i++)
if (!Arrays.equals(a[i], b[i]))
return false;
return true;
}
void shuffle() {
for (int i = 0; i < n * n; i++) {
if (rand.nextBoolean())
flipRow(rand.nextInt(n));
else
flipCol(rand.nextInt(n));
}
}
void flipRow(int r) {
for (int c = 0; c < n; c++) {
grid[r][c] ^= 1;
}
}
void flipCol(int c) {
for (int[] row : grid) {
row[c] ^= 1;
}
}
void drawGrid(Graphics2D g) {
g.setColor(getForeground());
if (solved)
g.drawString("Solved! Click here to play again.", 180, 600);
else
g.drawString("Click next to a row or a column to flip.", 170, 600);
int size = box.width / n;
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(getBackground());
g.drawRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Flipping Bits Game");
f.setResizable(false);
f.add(new FlippingBitsGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Floyd's triangle | Java | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
* the first row is '''1''' (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
;Task:
:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
| public class Floyd {
public static void main(String[] args){
printTriangle(5);
printTriangle(14);
}
private static void printTriangle(int n){
System.out.println(n + " rows:");
for(int rowNum = 1, printMe = 1, numsPrinted = 0;
rowNum <= n; printMe++){
int cols = (int)Math.ceil(Math.log10(n*(n-1)/2 + numsPrinted + 2));
System.out.printf("%"+cols+"d ", printMe);
if(++numsPrinted == rowNum){
System.out.println();
rowNum++;
numsPrinted = 0;
}
}
}
} |
Four bit adder | Java | "''Simulate''" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;
Finally a half adder can be made using an ''xor'' gate and an ''and'' gate.
The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.
'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
! (A half adder)
! (A full adder)
! (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
| public class GateLogic
{
// Basic gate interfaces
public interface OneInputGate
{ boolean eval(boolean input); }
public interface TwoInputGate
{ boolean eval(boolean input1, boolean input2); }
public interface MultiGate
{ boolean[] eval(boolean... inputs); }
// Create NOT
public static OneInputGate NOT = new OneInputGate() {
public boolean eval(boolean input)
{ return !input; }
};
// Create AND
public static TwoInputGate AND = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 && input2; }
};
// Create OR
public static TwoInputGate OR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{ return input1 || input2; }
};
// Create XOR
public static TwoInputGate XOR = new TwoInputGate() {
public boolean eval(boolean input1, boolean input2)
{
return OR.eval(
AND.eval(input1, NOT.eval(input2)),
AND.eval(NOT.eval(input1), input2)
);
}
};
// Create HALF_ADDER
public static MultiGate HALF_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 2)
throw new IllegalArgumentException();
return new boolean[] {
XOR.eval(inputs[0], inputs[1]), // Output bit
AND.eval(inputs[0], inputs[1]) // Carry bit
};
}
};
// Create FULL_ADDER
public static MultiGate FULL_ADDER = new MultiGate() {
public boolean[] eval(boolean... inputs)
{
if (inputs.length != 3)
throw new IllegalArgumentException();
// Inputs: CarryIn, A, B
// Outputs: S, CarryOut
boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]);
boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]);
return new boolean[] {
haOutputs2[0], // Output bit
OR.eval(haOutputs1[1], haOutputs2[1]) // Carry bit
};
}
};
public static MultiGate buildAdder(final int numBits)
{
return new MultiGate() {
public boolean[] eval(boolean... inputs)
{
// Inputs: A0, A1, A2..., B0, B1, B2...
if (inputs.length != (numBits << 1))
throw new IllegalArgumentException();
boolean[] outputs = new boolean[numBits + 1];
boolean[] faInputs = new boolean[3];
boolean[] faOutputs = null;
for (int i = 0; i < numBits; i++)
{
faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; // CarryIn
faInputs[1] = inputs[i]; // Ai
faInputs[2] = inputs[numBits + i]; // Bi
faOutputs = FULL_ADDER.eval(faInputs);
outputs[i] = faOutputs[0]; // Si
}
if (faOutputs != null)
outputs[numBits] = faOutputs[1]; // CarryOut
return outputs;
}
};
}
public static void main(String[] args)
{
int numBits = Integer.parseInt(args[0]);
int firstNum = Integer.parseInt(args[1]);
int secondNum = Integer.parseInt(args[2]);
int maxNum = 1 << numBits;
if ((firstNum < 0) || (firstNum >= maxNum))
{
System.out.println("First number is out of range");
return;
}
if ((secondNum < 0) || (secondNum >= maxNum))
{
System.out.println("Second number is out of range");
return;
}
MultiGate multiBitAdder = buildAdder(numBits);
// Convert input numbers into array of bits
boolean[] inputs = new boolean[numBits << 1];
String firstNumDisplay = "";
String secondNumDisplay = "";
for (int i = 0; i < numBits; i++)
{
boolean firstBit = ((firstNum >>> i) & 1) == 1;
boolean secondBit = ((secondNum >>> i) & 1) == 1;
inputs[i] = firstBit;
inputs[numBits + i] = secondBit;
firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay;
secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay;
}
boolean[] outputs = multiBitAdder.eval(inputs);
int outputNum = 0;
String outputNumDisplay = "";
String outputCarryDisplay = null;
for (int i = numBits; i >= 0; i--)
{
outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0);
if (i == numBits)
outputCarryDisplay = outputs[i] ? "1" : "0";
else
outputNumDisplay += (outputs[i] ? "1" : "0");
}
System.out.println("numBits=" + numBits);
System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")");
return;
}
} |
Four is magic | Java | Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.'''
'''Three is five, five is four, four is magic.'''
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)
:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.
:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.
:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.
:* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.
;Related tasks:
:* [[Four is the number of_letters in the ...]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Summarize and say sequence]]
:* [[Spelling of ordinal numbers]]
:* [[De Bruijn sequences]]
| public class FourIsMagic {
public static void main(String[] args) {
for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) {
String magic = fourIsMagic(n);
System.out.printf("%d = %s%n", n, toSentence(magic));
}
}
private static final String toSentence(String s) {
return s.substring(0,1).toUpperCase() + s.substring(1) + ".";
}
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 fourIsMagic(long n) {
if ( n == 4 ) {
return numToString(n) + " is magic";
}
String result = numToString(n);
return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length());
}
private static final String numToString(long n) {
if ( n < 0 ) {
return "negative " + numToString(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? " " + numToString(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 numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : "");
}
}
|
Four is the number of letters in the ... | Java | The '''Four is ...''' sequence is based on the counting of the number of
letters in the words of the (never-ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ***
;Definitions and directives:
:* English is to be used in spelling numbers.
:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').
:* Commas are not counted, nor are hyphens (dashes or minus signs).
:* '''twenty-three''' has eleven letters.
:* '''twenty-three''' is considered one word (which is hyphenated).
:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.
:* The American version of numbers will be used here in this task (as opposed to the British version).
'''2,000,000,000''' is two billion, ''not'' two milliard.
;Task:
:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
'''4 2 3 6 2 7'''
:* Only construct as much as is needed for the never-ending sentence.
:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.
:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
:* Show all output here.
;Test cases:
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
;Related tasks:
:* [[Four is magic]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Self-referential sequence]]
:* [[Spelling of ordinal numbers]]
;Also see:
:* See the OEIS sequence A72425 "Four is the number of letters...".
:* See the OEIS sequence A72424 "Five's the number of letters..."
| import java.util.HashMap;
import java.util.Map;
public class FourIsTheNumberOfLetters {
public static void main(String[] args) {
String [] words = neverEndingSentence(201);
System.out.printf("Display the first 201 numbers in the sequence:%n%3d: ", 1);
for ( int i = 0 ; i < words.length ; i++ ) {
System.out.printf("%2d ", numberOfLetters(words[i]));
if ( (i+1) % 25 == 0 ) {
System.out.printf("%n%3d: ", i+2);
}
}
System.out.printf("%nTotal number of characters in the sentence is %d%n", characterCount(words));
for ( int i = 3 ; i <= 7 ; i++ ) {
int index = (int) Math.pow(10, i);
words = neverEndingSentence(index);
String last = words[words.length-1].replace(",", "");
System.out.printf("Number of letters of the %s word is %d. The word is \"%s\". The sentence length is %,d characters.%n", toOrdinal(index), numberOfLetters(last), last, characterCount(words));
}
}
@SuppressWarnings("unused")
private static void displaySentence(String[] words, int lineLength) {
int currentLength = 0;
for ( String word : words ) {
if ( word.length() + currentLength > lineLength ) {
String first = word.substring(0, lineLength-currentLength);
String second = word.substring(lineLength-currentLength);
System.out.println(first);
System.out.print(second);
currentLength = second.length();
}
else {
System.out.print(word);
currentLength += word.length();
}
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
System.out.print(" ");
currentLength++;
if ( currentLength == lineLength ) {
System.out.println();
currentLength = 0;
}
}
System.out.println();
}
private static int numberOfLetters(String word) {
return word.replace(",","").replace("-","").length();
}
private static long characterCount(String[] words) {
int characterCount = 0;
for ( int i = 0 ; i < words.length ; i++ ) {
characterCount += words[i].length() + 1;
}
// Extra space counted in last loop iteration
characterCount--;
return characterCount;
}
private static String[] startSentence = new String[] {"Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,"};
private static String[] neverEndingSentence(int wordCount) {
String[] words = new String[wordCount];
int index;
for ( index = 0 ; index < startSentence.length && index < wordCount ; index++ ) {
words[index] = startSentence[index];
}
int sentencePosition = 1;
while ( index < wordCount ) {
// X in the Y
// X
sentencePosition++;
String word = words[sentencePosition-1];
for ( String wordLoop : numToString(numberOfLetters(word)).split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
// in
words[index] = "in";
index++;
if ( index == wordCount ) {
break;
}
// the
words[index] = "the";
index++;
if ( index == wordCount ) {
break;
}
// Y
for ( String wordLoop : (toOrdinal(sentencePosition) + ",").split(" ") ) {
words[index] = wordLoop;
index++;
if ( index == wordCount ) {
break;
}
}
}
return words;
}
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 ) : "");
}
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);
}
}
|
Subsets and Splits