Mind boggling card trick

Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos.

The task is to simulate the trick in a way that mimics the steps shown in the video.

; 1. Cards.
# Create a common deck of cards of 52 cards    (which are half red, half black).
# Give the pack a good shuffle.
; 2. Deal from the shuffled deck, you'll be creating three piles.
#   Assemble the cards face down.
##   Turn up the   ''top card''   and hold it in your hand.
###    if the card is         black,        then add the   ''next''   card (unseen) to the       "black"      pile.
###    If the card is     red,    then add the   ''next''   card (unseen) to the   "red"  pile.
##   Add the   ''top card''   that you're holding to the '''discard''' pile.   (You might optionally show these discarded cards to get an idea of the randomness).
# Repeat the above for the rest of the shuffled deck.
; 3. Choose a random number   (call it '''X''')   that will be used to swap cards from the "red" and "black" piles.
# Randomly choose   '''X'''   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch.
# Randomly choose   '''X'''   cards from the       "black"      pile (unseen), let's call this the      "black"       bunch.
# Put the     "red"    bunch into the         "black"      pile.
# Put the        "black"        bunch into the      "red"  pile.
# (The above two steps complete the swap of   '''X'''   cards of the "red" and "black" piles.  (Without knowing what those cards are --- they could be red or black, nobody knows).
; 4. Order from randomness?
# Verify (or not) the mathematician's assertion that:
      '''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.'''

(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)

Show output on this page.

Solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public final class MindBogglingCardTrick {

	public static void main(String[] aArgs) {
		List<Character> cards = new ArrayList<Character>(52);
		cards.addAll(Collections.nCopies(26, 'R'));
		cards.addAll(Collections.nCopies(26, 'B'));
		Collections.shuffle(cards);

		List<Character> redPile = new ArrayList<Character>();
		List<Character> blackPile = new ArrayList<Character>();
		List<Character> discardPile = new ArrayList<Character>();

		for ( int i = 0; i < 52; i += 2 ) {
			if ( cards.get(i) == 'R' ) {
				redPile.add(cards.get(i + 1));
			} else {
				blackPile.add(cards.get(i + 1));
			}
	        discardPile.add(cards.get(i));
	    }

		System.out.println("A sample run." + System.lineSeparator());
		System.out.println("After dealing the cards the state of the piles is:");
		System.out.println(String.format("    Red    : %2d cards -> %s", redPile.size(), redPile));
		System.out.println(String.format("    Black  : %2d cards -> %s", blackPile.size(), blackPile));
		System.out.println(String.format("    Discard: %2d cards -> %s", discardPile.size(), discardPile));

		ThreadLocalRandom random = ThreadLocalRandom.current();
	    final int minimumSize = Math.min(redPile.size(), blackPile.size());
	    final int choice = random.nextInt(1, minimumSize + 1);

	    List<Integer> redIndexes = IntStream.range(0, redPile.size()).boxed().collect(Collectors.toList());
	    List<Integer> blackIndexes = IntStream.range(0, blackPile.size()).boxed().collect(Collectors.toList());
	    Collections.shuffle(redIndexes);
	    Collections.shuffle(blackIndexes);
	    List<Integer> redChosenIndexes = redIndexes.subList(0, choice);
	    List<Integer> blackChosenIndexes = blackIndexes.subList(0, choice);

	    System.out.println(System.lineSeparator() + "Number of cards are to be swapped: " + choice);
	    System.out.println("The respective zero-based indices of the cards to be swapped are:");
	    System.out.println("    Red    : " + redChosenIndexes);
	    System.out.println("    Black  : " + blackChosenIndexes);

	    for ( int i = 0; i < choice; i++ ) {
	        final char temp = redPile.get(redChosenIndexes.get(i));
	        redPile.set(redChosenIndexes.get(i), blackPile.get(blackChosenIndexes.get(i)));
	        blackPile.set(blackChosenIndexes.get(i), temp);
	    }

	    System.out.println(System.lineSeparator() + "After swapping cards the state of the red and black piless is:");
	    System.out.println("    Red    : " + redPile);
	    System.out.println("    Black  : " + blackPile);

	    int redCount = 0;
	    for ( char ch : redPile ) {
	    	if ( ch == 'R' ) {
	    		redCount += 1;
	    	}
	    }

	    int blackCount = 0;
	    for ( char ch : blackPile ) {
	    	if ( ch == 'B' ) {
	    		blackCount += 1;
	    	}
	    }

	    System.out.println(System.lineSeparator() + "The number of red cards in the red pile: " + redCount);
	    System.out.println("The number of black cards in the black pile: " + blackCount);
	    if ( redCount == blackCount ) {
	    	System.out.println("So the asssertion is correct.");
	    } else {
	    	System.out.println("So the asssertion is incorrect.");
	    }
	}

}


Minimal steps down to 1

Given:
* A starting, positive integer (greater than one), N.
* A selection of possible integer perfect divisors, D.
* And a selection of possible subtractors, S.
The goal is find the minimum number of steps  necessary to reduce N down to one.

At any step, the number may be:
* Divided by any member of D if it is perfectly divided by D, (remainder zero).
* OR have one of S subtracted from it, if N is greater than the member of S.

There may be many ways to reduce the initial N down to 1. Your program needs to:
* Find the ''minimum'' number of ''steps'' to reach 1.
* Show '''one''' way of getting fron N to 1 in those minimum steps.

;Examples:
No divisors, D. a single subtractor of 1.
:Obviousely N will take N-1 subtractions of 1 to reach 1

Single divisor of 2; single subtractor of 1:
:N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
:N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1

Divisors 2 and 3; subtractor 1:
:N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1

;Task:
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:

:1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.

Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:

:3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.

;Optional stretch goal:
:2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000

;Reference:
* Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.

