Evolutionary algorithm

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.

Solution:
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

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.

Solution:
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****

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.

Solution:
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

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.

Solution:
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

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]]

Solution: 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

{{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.

Solution:
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

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]]

Solution:
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

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

Solution:
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

Solution:
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

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

Solution:
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

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'''

Solution:
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

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))

Solution:
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

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

Solution:
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

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.

Solution:
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

Calculate the Feigenbaum constant.

;See:
:*   Details in the Wikipedia article:   Feigenbaum constant.

Solution:
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

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

Solution:
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

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]]

Solution:
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

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]]

Solution:
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

Solution:
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

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

Solution:
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

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.

Solution:
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

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]]

Solution:
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

{{selection|Short Circuit|Console Program Basics}}

;Task:
Find the limit of recursion.

Solution:
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

*   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''.

Solution:
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

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].

Solution:
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

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) .

Solution:
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

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]]

Solution:
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

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]])

Solution:
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

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]]

Solution:
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

Solution:
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

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.

Solution:
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

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]]

Solution:
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

Solution:
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());
	}
}