Solution:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MinimalStepsDownToOne {

    public static void main(String[] args) {
        runTasks(getFunctions1());
        runTasks(getFunctions2());
        runTasks(getFunctions3());
    }

    private static void runTasks(List<Function> functions) {
        Map<Integer,List<String>> minPath = getInitialMap(functions, 5);

        //  Task 1
        int max = 10;
        populateMap(minPath, functions, max);
        System.out.printf("%nWith functions:  %s%n", functions);
        System.out.printf("  Minimum steps to 1:%n");
        for ( int n = 2 ; n <= max ; n++ ) {
            int steps = minPath.get(n).size();
            System.out.printf("    %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n));
        }

        //  Task 2
        displayMaxMin(minPath, functions, 2000);

        //  Task 2a
        displayMaxMin(minPath, functions, 20000);

        //  Task 2a +
        displayMaxMin(minPath, functions, 100000);
    }

    private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
        populateMap(minPath, functions, max);
        List<Integer> maxIntegers = getMaxMin(minPath, max);
        int maxSteps = maxIntegers.remove(0);
        int numCount = maxIntegers.size();
        System.out.printf("  There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n    %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers);

    }

    private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {
        int maxSteps = Integer.MIN_VALUE;
        List<Integer> maxIntegers = new ArrayList<Integer>();
        for ( int n = 2 ; n <= max ; n++ ) {
            int len = minPath.get(n).size();
            if ( len > maxSteps ) {
                maxSteps = len;
                maxIntegers.clear();
                maxIntegers.add(n);
            }
            else if ( len == maxSteps ) {
                maxIntegers.add(n);
            }
        }
        maxIntegers.add(0, maxSteps);
        return maxIntegers;
    }

    private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
        for ( int n = 2 ; n <= max ; n++ ) {
            if ( minPath.containsKey(n) ) {
                continue;
            }
            Function minFunction = null;
            int minSteps = Integer.MAX_VALUE;
            for ( Function f : functions ) {
                if ( f.actionOk(n) ) {
                    int result = f.action(n);
                    int steps = 1 + minPath.get(result).size();
                    if ( steps < minSteps ) {
                        minFunction = f;
                        minSteps = steps;
                    }
                }
            }
            int result = minFunction.action(n);
            List<String> path = new ArrayList<String>();
            path.add(minFunction.toString(n));
            path.addAll(minPath.get(result));
            minPath.put(n, path);
        }

    }

    private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {
        Map<Integer,List<String>> minPath = new HashMap<>();
        for ( int i = 2 ; i <= max ; i++ ) {
            for ( Function f : functions ) {
                if ( f.actionOk(i) ) {
                    int result = f.action(i);
                    if ( result == 1 ) {
                        List<String> path = new ArrayList<String>();
                        path.add(f.toString(i));
                        minPath.put(i, path);
                    }
                }
            }
        }
        return minPath;
    }

    private static List<Function> getFunctions3() {
        List<Function> functions = new ArrayList<>();
        functions.add(new Divide2Function());
        functions.add(new Divide3Function());
        functions.add(new Subtract2Function());
        functions.add(new Subtract1Function());
        return functions;
    }

    private static List<Function> getFunctions2() {
        List<Function> functions = new ArrayList<>();
        functions.add(new Divide3Function());
        functions.add(new Divide2Function());
        functions.add(new Subtract2Function());
        return functions;
    }

    private static List<Function> getFunctions1() {
        List<Function> functions = new ArrayList<>();
        functions.add(new Divide3Function());
        functions.add(new Divide2Function());
        functions.add(new Subtract1Function());
        return functions;
    }

    public abstract static class Function {
        abstract public int action(int n);
        abstract public boolean actionOk(int n);
        abstract public String toString(int n);
    }

    public static class Divide2Function extends Function {
        @Override public int action(int n) {
            return n/2;
        }

        @Override public boolean actionOk(int n) {
            return n % 2 == 0;
        }

        @Override public String toString(int n) {
            return "/2 -> " + n/2;
        }

        @Override public String toString() {
            return "Divisor 2";
        }

    }

    public static class Divide3Function extends Function {
        @Override public int action(int n) {
            return n/3;
        }

        @Override public boolean actionOk(int n) {
            return n % 3 == 0;
        }

        @Override public String toString(int n) {
            return "/3 -> " + n/3;
        }

        @Override public String toString() {
            return "Divisor 3";
        }

    }

    public static class Subtract1Function extends Function {
        @Override public int action(int n) {
            return n-1;
        }

        @Override public boolean actionOk(int n) {
            return true;
        }

        @Override public String toString(int n) {
            return "-1 -> " + (n-1);
        }

        @Override public String toString() {
            return "Subtractor 1";
        }

    }

    public static class Subtract2Function extends Function {
        @Override public int action(int n) {
            return n-2;
        }

        @Override public boolean actionOk(int n) {
            return n > 2;
        }

        @Override public String toString(int n) {
            return "-2 -> " + (n-2);
        }

        @Override public String toString() {
            return "Subtractor 2";
        }

    }

}


Minimum multiple of m where digital sum equals m

Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.

;Task

* Find the first 40 elements of the sequence.

;Stretch

* Find the next 30 elements of the sequence.

;See also

;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n

Solution:
public final class MinimumMultipleDigitSum {

	public static void main(String[] aArgs) {
		for ( int n = 1; n <= 70; n++ ) {
			int k = 0;
			while ( digitSum(k += n) != n );
			System.out.print(String.format("%8d%s", k / n, ( n % 10 ) == 0 ? "\n" : " "));
		}
	}

	private static int digitSum(int aN) {
		int sum = 0;
		while ( aN > 0 ) {
			sum += aN % 10;
			aN /= 10;
		}
		return sum;
	}

}


Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.

This is simple to do, but can be challenging to do efficiently.

To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''".

;Task:

Write a routine to find the B10 of a given integer.

E.G.

       '''n'''                  '''B10'''      '''n'''  x '''multiplier'''
       1                    1    ( 1  x 1         )
       2                   10    ( 2  x 5         )
       7                 1001    ( 7  x 143       )
       9            111111111    ( 9  x 12345679  )
      10                   10    ( 10 x 1         )

and so on.

Use the routine to find and display here, on this page, the '''B10''' value for:

    1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999

Optionally find '''B10''' for:

    1998, 2079, 2251, 2277

Stretch goal; find '''B10''' for:

    2439, 2997, 4878

There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.

;See also:

:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1

Solution:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

//  Title:  Minimum positive multiple in base 10 using only 0 and 1

public class MinimumNumberOnlyZeroAndOne {

    public static void main(String[] args) {
        for ( int n : getTestCases() ) {
            BigInteger result = getA004290(n);
            System.out.printf("A004290(%d) = %s = %s * %s%n", n, result, n, result.divide(BigInteger.valueOf(n)));
        }
    }

    private static List<Integer> getTestCases() {
        List<Integer> testCases = new ArrayList<>();
        for ( int i = 1 ; i <= 10 ; i++ ) {
            testCases.add(i);
        }
        for ( int i = 95 ; i <= 105 ; i++ ) {
            testCases.add(i);
        }
        for (int i : new int[] {297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878} ) {
            testCases.add(i);
        }
        return testCases;
    }

    private static BigInteger getA004290(int n) {
        if ( n == 1 ) {
            return BigInteger.valueOf(1);
        }
        int[][] L = new int[n][n];
        for ( int i = 2 ; i < n ; i++ ) {
            L[0][i] = 0;
        }
        L[0][0] = 1;
        L[0][1] = 1;
        int m = 0;
        BigInteger ten = BigInteger.valueOf(10);
        BigInteger nBi = BigInteger.valueOf(n);
        while ( true ) {
            m++;
            //  if L[m-1, (-10^m) mod n] = 1 then break
            if ( L[m-1][mod(ten.pow(m).negate(), nBi).intValue()] == 1 ) {
                break;
            }
            L[m][0] = 1;
            for ( int k = 1 ; k < n ; k++ ) {
                //L[m][k] = Math.max(L[m-1][k], L[m-1][mod(k-pow(10,m), n)]);
                L[m][k] = Math.max(L[m-1][k], L[m-1][mod(BigInteger.valueOf(k).subtract(ten.pow(m)), nBi).intValue()]);
            }

        }
        //int r = pow(10,m);
        //int k = mod(-pow(10,m), n);
        BigInteger r = ten.pow(m);
        BigInteger k = mod(r.negate(), nBi);
        for ( int j = m-1 ; j >= 1 ; j-- ) {
            if ( L[j-1][k.intValue()] == 0 ) {
                //r = r + pow(10, j);
                //k = mod(k-pow(10, j), n);
                r = r.add(ten.pow(j));
                k = mod(k.subtract(ten.pow(j)), nBi);
            }
        }
        if ( k.compareTo(BigInteger.ONE) == 0 ) {
            r = r.add(BigInteger.ONE);
        }
        return r;
    }

    private static BigInteger mod(BigInteger m, BigInteger n) {
        BigInteger result = m.mod(n);
        if ( result.compareTo(BigInteger.ZERO) < 0 ) {
            result = result.add(n);
        }
        return result;
    }

    @SuppressWarnings("unused")
    private static int mod(int m, int n) {
        int result = m % n;
        if ( result < 0 ) {
            result += n;
        }
        return result;
    }

    @SuppressWarnings("unused")
    private static int pow(int base, int exp) {
        return (int) Math.pow(base, exp);
    }
}


Modified random distribution

Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by  function modifier:
while True:
    random1 = rgen()
    random2 = rgen()
    if random2 < modifier(random1):
        answer = random1
        break
    endif
endwhile

;Task:
* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:
                       modifier(x)  =  2*(0.5 - x)  if x < 0.5  else 2*(x - 0.5)
* Create a generator of random numbers with probabilities modified by the above function.
* Generate >= 10,000 random numbers subject to the probability modification.
* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.

Show your output here, on this page.

Solution:
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;

interface ModifierInterface {
	double modifier(double aDouble);
}

public final class ModifiedRandomDistribution222 {

	public static void main(String[] aArgs) {
		final int sampleSize = 100_000;
		final int binCount = 20;
		final double binSize = 1.0 / binCount;

		List<Integer> bins = Stream.generate( () -> 0 ).limit(binCount).toList();

	    for ( int i = 0; i < sampleSize; i++ ) {
	    	double random = modifiedRandom(modifier);
	        int binNumber = (int) Math.floor(random / binSize);
	        bins.set(binNumber, bins.get(binNumber) + 1);
	    }

		System.out.println("Modified random distribution with " + sampleSize + " samples in range [0, 1):");
		System.out.println();
		System.out.println("    Range           		  Number of samples within range");

		final int scaleFactor = 125;
		for ( int i = 0; i < binCount; i++ ) {
			String histogram = String.valueOf("#").repeat(bins.get(i) / scaleFactor);
			System.out.println(String.format("%4.2f ..< %4.2f %s %s",
				(float) i / binCount, (float) ( i + 1.0 ) / binCount, histogram, bins.get(i)));
		}
	}

	private static double modifiedRandom(ModifierInterface aModifier) {
		double result = -1.0;

		while ( result < 0.0 ) {
			double randomOne = RANDOM.nextDouble();
			double randomTwo = RANDOM.nextDouble();
			if ( randomTwo < aModifier.modifier(randomOne) ) {
				result = randomOne;
			}
		}

		return result;
	}

	private static ModifierInterface modifier = aX -> ( aX < 0.5 ) ? 2 * ( 0.5 - aX ) : 2 * ( aX - 0.5 );

	private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();

}


Modular arithmetic

equivalence relation called ''congruence''.

For any positive integer p called the ''congruence modulus'',
two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:
:a = b + k\,p

The corresponding set of multiplicative inverse for this task.

Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.

The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.

You will use the following function for demonstration:
:f(x) = x^{100} + x + 1
You will use 13 as the congruence modulus and you will compute f(10).

It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.

Solution:
public class ModularArithmetic {
    private interface Ring<T> {
        Ring<T> plus(Ring<T> rhs);

        Ring<T> times(Ring<T> rhs);

        int value();

        Ring<T> one();

        default Ring<T> pow(int p) {
            if (p < 0) {
                throw new IllegalArgumentException("p must be zero or greater");
            }

            int pp = p;
            Ring<T> pwr = this.one();
            while (pp-- > 0) {
                pwr = pwr.times(this);
            }
            return pwr;
        }
    }

    private static class ModInt implements Ring<ModInt> {
        private int value;
        private int modulo;

        private ModInt(int value, int modulo) {
            this.value = value;
            this.modulo = modulo;
        }

        @Override
        public Ring<ModInt> plus(Ring<ModInt> other) {
            if (!(other instanceof ModInt)) {
                throw new IllegalArgumentException("Cannot add an unknown ring.");
            }
            ModInt rhs = (ModInt) other;
            if (modulo != rhs.modulo) {
                throw new IllegalArgumentException("Cannot add rings with different modulus");
            }
            return new ModInt((value + rhs.value) % modulo, modulo);
        }

        @Override
        public Ring<ModInt> times(Ring<ModInt> other) {
            if (!(other instanceof ModInt)) {
                throw new IllegalArgumentException("Cannot multiple an unknown ring.");
            }
            ModInt rhs = (ModInt) other;
            if (modulo != rhs.modulo) {
                throw new IllegalArgumentException("Cannot multiply rings with different modulus");
            }
            return new ModInt((value * rhs.value) % modulo, modulo);
        }

        @Override
        public int value() {
            return value;
        }

        @Override
        public Ring<ModInt> one() {
            return new ModInt(1, modulo);
        }

        @Override
        public String toString() {
            return String.format("ModInt(%d, %d)", value, modulo);
        }
    }

    private static <T> Ring<T> f(Ring<T> x) {
        return x.pow(100).plus(x).plus(x.one());
    }

    public static void main(String[] args) {
        ModInt x = new ModInt(10, 13);
        Ring<ModInt> y = f(x);
        System.out.print("x ^ 100 + x + 1 for x = ModInt(10, 13) is ");
        System.out.println(y);
        System.out.flush();
    }
}


Modular exponentiation

Find the last   '''40'''   decimal digits of   a^b,   where

::*   a = 2988348162058574136915891421498819466320163312926952423791023078876139
::*   b = 2351399303373464486466122544523690094744975233415544072992656881240319

A computer is too slow to find the entire value of   a^b.

Instead, the program must use a fast algorithm for modular exponentiation:   a^b \mod m.

The algorithm must work for any integers   a, b, m,     where   b \ge 0   and   m > 0.

Solution:
import java.math.BigInteger;

public class PowMod {
    public static void main(String[] args){
        BigInteger a = new BigInteger(
      "2988348162058574136915891421498819466320163312926952423791023078876139");
        BigInteger b = new BigInteger(
      "2351399303373464486466122544523690094744975233415544072992656881240319");
        BigInteger m = new BigInteger("10000000000000000000000000000000000000000");

        System.out.println(a.modPow(b, m));
    }
}


Modular inverse

From Wikipedia:

In modulo    ''m''    is an integer    ''x''    such that

::a\,x \equiv 1 \pmod{m}.

Or in other words, such that:

::\exists k \in\Z,\qquad a\, x = 1 + k\,m

It can be shown that such an inverse exists   if and only if    ''a''    and    ''m''    are coprime,   but we will ignore this for this task.

;Task:
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language,   compute the modular inverse of   42 modulo 2017.

Solution: System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));


Monads/Maybe monad

Demonstrate in your programming language the following:

#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind

A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.

A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.

Solution:
import java.util.Optional;

public final class MonadMaybe {

	public static void main(String[] aArgs) {
	    System.out.println(doubler(5).flatMap(MonadMaybe::stringify).get());

	    System.out.println(doubler(2).flatMap(MonadMaybe::stringifyNullable).get());

	    Optional<String> option = doubler(0).flatMap(MonadMaybe::stringifyNullable);

	    String result = option.isPresent() ? option.get() : "Result is Null";

	    System.out.println(result);
	}

	private static Optional<Integer> doubler(int aN) {
		return Optional.of(2 * aN);
	}

	private static Optional<String> stringify(int aN) {
		return Optional.of("A".repeat(aN));
	}

	private static Optional<String> stringifyNullable(int aN) {
		return ( aN > 0 ) ? Optional.ofNullable("A".repeat(aN)) : Optional.ofNullable(null);
	}

}


Monads/Writer monad

The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.

Demonstrate in your programming language the following:

# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
# Write three simple functions: root, addOne, and half
# Derive Writer monad versions of each of these functions
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)

Solution:
import java.util.function.Function;

public final class MonadWriter {

	public static void main(String[] aArgs) {
		Monad<Double> initial = Monad.unit(5.0, "Initial value");
	    Monad<Double> result = initial.bind(MonadWriter::root).bind(MonadWriter::addOne).bind(MonadWriter::half);
	    System.out.println("The Golden Ratio is " + result.getValue() + System.lineSeparator());
	    System.out.println("This was derived as follows:"  + System.lineSeparator() + result.getText());
	}

	private static Monad<Double> root(double aD) {
		return Monad.unit(Math.sqrt(aD), "Took square root");
	}

	private static Monad<Double> addOne(double aD) {
		return Monad.unit(aD + 1.0, "Added one");
	}

	private static Monad<Double> half(double aD) {
		return Monad.unit(aD / 2.0, "Divided by two");
	}

}

final class Monad<T> {

	public static <T> Monad<T> unit(T aValue, String aText) {
		return new Monad<T>(aValue, aText);
	}

	public Monad<T> bind(Function<T, Monad<T>> aFunction) {
		Monad<T> monad = aFunction.apply(value);
		monad.text = text + monad.text;
		return monad;
	}

	public T getValue() {
		return value;
	}

	public String getText() {
		return text;
	}

	private Monad(T aValue, String aText) {
		value = aValue;
		text = String.format("%-21s%s%n", "    " + aText, ": " + aValue);
	}

	private T value;
	private String text;

}


Move-to-front algorithm

Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).

The transform in many cases acts to give frequently repeated input symbols
lower indices which is  useful in some compression algorithms.

;Encoding algorithm:

    for each symbol of the input sequence:
        output the index of the symbol in the symbol table
        move that symbol to the front of the symbol table

;Decoding algorithm:

    # Using the same starting symbol table
    for each index of the input sequence:
        output the symbol at that index of the symbol table
        move that symbol to the front of the symbol table

;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   '''a'''-to-'''z'''

:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}

Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
|  '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}

;Task:
:*   Encode and decode the following three strings of characters using the symbol table of the lowercase characters   '''a'''-to-'''z'''   as above.
:*   Show the strings and their encoding here.
:*   Add a check to ensure that the decoded string is the same as the original.

The strings are:

    broood
 bananaaa
 hiphophiphop
(Note the misspellings in the above strings.)

Solution:
import java.util.LinkedList;
import java.util.List;

public class MTF{
	public static List<Integer> encode(String msg, String symTable){
		List<Integer> output = new LinkedList<Integer>();
		StringBuilder s = new StringBuilder(symTable);
		for(char c : msg.toCharArray()){
			int idx = s.indexOf("" + c);
			output.add(idx);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output;
	}

	public static String decode(List<Integer> idxs, String symTable){
		StringBuilder output = new StringBuilder();
		StringBuilder s = new StringBuilder(symTable);
		for(int idx : idxs){
			char c = s.charAt(idx);
			output = output.append(c);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output.toString();
	}

	private static void test(String toEncode, String symTable){
		List<Integer> encoded = encode(toEncode, symTable);
		System.out.println(toEncode + ": " + encoded);
		String decoded = decode(encoded, symTable);
		System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
	}

	public static void main(String[] args){
		String symTable = "abcdefghijklmnopqrstuvwxyz";
		test("broood", symTable);
		test("bananaaa", symTable);
		test("hiphophiphop", symTable);
	}
}


Multi-dimensional array

For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.

It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.

;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.
:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.

Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).

Solution:
public class MultiDimensionalArray {
    public static void main(String[] args) {
        // create a regular 4 dimensional array and initialize successive elements to the values 1 to 120
        int m = 1;
        int[][][][] a4 = new int[5][4][3][2];
        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        a4[i][j][k][l] = m++;
                    }
                }
            }
        }

        System.out.println("First element = " + a4[0][0][0][0]);  // access and print value of first element
        a4[0][0][0][0] = 121;                                     // change value of first element
        System.out.println();

        for (int i = 0; i < a4.length; ++i) {
            for (int j = 0; j < a4[0].length; ++j) {
                for (int k = 0; k < a4[0][0].length; ++k) {
                    for (int l = 0; l < a4[0][0][0].length; ++l) {
                        System.out.printf("%4d", a4[i][j][k][l]);
                    }
                }
            }
        }
    }
}


Multifactorial

The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).

Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...

In all cases, the terms in the products are positive integers.

If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
# Write a function that given n and the degree, calculates the multifactorial.
# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.

'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.

Solution:
public class MultiFact {
	private static long multiFact(long n, int deg){
		long ans = 1;
		for(long i = n; i > 0; i -= deg){
			ans *= i;
		}
		return ans;
	}

	public static void main(String[] args){
		for(int deg = 1; deg <= 5; deg++){
			System.out.print("degree " + deg + ":");
			for(long n = 1; n <= 10; n++){
				System.out.print(" " + multiFact(n, deg));
			}
			System.out.println();
		}
	}
}


Multiple distinct objects

Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.

By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.

By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.

This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.

This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).

See also: [[Closures/Value capture]]

Solution:
public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){
	List<E> ans = new LinkedList<E>();
	try {
		for(int i=0;i<n;i++)
			ans.add(c.newInstance());//can't call new on a class object
	} catch (InstantiationException e) {
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	}
	return ans;
}

public static List<Object> getNNewObjects(int n, String className)
throws ClassNotFoundException{
	return getNNewObjects(n, Class.forName(className));
}


Multisplit

It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.

This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.

The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.

The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.

Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".

For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.

'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.

Solution:
import java.util.*;

public class MultiSplit {

    public static void main(String[] args) {
        System.out.println("Regex split:");
        System.out.println(Arrays.toString("a!===b=!=c".split("==|!=|=")));

        System.out.println("\nManual split:");
        for (String s : multiSplit("a!===b=!=c", new String[]{"==", "!=", "="}))
            System.out.printf("\"%s\" ", s);
    }

    static List<String> multiSplit(String txt, String[] separators) {
        List<String> result = new ArrayList<>();
        int txtLen = txt.length(), from = 0;

        for (int to = 0; to < txtLen; to++) {
            for (String sep : separators) {
                int sepLen = sep.length();
                if (txt.regionMatches(to, sep, 0, sepLen)) {
                    result.add(txt.substring(from, to));
                    from = to + sepLen;
                    to = from - 1; // compensate for the increment
                    break;
                }
            }
        }
        if (from < txtLen)
            result.add(txt.substring(from));
        return result;
    }
}


Munchausen numbers

A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.

('''Munchausen''' is also spelled: '''Munchhausen'''.)

For instance:    3435 = 33 + 44 + 33 + 55

;Task
Find all Munchausen numbers between   '''1'''   and   '''5000'''.

;Also see:
:* The OEIS entry:  A046253
:* The Wikipedia entry:  Perfect digit-to-digit invariant, redirected from ''Munchausen Number''

Solution:
public class Main {
    public static void main(String[] args) {
        for(int i = 0 ; i <= 5000 ; i++ ){
            int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum();
            if( i == val){
                System.out.println( i + " (munchausen)");
            }
        }
    }
}


Munchausen numbers

Solution:
public class Munchhausen {

    static final long[] cache = new long[10];

    public static void main(String[] args) {
        // Allowing 0 ^ 0 to be 0
        for (int i = 1; i < 10; i++) {
            cache[i] = (long) Math.pow(i, i);
        }
        for (long i = 0L; i <= 500_000_000L; i++) {
            if (isMunchhausen(i)) {
                System.out.println(i);
            }
        }
    }

    private static boolean isMunchhausen(long n) {
        long sum = 0, nn = n;
        do {
            sum += cache[(int)(nn % 10)];
            if (sum > n) {
                return false;
            }
            nn /= 10;
        } while (nn > 0);

        return sum == n;
    }
}


Musical scale

Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.

These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege.

For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.

For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file),  or the task can be omitted.

Solution:
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public final class MusicalScale {

	public static void main(String[] aArgs) {
		List<Double> frequencies = List.of( 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 );
		final int duration = 500;
		final int volume = 1;

		for ( int i = 0; i < 3; i++ ) {
			for ( double frequency : frequencies ) {
				musicalTone(frequency, duration, volume);
			}
		}
	}

	private static void musicalTone(double aFrequency, int aDuration, int aVolume) {
	    byte[] buffer = new byte[1];
	    AudioFormat audioFormat = getAudioFormat();

		try ( SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat) ) {
		    sourceDataLine.open(audioFormat);
		    sourceDataLine.start();

		    for ( int i = 0; i < aDuration * 8; i++ ) {
		        double angle = i / ( SAMPLE_RATE / aFrequency ) * 2 * Math.PI;
		        buffer[0] = (byte) ( Math.sin(angle) * 127 * aVolume );
		        sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length);
		    }

		    sourceDataLine.drain();
		    sourceDataLine.stop();
		    sourceDataLine.close();
		} catch (LineUnavailableException exception) {
			exception.printStackTrace();
		}
	}

	private static AudioFormat getAudioFormat() {
		final int sampleSizeInBits = 8;
		final int numberChannels = 1;
		final boolean signedData = true;
		final boolean isBigEndian = false;

		return new AudioFormat(SAMPLE_RATE, sampleSizeInBits, numberChannels, signedData, isBigEndian);
	}

	private static float SAMPLE_RATE = 8_000.0F;
	private static final int BYTE_OFFSET = 0;

}


Mutex

{{requires|Concurrency}}

A '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1.
A mutex is said to be seized by a [[task]] decreasing ''k''.
It is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access.
A [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.

A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order).
Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down.

=Variants of mutexes=

==Global and local mutexes==
Usually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.

==Reentrant mutex==
A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.

==Read write mutex==
A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.

=Deadlock prevention=
There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem.

=Sample implementations / APIs=

Solution:
public class Main {
    static Object mutex = new Object();
    static int i = 0;

    public void addAndPrint()
    {
        System.out.print("" + i + " + 1 = ");
        i++;
        System.out.println("" + i);
    }

    public void subAndPrint()
    {
        System.out.print("" + i + " - 1 = ");
        i--;
        System.out.println("" + i);
    }

    public static void main(String[] args){
        final Main m = new Main();
        new Thread() {
            public void run()
            {
                while (true) { synchronized(m.mutex) { m.addAndPrint(); } }
            }
        }.start();
        new Thread() {
            public void run()
            {
                while (true) { synchronized(m.mutex) { m.subAndPrint(); } }
            }
        }.start();
    }
}


N-queens problem

right

Solve the eight queens puzzle.

You can extend the problem to solve the puzzle with a board of size   '''N'''x'''N'''.

For the number of solutions for small values of   '''N''',   see   OEIS: A000170.

;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]

Solution:
public class NQueens {

  private static int[] b = new int[8];
  private static int s = 0;

  static boolean unsafe(int y) {
    int x = b[y];
    for (int i = 1; i <= y; i++) {
      int t = b[y - i];
      if (t == x ||
          t == x - i ||
          t == x + i) {
        return true;
      }
    }

    return false;
  }

  public static void putboard() {
    System.out.println("\n\nSolution " + (++s));
    for (int y = 0; y < 8; y++) {
      for (int x = 0; x < 8; x++) {
        System.out.print((b[y] == x) ? "|Q" : "|_");
      }
      System.out.println("|");
    }
  }

  public static void main(String[] args) {
    int y = 0;
    b[0] = -1;
    while (y >= 0) {
      do {
        b[y]++;
      } while ((b[y] < 8) && unsafe(y));
      if (b[y] < 8) {
        if (y < 7) {
          b[++y] = -1;
        } else {
          putboard();
        }
      } else {
        y--;
      }
    }
  }
}


Narcissist

Quoting from the Esolangs wiki page:

A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].

A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.

For concreteness, in this task we shall assume that symbol = character.

The narcissist should be able to cope with any finite input, whatever its length.

Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.

Solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Narcissist {
    private static final String SOURCE = "import java.io.BufferedReader;%nimport java.io.IOException;%nimport java.io.InputStreamReader;%n%npublic class Narcissist {%n    private static final String SOURCE = %c%s%c;%n    private static final char QUOTE = 0x22;%n%n    public static void main(String[] args) throws IOException {%n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));%n        StringBuilder sb = new StringBuilder();%n%n        while (true) {%n            String line = br.readLine();%n            if (null == line) break;%n            sb.append(line).append(System.lineSeparator());%n        }%n%n        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);%n        if (program.equals(sb.toString())) {%n            System.out.println(%caccept%c);%n        } else {%n            System.out.println(%creject%c);%n        }%n    }%n}%n";
    private static final char QUOTE = 0x22;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        while (true) {
            String line = br.readLine();
            if (null == line) break;
            sb.append(line).append(System.lineSeparator());
        }

        String program = String.format(SOURCE, QUOTE, SOURCE, QUOTE, QUOTE, QUOTE, QUOTE, QUOTE);
        if (program.equals(sb.toString())) {
            System.out.println("accept");
        } else {
            System.out.println("reject");
        }
    }
}


Narcissistic decimal number

A   Narcissistic decimal number   is a non-negative integer,   n,   that is equal to the sum of the   m-th   powers of each of the digits in the decimal representation of   n,   where   m   is the number of digits in the decimal representation of   n.

Narcissistic (decimal) numbers are sometimes called   '''Armstrong'''   numbers, named after Michael F. Armstrong.
They are also known as   '''Plus Perfect'''   numbers.

;An example:
::::*   if   n   is   '''153'''
::::*   then   m,   (the number of decimal digits)   is   '''3'''
::::*   we have    13 + 53 + 33   =   1 + 125 + 27   =   '''153'''
::::*   and so   '''153'''   is a narcissistic decimal number

;Task:
Generate and show here the first   '''25'''   narcissistic decimal numbers.

Note:   0^1 = 0,   the first in the series.

;See also:
*   the  OEIS entry:     Armstrong (or Plus Perfect, or narcissistic) numbers.
*   MathWorld entry:   Narcissistic Number.
*   Wikipedia entry:     Narcissistic number.

Solution:
public class Narc{
	public static boolean isNarc(long x){
		if(x < 0) return false;

		String xStr = Long.toString(x);
		int m = xStr.length();
		long sum = 0;

		for(char c : xStr.toCharArray()){
			sum += Math.pow(Character.digit(c, 10), m);
		}
		return sum == x;
	}

	public static void main(String[] args){
		for(long x = 0, count = 0; count < 25; x++){
			if(isNarc(x)){
				System.out.print(x + " ");
				count++;
			}
		}
	}
}


Narcissistic decimal number

Solution:
import java.util.stream.IntStream;
public class NarcissisticNumbers {
    static int numbersToCalculate = 25;
    static int numbersCalculated = 0;

    public static void main(String[] args) {
        IntStream.iterate(0, n -> n + 1).limit(Integer.MAX_VALUE).boxed().forEach(i -> {
            int length = i.toString().length();
            int addedDigits = 0;

            for (int count = 0; count < length; count++) {
                int value = Integer.parseInt(String.valueOf(i.toString().charAt(count)));
                addedDigits += Math.pow(value, length);
            }

            if (i == addedDigits) {
                numbersCalculated++;
                System.out.print(addedDigits + " ");
            }

            if (numbersCalculated == numbersToCalculate) {
                System.exit(0);
            }
        });
    }
}


Nautical bell

Task

Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.

The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.

It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.

;Related task:
* [[Sleep]]

Solution:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class NauticalBell extends Thread {

    public static void main(String[] args) {
        NauticalBell bells = new NauticalBell();
        bells.setDaemon(true);
        bells.start();
        try {
            bells.join();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }

    @Override
    public void run() {
        DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        int numBells = 0;
        long time = System.currentTimeMillis();
        long next = time - (time % (24 * 60 * 60 * 1000)); // midnight

        while (next < time) {
            next += 30 * 60 * 1000; // 30 minutes
            numBells = 1 + (numBells % 8);
        }

        while (true) {
            long wait = 100L;
            time = System.currentTimeMillis();
            if (time - next >= 0) {
                String bells = numBells == 1 ? "bell" : "bells";
                String timeString = sdf.format(time);
                System.out.printf("%s : %d %s\n", timeString, numBells, bells);
                next += 30 * 60 * 1000;
                wait = next - time;
                numBells = 1 + (numBells % 8);
            }
            try {
                Thread.sleep(wait);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}


Negative base numbers

Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia

;Task:

*Encode the decimal number 10 as negabinary (expect 11110)
*Encode the decimal number 146 as negaternary (expect 21102)
*Encode the decimal number 15 as negadecimal (expect 195)
*In each of the above cases, convert the encoded number back to decimal.

;extra credit:

* supply an integer, that when encoded to base   -62   (or something "higher"),   expresses the name of the language being used   (with correct capitalization).   If the computer language has non-alphanumeric characters,   try to encode them into the negatory numerals,   or use other characters instead.

Solution:
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class NegativeBaseNumbers {
    private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private static String encodeNegBase(long n, int b) {
        if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
        if (n == 0) return "0";
        StringBuilder out = new StringBuilder();
        long nn = n;
        while (nn != 0) {
            int rem = (int) (nn % b);
            nn /= b;
            if (rem < 0) {
                nn++;
                rem -= b;
            }
            out.append(DIGITS.charAt(rem));
        }
        out.reverse();
        return out.toString();
    }

    private static long decodeNegBase(String ns, int b) {
        if (b < -62 || b > -1) throw new IllegalArgumentException("Parameter b is out of bounds");
        if (Objects.equals(ns, "0")) return 0;
        long total = 0;
        long bb = 1;
        for (int i = ns.length() - 1; i >= 0; i--) {
            char c = ns.charAt(i);
            total += DIGITS.indexOf(c) * bb;
            bb *= b;
        }
        return total;
    }

    public static void main(String[] args) {
        List<Map.Entry<Long, Integer>> nbl = List.of(
                Map.entry(10L, -2),
                Map.entry(146L, -3),
                Map.entry(15L, -10),
                Map.entry(-4393346L, -62)
        );
        for (Map.Entry<Long, Integer> p : nbl) {
            String ns = encodeNegBase(p.getKey(), p.getValue());
            System.out.printf("%12d encoded in base %-3d = %s\n", p.getKey(), p.getValue(), ns);
            long n = decodeNegBase(ns, p.getValue());
            System.out.printf("%12s decoded in base %-3d = %d\n\n", ns, p.getValue(), n);
        }
    }
}


Nested function

In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.

;Task:
Write a program consisting of two nested functions that prints the following text.

 1. first
 2. second
 3. third

The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.

The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.

;References:
:* Nested function

Solution:
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

public class NestedFunctionsDemo {

    static String makeList(String separator) {
        AtomicInteger counter = new AtomicInteger(1);

        Function<String, String> makeItem = item -> counter.getAndIncrement() + separator + item + "\n";

        return makeItem.apply("first") + makeItem.apply("second") + makeItem.apply("third");
    }

    public static void main(String[] args) {
        System.out.println(makeList(". "));
    }
}


Next highest int from digits

Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.

*   Numbers will not be padded to the left with zeroes.
*   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
*   If there is no next highest integer return zero.

:*1   Alternatively phrased as:   "Find the smallest integer larger than the (positive or zero) integer   '''N'''
:: which can be obtained by reordering the (base ten) digits of   '''N'''".

;Algorithm 1:
#   Generate all the permutations of the digits and sort into numeric order.
#   Find the number in the list.
#   Return the next highest number from the list.

The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.

;Algorithm 2:
#   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
#   Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.
#   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)

'''E.g.:'''

    n = 12453

    12_4_53

    12_5_43

    12_5_34

    return: 12534

This second algorithm is faster and more memory efficient, but implementations
may be harder to test.

One method of testing, (as used in developing the task),   is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.

;Task requirements:
Calculate the next highest int from the digits of the following numbers:
:*   0
:*   9
:*   12
:*   21
:*   12453
:*   738440
:*   45072010
:*   95322020

;Optional stretch goal:
:*   9589776899767587796600

Solution:
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NextHighestIntFromDigits {

    public static void main(String[] args) {
        for ( String s : new String[] {"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600", "3345333"} ) {
            System.out.printf("%s -> %s%n", format(s), format(next(s)));
        }
        testAll("12345");
        testAll("11122");
    }

    private static NumberFormat FORMAT = NumberFormat.getNumberInstance();

    private static String format(String s) {
        return FORMAT.format(new BigInteger(s));
    }

    private static void testAll(String s) {
        System.out.printf("Test all permutations of:  %s%n", s);
        String sOrig = s;
        String sPrev = s;
        int count = 1;

        //  Check permutation order.  Each is greater than the last
        boolean orderOk = true;
        Map <String,Integer> uniqueMap = new HashMap<>();
        uniqueMap.put(s, 1);
        while ( (s = next(s)).compareTo("0") != 0 ) {
            count++;
            if ( Long.parseLong(s) < Long.parseLong(sPrev) ) {
                orderOk = false;
            }
            uniqueMap.merge(s, 1, (v1, v2) -> v1 + v2);
            sPrev = s;
        }
        System.out.printf("    Order:  OK =  %b%n", orderOk);

        //  Test last permutation
        String reverse = new StringBuilder(sOrig).reverse().toString();
        System.out.printf("    Last permutation:  Actual = %s, Expected = %s, OK = %b%n", sPrev, reverse, sPrev.compareTo(reverse) == 0);

        //  Check permutations unique
        boolean unique = true;
        for ( String key : uniqueMap.keySet() ) {
            if ( uniqueMap.get(key) > 1 ) {
                unique = false;
            }
        }
        System.out.printf("    Permutations unique:  OK =  %b%n", unique);

        //  Check expected count.
        Map<Character,Integer> charMap = new HashMap<>();
        for ( char c : sOrig.toCharArray() ) {
            charMap.merge(c, 1, (v1, v2) -> v1 + v2);
        }
        long permCount = factorial(sOrig.length());
        for ( char c : charMap.keySet() ) {
            permCount /= factorial(charMap.get(c));
        }
        System.out.printf("    Permutation count:  Actual = %d, Expected = %d, OK = %b%n", count, permCount, count == permCount);

    }

    private static long factorial(long n) {
        long fact = 1;
        for (long num = 2 ; num <= n ; num++ ) {
            fact *= num;
        }
        return fact;
    }

    private static String next(String s) {
        StringBuilder sb = new StringBuilder();
        int index = s.length()-1;
        //  Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
        while ( index > 0 && s.charAt(index-1) >= s.charAt(index)) {
            index--;
        }
        //  Reached beginning.  No next number.
        if ( index == 0 ) {
            return "0";
        }

        //  Find digit on the right that is both more than it, and closest to it.
        int index2 = index;
        for ( int i = index + 1 ; i < s.length() ; i++ ) {
            if ( s.charAt(i) < s.charAt(index2) && s.charAt(i) > s.charAt(index-1) ) {
                index2 = i;
            }
        }

        //  Found data, now build string
        //  Beginning of String
        if ( index > 1 ) {
            sb.append(s.subSequence(0, index-1));
        }

        //  Append found, place next
        sb.append(s.charAt(index2));

        //  Get remaining characters
        List<Character> chars = new ArrayList<>();
        chars.add(s.charAt(index-1));
        for ( int i = index ; i < s.length() ; i++ ) {
            if ( i != index2 ) {
                chars.add(s.charAt(i));
            }
        }

        //  Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
        Collections.sort(chars);
        for ( char c : chars ) {
            sb.append(c);
        }
        return sb.toString();
    }
}


Nim game

Nim is a simple game where the second player-if they know the trick-will always win.

The game has only 3 rules:
::*   start with   '''12'''   tokens
::*   each player takes    '''1,  2,  or  3'''   tokens in turn
::*  the player who takes the last token wins.

To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3; if the first player takes 2,   the second should take 2; and if the first player takes 3,   the second player will take 1.

;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.

Solution:
import java.util.Scanner;

public class NimGame {

    public static void main(String[] args) {
        runGame(12);
    }

    private static void runGame(int tokens) {
        System.out.printf("Nim game.%n%n");

        Scanner in = new Scanner(System.in);;

        do {
            boolean humanInputOk = false;
            int humanTokens = 0;
            while ( ! humanInputOk ) {
                System.out.printf("Human takes how many tokens?  ");
                String input = in.next();
                try {
                    humanTokens = Integer.parseInt(input);
                    if ( humanTokens >= 1 && humanTokens <= 3 ) {
                        humanInputOk = true;
                    }
                    else {
                        System.out.printf("Try a number between 1 and 3.%n");
                    }
                }
                catch (NumberFormatException e) {
                    System.out.printf("Invalid input.  Try a number between 1 and 3.%n");
                }
            }

            tokens -= humanTokens;

            System.out.printf("You take %d token%s.%n%d token%s remaining.%n%n", humanTokens, humanTokens > 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
            if ( tokens == 0 ) {
                System.out.printf("You win!!.%n%n");
                break;
            }
            int computerTokens = 4 - humanTokens;
            tokens -= computerTokens;

            System.out.printf("Computer takes %d token%s.%n%d token%s remaining.%n%n", computerTokens, computerTokens != 1 ? "s" : "", tokens, tokens != 1 ? "s" : "");
            if ( tokens == 0 ) {
                System.out.printf("Computer wins!!.%n%n");
            }

        } while (tokens > 0);

        in.close();
    }

}


Non-transitive dice

Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
number of faces and the numbers on each face).

Throwing dice will randomly select a face on each die with equal probability.
To show which die of dice thrown multiple times is more likely to win over the
others:
# calculate all possible combinations of different faces from each die
# Count how many times each die wins a combination
# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.

'''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.
'''
;Example 1:
If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its
faces then the equal possibility outcomes from throwing both, and the winners
is:

    X   Y   Winner
    =   =   ======
    1   2   Y
    1   3   Y
    1   4   Y
    3   2   X
    3   3   -
    3   4   Y
    6   2   X
    6   3   X
    6   4   X

    TOTAL WINS: X=4, Y=4

Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y

;Transitivity:
In mathematics transitivity are rules like:
    if a op b and b op c then a op c
If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers
we get the familiar if a < b and b < c then a < c

;Non-transitive dice
These are an ordered list of dice where the '>' operation between successive
dice pairs applies but a comparison between the first and last of the list
yields the opposite result, '<'.
''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''

Three dice S, T, U with appropriate face values could satisfy

    S < T, T < U and yet S > U

To be non-transitive.

;Notes:

* The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms).
* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4
* '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.

;Task:
;====
Find all the ordered lists of ''three'' non-transitive dice S, T, U of the form
S < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''
, (unique w.r.t the notes), possible by having selections from the integers
''one to four'' on any dies face.

Solution can be found by generating all possble individual die then testing all
possible permutations, (permutations are ordered), of three dice for
non-transitivity.

;Optional stretch goal:
Find lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.

Show the results here, on this page.

;References:
* The Most Powerful Dice - Numberphile Video.
* Nontransitive dice - Wikipedia.

Solution:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    private static List<List<Integer>> fourFaceCombos() {
        List<List<Integer>> res = new ArrayList<>();
        Set<Integer> found = new HashSet<>();

        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 4; j++) {
                for (int k = 1; k <= 4; k++) {
                    for (int l = 1; l <= 4; l++) {
                        List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());

                        int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);
                        if (found.add(key)) {
                            res.add(c);
                        }
                    }
                }
            }
        }

        return res;
    }

    private static int cmp(List<Integer> x, List<Integer> y) {
        int xw = 0;
        int yw = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (x.get(i) > y.get(j)) {
                    xw++;
                } else if (x.get(i) < y.get(j)) {
                    yw++;
                }
            }
        }
        return Integer.compare(xw, yw);
    }

    private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {
        int c = cs.size();
        List<List<List<Integer>>> res = new ArrayList<>();

        for (int i = 0; i < c; i++) {
            for (int j = 0; j < c; j++) {
                if (cmp(cs.get(i), cs.get(j)) == -1) {
                    for (List<Integer> kl : cs) {
                        if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {
                            res.add(List.of(cs.get(i), cs.get(j), kl));
                        }
                    }
                }
            }
        }

        return res;
    }

    private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {
        int c = cs.size();
        List<List<List<Integer>>> res = new ArrayList<>();

        for (int i = 0; i < c; i++) {
            for (int j = 0; j < c; j++) {
                if (cmp(cs.get(i), cs.get(j)) == -1) {
                    for (int k = 0; k < cs.size(); k++) {
                        if (cmp(cs.get(j), cs.get(k)) == -1) {
                            for (List<Integer> ll : cs) {
                                if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {
                                    res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));
                                }
                            }
                        }
                    }
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {
        List<List<Integer>> combos = fourFaceCombos();
        System.out.printf("Number of eligible 4-faced dice: %d%n", combos.size());
        System.out.println();

        List<List<List<Integer>>> it3 = findIntransitive3(combos);
        System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size());
        for (List<List<Integer>> a : it3) {
            System.out.println(a);
        }
        System.out.println();

        List<List<List<Integer>>> it4 = findIntransitive4(combos);
        System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size());
        for (List<List<Integer>> a : it4) {
            System.out.println(a);
        }
    }
}


Nonoblock

Nonogram puzzle.

;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.

;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.

;Enumerate the following configurations:
#   '''5'''   cells   and   '''[2, 1]'''   blocks
#   '''5'''   cells   and   '''[]'''   blocks   (no blocks)
#   '''10'''   cells   and   '''[8]'''   blocks
#   '''15'''   cells   and   '''[2, 3, 2, 3]'''   blocks
#   '''5'''   cells   and   '''[2, 3]'''   blocks   (should give some indication of this not being possible)

;Example:
Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:

    |_|_|_|_|_| # 5 cells and [2, 1] blocks

And would expand to the following 3 possible rows of block positions:

    |A|A|_|B|_|
    |A|A|_|_|B|
    |_|A|A|_|B|

Note how the sets of blocks are always separated by a space.

Note also that it is not necessary for each block to have a separate letter.
Output approximating

This:
                        |#|#|_|#|_|
                        |#|#|_|_|#|
                        |_|#|#|_|#|

This would also work:
                        ##.#.
                        ##..#
                       .##.#

;An algorithm:
* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).
* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.
* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.

(This is the algorithm used in the [[Nonoblock#Python]] solution).

;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.

Solution:
import java.util.*;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;

public class Nonoblock {

    public static void main(String[] args) {
        printBlock("21", 5);
        printBlock("", 5);
        printBlock("8", 10);
        printBlock("2323", 15);
        printBlock("23", 5);
    }

    static void printBlock(String data, int len) {
        int sumChars = data.chars().map(c -> Character.digit(c, 10)).sum();
        String[] a = data.split("");

        System.out.printf("%nblocks %s, cells %s%n", Arrays.toString(a), len);
        if (len - sumChars <= 0) {
            System.out.println("No solution");
            return;
        }

        List<String> prep = stream(a).filter(x -> !"".equals(x))
                .map(x -> repeat(Character.digit(x.charAt(0), 10), "1"))
                .collect(toList());

        for (String r : genSequence(prep, len - sumChars + 1))
            System.out.println(r.substring(1));
    }

    // permutation generator, translated from Python via D
    static List<String> genSequence(List<String> ones, int numZeros) {
        if (ones.isEmpty())
            return Arrays.asList(repeat(numZeros, "0"));

        List<String> result = new ArrayList<>();
        for (int x = 1; x < numZeros - ones.size() + 2; x++) {
            List<String> skipOne = ones.stream().skip(1).collect(toList());
            for (String tail : genSequence(skipOne, numZeros - x))
                result.add(repeat(x, "0") + ones.get(0) + tail);
        }
        return result;
    }

    static String repeat(int n, String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++)
            sb.append(s);
        return sb.toString();
    }
}


Nonogram solver

nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.

Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.

;Example
Problem:                 Solution:

. . . . . . . .  3       . # # # . . . .  3
. . . . . . . .  2 1     # # . # . . . .  2 1
. . . . . . . .  3 2     . # # # . . # #  3 2
. . . . . . . .  2 2     . . # # . . # #  2 2
. . . . . . . .  6       . . # # # # # #  6
. . . . . . . .  1 5     # . # # # # # .  1 5
. . . . . . . .  6       # # # # # # . .  6
. . . . . . . .  1       . . . . # . . .  1
. . . . . . . .  2       . . . # # . . .  2
1 3 1 7 5 3 4 3          1 3 1 7 5 3 4 3
2 1 5 1                  2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"

;Task
For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C

F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA

CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC

E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM

'''Extra credit''': generate nonograms with unique solutions, of desired height and width.

This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).

; Related tasks
* [[Nonoblock]].

;See also
* Arc Consistency Algorithm
* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
* http://twanvl.nl/blog/haskell/Nonograms (Haskell)
* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)

Solution:
import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;

public class NonogramSolver {

    static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};

    static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
        + "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};

    static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
        + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
        "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
        + "AAAAD BDG CEF CBDB BBB FC"};

    static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
        + "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
        + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};

    public static void main(String[] args) {
        for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
            newPuzzle(puzzleData);
    }

    static void newPuzzle(String[] data) {
        String[] rowData = data[0].split("\\s");
        String[] colData = data[1].split("\\s");

        List<List<BitSet>> cols, rows;
        rows = getCandidates(rowData, colData.length);
        cols = getCandidates(colData, rowData.length);

        int numChanged;
        do {
            numChanged = reduceMutual(cols, rows);
            if (numChanged == -1) {
                System.out.println("No solution");
                return;
            }
        } while (numChanged > 0);

        for (List<BitSet> row : rows) {
            for (int i = 0; i < cols.size(); i++)
                System.out.print(row.get(0).get(i) ? "# " : ". ");
            System.out.println();
        }
        System.out.println();
    }

    // collect all possible solutions for the given clues
    static List<List<BitSet>> getCandidates(String[] data, int len) {
        List<List<BitSet>> result = new ArrayList<>();

        for (String s : data) {
            List<BitSet> lst = new LinkedList<>();

            int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
            List<String> prep = stream(s.split(""))
                    .map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());

            for (String r : genSequence(prep, len - sumChars + 1)) {
                char[] bits = r.substring(1).toCharArray();
                BitSet bitset = new BitSet(bits.length);
                for (int i = 0; i < bits.length; i++)
                    bitset.set(i, bits[i] == '1');
                lst.add(bitset);
            }
            result.add(lst);
        }
        return result;
    }

    // permutation generator, translated from Python via D
    static List<String> genSequence(List<String> ones, int numZeros) {
        if (ones.isEmpty())
            return asList(repeat(numZeros, "0"));

        List<String> result = new ArrayList<>();
        for (int x = 1; x < numZeros - ones.size() + 2; x++) {
            List<String> skipOne = ones.stream().skip(1).collect(toList());
            for (String tail : genSequence(skipOne, numZeros - x))
                result.add(repeat(x, "0") + ones.get(0) + tail);
        }
        return result;
    }

    static String repeat(int n, String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++)
            sb.append(s);
        return sb.toString();
    }

    /* If all the candidates for a row have a value in common for a certain cell,
    then it's the only possible outcome, and all the candidates from the
    corresponding column need to have that value for that cell too. The ones
    that don't, are removed. The same for all columns. It goes back and forth,
    until no more candidates can be removed or a list is empty (failure). */

    static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
        int countRemoved1 = reduce(cols, rows);
        if (countRemoved1 == -1)
            return -1;

        int countRemoved2 = reduce(rows, cols);
        if (countRemoved2 == -1)
            return -1;

        return countRemoved1 + countRemoved2;
    }

    static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
        int countRemoved = 0;

        for (int i = 0; i < a.size(); i++) {

            BitSet commonOn = new BitSet();
            commonOn.set(0, b.size());
            BitSet commonOff = new BitSet();

            // determine which values all candidates of ai have in common
            for (BitSet candidate : a.get(i)) {
                commonOn.and(candidate);
                commonOff.or(candidate);
            }

            // remove from bj all candidates that don't share the forced values
            for (int j = 0; j < b.size(); j++) {
                final int fi = i, fj = j;

                if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
                        || (!commonOff.get(fj) && cnd.get(fi))))
                    countRemoved++;

                if (b.get(j).isEmpty())
                    return -1;
            }
        }
        return countRemoved;
    }
}


Numbers with equal rises and falls

When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right).

;Definition:
Given the decimal digits of the number are written as a series   d:
:*   A   ''rise''         is an index   i   such that    d(i)  <  d(i+1)
:*   A   ''fall''    is an index   i   such that    d(i)  >  d(i+1)

;Examples:
:*   The number          '''726,169'''   has   '''3'''   rises and   '''2'''   falls,   so it isn't in the sequence.
:*   The number     '''83,548'''    has   '''2'''   rises and   '''2'''   falls,   so it   is   in the sequence.

;Task:
:*   Print the first   '''200'''    numbers in the sequence
:*   Show that the   '''10 millionth'''   (10,000,000th)   number in the sequence is   '''41,909,002'''

;See also:
*   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls".

;Related tasks:
*   Esthetic numbers

Solution:
public class EqualRisesFalls {
    public static void main(String[] args) {
        final int limit1 = 200;
        final int limit2 = 10000000;
        System.out.printf("The first %d numbers in the sequence are:\n", limit1);
        int n = 0;
        for (int count = 0; count < limit2; ) {
            if (equalRisesAndFalls(++n)) {
                ++count;
                if (count <= limit1)
                    System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
            }
        }
        System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
    }

    private static boolean equalRisesAndFalls(int n) {
        int total = 0;
        for (int previousDigit = -1; n > 0; n /= 10) {
            int digit = n % 10;
            if (previousDigit > digit)
                ++total;
            else if (previousDigit >= 0 && previousDigit < digit)
                --total;
            previousDigit = digit;
        }
        return total == 0;
    }
}


Numeric error propagation

If   '''f''',   '''a''',   and   '''b'''   are values with uncertainties   sf,   sa,   and   sb,   and   '''c'''   is a constant;
then if   '''f'''   is derived from   '''a''',   '''b''',   and   '''c'''   in the following ways,
then   sf   can be calculated as follows:

:;Addition/Subtraction
:* If   f = a +- c,   or   f = c +- a   then   '''sf = sa'''
:* If   f = a +- b   then   '''sf2 = sa2 + sb2'''

:;Multiplication/Division
:* If   f = ca   or   f = ac       then   '''sf = |csa|'''
:* If   f = ab   or   f = a / b              then   '''sf2 = f2( (sa / a)2 + (sb / b)2)'''

:;Exponentiation
:* If   f = ac   then   '''sf = |fc(sa / a)|'''

Caution:
::This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   '''a'''   and   '''b'''   are independent and so the formula for multiplication should not be applied to   '''a*a'''   for example.   See   the talk page   for some of the implications of this issue.

;Task details:
# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.
# Given coordinates and their errors:x1 = 100 +- 1.1y1 =  50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:   d =    (x1 - x2)2   +   (y1 - y2)2
# Print and display both    '''d'''    and its error.

;References:
* A Guide to Error Propagation B. Keeney, 2005.
* Propagation of uncertainty Wikipedia.

;Related task:
*   [[Quaternion type]]

Solution:
public class Approx {
    private double value;
    private double error;

    public Approx(){this.value = this.error = 0;}

    public Approx(Approx b){
        this.value = b.value;
        this.error = b.error;
    }

    public Approx(double value, double error){
        this.value = value;
        this.error = error;
    }

    public Approx add(Approx b){
        value+= b.value;
        error = Math.sqrt(error * error + b.error * b.error);
        return this;
    }

    public Approx add(double b){
        value+= b;
        return this;
    }

    public Approx sub(Approx b){
        value-= b.value;
        error = Math.sqrt(error * error + b.error * b.error);
        return this;
    }

    public Approx sub(double b){
        value-= b;
        return this;
    }

    public Approx mult(Approx b){
        double oldVal = value;
        value*= b.value;
        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
                                  (b.error*b.error) / (b.value*b.value));
        return this;
    }

    public Approx mult(double b){
        value*= b;
        error = Math.abs(b * error);
        return this;
    }

    public Approx div(Approx b){
        double oldVal = value;
        value/= b.value;
        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
                                  (b.error*b.error) / (b.value*b.value));
        return this;
    }

    public Approx div(double b){
        value/= b;
        error = Math.abs(b * error);
        return this;
    }

    public Approx pow(double b){
        double oldVal = value;
        value = Math.pow(value, b);
        error = Math.abs(value * b * (error / oldVal));
        return this;
    }

    @Override
    public String toString(){return value+"±"+error;}

    public static void main(String[] args){
        Approx x1 = new Approx(100, 1.1);
        Approx y1 = new Approx(50, 1.2);
        Approx x2 = new Approx(200, 2.2);
        Approx y2 = new Approx(100, 2.3);

        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);

        System.out.println(x1);
    }
}


Odd word problem

Write a program that solves the odd word problem with the restrictions given below.

;Description:
You are promised an input stream consisting of English letters and punctuations.

It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long,   and
* a full stop (a period, [.]) appears after, and only after, the last word.

;Example:
A stream with six words:
:: what,is,the;meaning,of:life.

The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.

;Test cases:
Work on both the   "life"   example given above, and also the text:
:: we,are;not,in,kansas;any,more.

Solution:
public class OddWord {
    interface CharHandler {
	CharHandler handle(char c) throws Exception;
    }
    final CharHandler fwd = new CharHandler() {
	public CharHandler handle(char c) {
	    System.out.print(c);
	    return (Character.isLetter(c) ? fwd : rev);
	}
    };
    class Reverser extends Thread implements CharHandler {
	Reverser() {
	    setDaemon(true);
	    start();
	}
	private Character ch; // For inter-thread comms
	private char recur() throws Exception {
	    notify();
	    while (ch == null) wait();
	    char c = ch, ret = c;
	    ch = null;
	    if (Character.isLetter(c)) {
		ret = recur();
		System.out.print(c);
	    }
	    return ret;
	}
	public synchronized void run() {
	    try {
		while (true) {
		    System.out.print(recur());
		    notify();
		}
	    } catch (Exception e) {}
	}
	public synchronized CharHandler handle(char c) throws Exception {
	    while (ch != null) wait();
	    ch = c;
	    notify();
	    while (ch != null) wait();
	    return (Character.isLetter(c) ? rev : fwd);
	}
    }
    final CharHandler rev = new Reverser();

    public void loop() throws Exception {
	CharHandler handler = fwd;
	int c;
	while ((c = System.in.read()) >= 0) {
	    handler = handler.handle((char) c);
	}
    }

    public static void main(String[] args) throws Exception {
	new OddWord().loop();
    }
}