title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Vector products | Java 1.5+ | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
* '''The dot product''' (a scalar quantity)
:::: A * B = a1b1 + a2b2 + a3b3
* '''The cross product''' (a vector quantity)
:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
* '''The scalar triple product''' (a scalar quantity)
:::: A * (B x C)
* '''The vector triple product''' (a vector quantity)
:::: A x (B x C)
;Task:
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
# Create a named function/subroutine/method to compute the dot product of two vectors.
# Create a function to compute the cross product of two vectors.
# Optionally create a function to compute the scalar triple product of three vectors.
# Optionally create a function to compute the vector triple product of three vectors.
# Compute and display: a * b
# Compute and display: a x b
# Compute and display: a * (b x c), the scalar triple product.
# Compute and display: a x (b x c), the vector triple product.
;References:
* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.
* Wikipedia dot product.
* Wikipedia cross product.
* Wikipedia triple product.
;Related tasks:
* [[Dot product]]
* [[Quaternion type]]
| public class VectorProds{
public static class Vector3D<T extends Number>{
private T a, b, c;
public Vector3D(T a, T b, T c){
this.a = a;
this.b = b;
this.c = c;
}
public double dot(Vector3D<?> vec){
return (a.doubleValue() * vec.a.doubleValue() +
b.doubleValue() * vec.b.doubleValue() +
c.doubleValue() * vec.c.doubleValue());
}
public Vector3D<Double> cross(Vector3D<?> vec){
Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue();
Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue();
Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue();
return new Vector3D<Double>(newA, newB, newC);
}
public double scalTrip(Vector3D<?> vecB, Vector3D<?> vecC){
return this.dot(vecB.cross(vecC));
}
public Vector3D<Double> vecTrip(Vector3D<?> vecB, Vector3D<?> vecC){
return this.cross(vecB.cross(vecC));
}
@Override
public String toString(){
return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">";
}
}
public static void main(String[] args){
Vector3D<Integer> a = new Vector3D<Integer>(3, 4, 5);
Vector3D<Integer> b = new Vector3D<Integer>(4, 3, 5);
Vector3D<Integer> c = new Vector3D<Integer>(-5, -12, -13);
System.out.println(a.dot(b));
System.out.println(a.cross(b));
System.out.println(a.scalTrip(b, c));
System.out.println(a.vecTrip(b, c));
}
} |
Vector products | Java 1.8+ | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
* '''The dot product''' (a scalar quantity)
:::: A * B = a1b1 + a2b2 + a3b3
* '''The cross product''' (a vector quantity)
:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
* '''The scalar triple product''' (a scalar quantity)
:::: A * (B x C)
* '''The vector triple product''' (a vector quantity)
:::: A x (B x C)
;Task:
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
# Create a named function/subroutine/method to compute the dot product of two vectors.
# Create a function to compute the cross product of two vectors.
# Optionally create a function to compute the scalar triple product of three vectors.
# Optionally create a function to compute the vector triple product of three vectors.
# Compute and display: a * b
# Compute and display: a x b
# Compute and display: a * (b x c), the scalar triple product.
# Compute and display: a x (b x c), the vector triple product.
;References:
* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.
* Wikipedia dot product.
* Wikipedia cross product.
* Wikipedia triple product.
;Related tasks:
* [[Dot product]]
* [[Quaternion type]]
| import java.util.Arrays;
import java.util.stream.IntStream;
public class VectorsOp {
// Vector dot product using Java SE 8 stream abilities
// the method first create an array of size values,
// and map the product of each vectors components in a new array (method map())
// and transform the array to a scalr by summing all elements (method reduce)
// the method parallel is there for optimization
private static int dotProduct(int[] v1, int[] v2,int length) {
int result = IntStream.range(0, length)
.parallel()
.map( id -> v1[id] * v2[id])
.reduce(0, Integer::sum);
return result;
}
// Vector Cross product using Java SE 8 stream abilities
// here we map in a new array where each element is equal to the cross product
// With Stream is is easier to handle N dimensions vectors
private static int[] crossProduct(int[] v1, int[] v2,int length) {
int result[] = new int[length] ;
//result[0] = v1[1] * v2[2] - v1[2]*v2[1] ;
//result[1] = v1[2] * v2[0] - v1[0]*v2[2] ;
// result[2] = v1[0] * v2[1] - v1[1]*v2[0] ;
result = IntStream.range(0, length)
.parallel()
.map( i -> v1[(i+1)%length] * v2[(i+2)%length] - v1[(i+2)%length]*v2[(i+1)%length])
.toArray();
return result;
}
public static void main (String[] args)
{
int[] vect1 = {3, 4, 5};
int[] vect2 = {4, 3, 5};
int[] vect3 = {-5, -12, -13};
System.out.println("dot product =:" + dotProduct(vect1,vect2,3));
int[] prodvect = new int[3];
prodvect = crossProduct(vect1,vect2,3);
System.out.println("cross product =:[" + prodvect[0] + ","
+ prodvect[1] + ","
+ prodvect[2] + "]");
prodvect = crossProduct(vect2,vect3,3);
System.out.println("scalar product =:" + dotProduct(vect1,prodvect,3));
prodvect = crossProduct(vect1,prodvect,3);
System.out.println("triple product =:[" + prodvect[0] + ","
+ prodvect[1] + ","
+ prodvect[2] + "]");
}
} |
Verhoeff algorithm | Java | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.
As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.
;Task:
Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.
The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.
Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.
Use your routines to calculate check digits for the integers: '''236''', '''12345''' and '''123456789012''' and then validate them. Also attempt to validate the same integers if the check digits in all cases were '''9''' rather than what they actually are.
Display digit by digit calculations for the first two integers but not for the third.
;Related task:
* [[Damm algorithm]]
| import java.util.Arrays;
import java.util.List;
public class VerhoeffAlgorithm {
public static void main(String[] args) {
initialise();
List<List<Object>> tests = List.of(
List.of( "236", true ), List.of( "12345", true ), List.of( "123456789012", false ) );
for ( List<Object> test : tests ) {
Object object = verhoeffChecksum((String) test.get(0), false, (boolean) test.get(1));
System.out.println("The check digit for " + test.get(0) + " is " + object + "\n");
for ( String number : List.of( test.get(0) + String.valueOf(object), test.get(0) + "9" ) ) {
object = verhoeffChecksum(number, true, (boolean) test.get(1));
String result = (boolean) object ? "correct" : "incorrect";
System.out.println("The validation for " + number + " is " + result + ".\n");
}
}
}
private static Object verhoeffChecksum(String number, boolean doValidation, boolean doDisplay) {
if ( doDisplay ) {
String calculationType = doValidation ? "Validation" : "Check digit";
System.out.println(calculationType + " calculations for " + number + "\n");
System.out.println(" i ni p[i, ni] c");
System.out.println("-------------------");
}
if ( ! doValidation ) {
number += "0";
}
int c = 0;
final int le = number.length() - 1;
for ( int i = le; i >= 0; i-- ) {
final int ni = number.charAt(i) - '0';
final int pi = permutationTable.get((le - i) % 8).get(ni);
c = multiplicationTable.get(c).get(pi);
if ( doDisplay ) {
System.out.println(String.format("%2d%3d%8d%6d\n", le - i, ni, pi, c));
}
}
if ( doDisplay && ! doValidation ) {
System.out.println("inverse[" + c + "] = " + inverse.get(c) + "\n");
}
return doValidation ? c == 0 : inverse.get(c);
}
private static void initialise() {
multiplicationTable = List.of(
List.of( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
List.of( 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 ),
List.of( 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 ),
List.of( 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 ),
List.of( 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 ),
List.of( 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 ),
List.of( 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 ),
List.of( 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 ),
List.of( 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 ),
List.of( 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 )
);
inverse = Arrays.asList( 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 );
permutationTable = List.of(
List.of( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
List.of( 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 ),
List.of( 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 ),
List.of( 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 ),
List.of( 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 ),
List.of( 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 ),
List.of( 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 ),
List.of( 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 )
);
}
private static List<List<Integer>> multiplicationTable;
private static List<Integer> inverse;
private static List<List<Integer>> permutationTable;
}
|
Video display modes | Java | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JLabel;
public final class VideoDisplay {
public static void main(String[] aArgs) throws InterruptedException {
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = environment.getScreenDevices();
System.out.println("Number of video screens: " + screens.length + System.lineSeparator());
for ( GraphicsDevice screen : screens ) {
System.out.println("Full screen display is supported: "
+ screen.isFullScreenSupported() + System.lineSeparator());
GraphicsConfiguration[] configurations = screen.getConfigurations();
System.out.println("This screen has number of configurations: " + configurations.length);
for ( GraphicsConfiguration config : configurations ) {
System.out.println("Configuration supports translucency: " + config.isTranslucencyCapable());
}
DisplayMode[] modes = screen.getDisplayModes();
System.out.println(System.lineSeparator() + "This screen has " + modes.length + " modes of operation");
for ( DisplayMode mode : modes ) {
System.out.println(mode.getWidth() + " X " + mode.getHeight()
+ " with refresh rate " + mode.getRefreshRate() + " Hz");
}
}
// Uncomment the line below to see an example of programmatically changing the video display.
// new VideoDisplay();
}
private VideoDisplay() throws InterruptedException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Video Display Demonstration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.LIGHT_GRAY);
frame.add( new JLabel(MESSAGE) );
frame.setSize(800, 600);
GraphicsDevice screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
DisplayMode originalDisplayMode = screen.getDisplayMode();
screen.setFullScreenWindow(frame);
screen.setDisplayMode( new DisplayMode(800, 600, 32, 60) );
frame.setVisible(true);
TimeUnit.SECONDS.sleep(3);
screen.setDisplayMode(originalDisplayMode);
TimeUnit.SECONDS.sleep(3);
Runtime.getRuntime().exit(0);
}
private static final String MESSAGE = "Please wait for a few seconds."
+ " Your video display will then be returned to its original setting.";
}
|
Visualize a tree | Java | A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
:::* indented text (a la unix tree command)
:::* nested HTML tables
:::* hierarchical GUI widgets
:::* 2D or 3D images
:::* etc.
;Task:
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| public class VisualizeTree {
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(100);
for (int i = 0; i < 20; i++)
tree.insert((int) (Math.random() * 200));
tree.display();
}
}
class BinarySearchTree {
private Node root;
private class Node {
private int key;
private Node left, right;
Node(int k) {
key = k;
}
}
public boolean insert(int key) {
if (root == null)
root = new Node(key);
else {
Node n = root;
Node parent;
while (true) {
if (n.key == key)
return false;
parent = n;
boolean goLeft = key < n.key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key);
} else {
parent.right = new Node(key);
}
break;
}
}
}
return true;
}
public void display() {
final int height = 5, width = 64;
int len = width * height * 2 + 2;
StringBuilder sb = new StringBuilder(len);
for (int i = 1; i <= len; i++)
sb.append(i < len - 2 && i % width == 0 ? "\n" : ' ');
displayR(sb, width / 2, 1, width / 4, width, root, " ");
System.out.println(sb);
}
private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n,
String edge) {
if (n != null) {
displayR(sb, c - d, r + 2, d / 2, w, n.left, " /");
String s = String.valueOf(n.key);
int idx1 = r * w + c - (s.length() + 1) / 2;
int idx2 = idx1 + s.length();
int idx3 = idx1 - w;
if (idx2 < sb.length())
sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge);
displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ ");
}
}
} |
Vogel's approximation method | Java 8 | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them "A", "B", "C", "D", and "E". They estimate that:
* A will require 30 hours of work,
* B will require 20 hours of work,
* C will require 70 hours of work,
* D will require 30 hours of work, and
* E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called "W", "X", "Y", and "Z".
* W has 50 hours available to commit to working,
* X has 60 hours available,
* Y has 50 hours available, and
* Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is PS3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is PS3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
;Cf.
* Transportation problem
| import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
static int[] nextCell() throws Exception {
Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));
int[] res1 = f1.get();
int[] res2 = f2.get();
if (res1[3] == res2[3])
return res1[2] < res2[2] ? res1 : res2;
return (res1[3] > res2[3]) ? res2 : res1;
}
static int[] diff(int j, int len, boolean isRow) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i])
continue;
int c = isRow ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2)
min2 = c;
}
return new int[]{min2 - min1, min1, minP};
}
static int[] maxPenalty(int len1, int len2, boolean isRow) {
int md = Integer.MIN_VALUE;
int pc = -1, pm = -1, mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i])
continue;
int[] res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0]; // max diff
pm = i; // pos of max diff
mc = res[1]; // min cost
pc = res[2]; // pos of min cost
}
}
return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
}
} |
Wagstaff primes | Java | Definition
A ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.
;Example
(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.
;Task
Find and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.
;Stretch (requires arbitrary precision integers)
Find and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for.
When testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.
;Note
It can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.
;References
* Wikipedia - Wagstaff prime
* OEIS:A000979 - Wagstaff primes
| import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
} |
War card game | Java | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
:* Bicycle card company: War game site
:* Wikipedia: War (card game)
Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards for FreeCell]]
* [[Poker hand_analyser]]
* [[Go Fish]]
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class WarCardGame {
public static void main(String[] args) {
WarGame warGame = new WarGame();
while ( ! warGame.gameOver() ) {
warGame.nextTurn();
}
warGame.declareWinner();
}
}
final class WarGame {
public WarGame() {
deck = new ArrayList<Card>(52);
for ( Character suit : SUITS ) {
for ( Character pip : PIPS ) {
deck.add( new Card(suit, pip) );
}
}
Collections.shuffle(deck);
handA = new ArrayList<Card>(deck.subList(0, 26));
handB = new ArrayList<Card>(deck.subList(26, 52));
tabledCards = new ArrayList<Card>();
}
public void nextTurn() {
Card cardA = handA.remove(0);
Card cardB = handB.remove(0);
tabledCards.add(cardA);
tabledCards.add(cardB);
int rankA = PIPS.indexOf(cardA.pip);
int rankB = PIPS.indexOf(cardB.pip);
System.out.print(cardA + " " + cardB);
if ( rankA > rankB ) {
System.out.println(" Player A takes the cards");
Collections.shuffle(tabledCards);
handA.addAll(tabledCards);
tabledCards.clear();
} else if ( rankA < rankB ) {
System.out.println(" Player B takes the cards");
Collections.shuffle(tabledCards);
handB.addAll(tabledCards);
tabledCards.clear();
} else {
System.out.println(" War!");
if ( gameOver() ) {
return;
}
Card cardAA = handA.remove(0);
Card cardBB = handB.remove(0);
tabledCards.add(cardAA);
tabledCards.add(cardBB);
System.out.println("? ? Cards are face down");
if ( gameOver() ) {
return;
}
nextTurn();
}
}
public boolean gameOver() {
return handA.size() == 0 || handB.size() == 0;
}
public void declareWinner() {
if ( handA.size() == 0 && handB.size() == 0 ) {
System.out.println("The game ended in a tie");
} else if ( handA.size() == 0 ) {
System.out.println("Player B has won the game");
} else {
System.out.println("Player A has won the game");
}
}
private record Card(Character suit, Character pip) {
@Override
public String toString() {
return "" + pip + suit;
}
}
private List<Card> deck, handA, handB, tabledCards;
private static final List<Character> PIPS =
Arrays.asList( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
private static final List<Character> SUITS = List.of( 'C', 'D', 'H', 'S' );
}
|
Water collected between towers | Java from D | In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ## 9 ##
8 ## 8 ##
7 ## ## 7 ####
6 ## ## ## 6 ######
5 ## ## ## #### 5 ##########
4 ## ## ######## 4 ############
3 ###### ######## 3 ##############
2 ################ ## 2 ##################
1 #################### 1 ####################
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele
* Water collected between towers on Stack Overflow, from which the example above is taken)
* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| public class WaterBetweenTowers {
public static void main(String[] args) {
int i = 1;
int[][] tba = new int[][]{
new int[]{1, 5, 3, 7, 2},
new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
new int[]{5, 5, 5, 5},
new int[]{5, 6, 7, 8},
new int[]{8, 7, 7, 6},
new int[]{6, 7, 10, 7, 6}
};
for (int[] tea : tba) {
int rht, wu = 0, bof;
do {
for (rht = tea.length - 1; rht >= 0; rht--) {
if (tea[rht] > 0) {
break;
}
}
if (rht < 0) {
break;
}
bof = 0;
for (int col = 0; col <= rht; col++) {
if (tea[col] > 0) {
tea[col]--;
bof += 1;
} else if (bof > 0) {
wu++;
}
}
if (bof < 2) {
break;
}
} while (true);
System.out.printf("Block %d", i++);
if (wu == 0) {
System.out.print(" does not hold any");
} else {
System.out.printf(" holds %d", wu);
}
System.out.println(" water units.");
}
}
} |
Weird numbers | Java | In number theory, a perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').
For example:
* '''12''' is ''not'' a weird number.
** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),
** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.
* '''70''' ''is'' a weird number.
** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),
** and there is no subset of proper divisors that sum to '''70'''.
;Task:
Find and display, here on this page, the first '''25''' weird numbers.
;Related tasks:
:* Abundant, deficient and perfect number classifications
:* Proper divisors
;See also:
:* OEIS: A006037 weird numbers
:* Wikipedia: weird number
:* MathWorld: weird number
| import java.util.ArrayList;
import java.util.List;
public class WeirdNumbers {
public static void main(String[] args) {
int n = 2;
// n += 2 : No odd weird numbers < 10^21
for ( int count = 1 ; count <= 25 ; n += 2 ) {
if ( isWeird(n) ) {
System.out.printf("w(%d) = %d%n", count, n);
count++;
}
}
}
private static boolean isWeird(int n) {
List<Integer> properDivisors = getProperDivisors(n);
return isAbundant(properDivisors, n) && ! isSemiPerfect(properDivisors, n);
}
private static boolean isAbundant(List<Integer> divisors, int n) {
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
return divisorSum > n;
}
// Use Dynamic Programming
private static boolean isSemiPerfect(List<Integer> divisors, int sum) {
int size = divisors.size();
// The value of subset[i][j] will be true if there is a subset of divisors[0..j-1] with sum equal to i
boolean subset[][] = new boolean[sum+1][size+1];
// If sum is 0, then answer is true
for (int i = 0; i <= size; i++) {
subset[0][i] = true;
}
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++) {
subset[i][0] = false;
}
// Fill the subset table in bottom up manner
for ( int i = 1 ; i <= sum ; i++ ) {
for ( int j = 1 ; j <= size ; j++ ) {
subset[i][j] = subset[i][j-1];
int test = divisors.get(j-1);
if ( i >= test ) {
subset[i][j] = subset[i][j] || subset[i - test][j-1];
}
}
}
return subset[sum][size];
}
private static final List<Integer> getProperDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i && div != number ) {
divisors.add(div);
}
}
}
return divisors;
}
}
|
Word frequency | Java | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| void printWordFrequency() throws URISyntaxException, IOException {
URL url = new URI("https://www.gutenberg.org/files/135/135-0.txt").toURL();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
Pattern pattern = Pattern.compile("(\\w+)");
Matcher matcher;
String line;
String word;
Map<String, Integer> map = new HashMap<>();
while ((line = reader.readLine()) != null) {
matcher = pattern.matcher(line);
while (matcher.find()) {
word = matcher.group().toLowerCase();
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
}
/* print out top 10 */
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
Collections.reverse(list);
int count = 1;
for (Map.Entry<String, Integer> value : list) {
System.out.printf("%-20s%,7d%n", value.getKey(), value.getValue());
if (count++ == 10) break;
}
}
}
|
Word frequency | Java from Kotlin | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class WordCount {
public static void main(String[] args) throws IOException {
Path path = Paths.get("135-0.txt");
byte[] bytes = Files.readAllBytes(path);
String text = new String(bytes);
text = text.toLowerCase();
Pattern r = Pattern.compile("\\p{javaLowerCase}+");
Matcher matcher = r.matcher(text);
Map<String, Integer> freq = new HashMap<>();
while (matcher.find()) {
String word = matcher.group();
Integer current = freq.getOrDefault(word, 0);
freq.put(word, current + 1);
}
List<Map.Entry<String, Integer>> entries = freq.entrySet()
.stream()
.sorted((i1, i2) -> Integer.compare(i2.getValue(), i1.getValue()))
.limit(10)
.collect(Collectors.toList());
System.out.println("Rank Word Frequency");
System.out.println("==== ==== =========");
int rank = 1;
for (Map.Entry<String, Integer> entry : entries) {
String word = entry.getKey();
Integer count = entry.getValue();
System.out.printf("%2d %-4s %5d\n", rank++, word, count);
}
}
} |
Word ladder | Java | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
} |
Word ladder | Java from C++ | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
| import java.io.*;
import java.util.*;
public class WordLadder {
public static void main(String[] args) {
try {
Map<Integer, List<String>> words = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
String line;
while ((line = reader.readLine()) != null)
words.computeIfAbsent(line.length(), k -> new ArrayList<String>()).add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle");
} catch (Exception e) {
e.printStackTrace();
}
}
// Returns true if strings s1 and s2 differ by one character.
private static boolean oneAway(String s1, String s2) {
if (s1.length() != s2.length())
return false;
boolean result = false;
for (int i = 0, n = s1.length(); i != n; ++i) {
if (s1.charAt(i) != s2.charAt(i)) {
if (result)
return false;
result = true;
}
}
return result;
}
// If possible, print the shortest chain of single-character modifications that
// leads from "from" to "to", with each intermediate step being a valid word.
// This is an application of breadth-first search.
private static void wordLadder(Map<Integer, List<String>> words, String from, String to) {
List<String> w = words.get(from.length());
if (w != null) {
Deque<String> poss = new ArrayDeque<>(w);
Deque<String> f = new ArrayDeque<String>();
f.add(from);
Deque<Deque<String>> queue = new ArrayDeque<>();
queue.add(f);
while (!queue.isEmpty()) {
Deque<String> curr = queue.poll();
for (Iterator<String> i = poss.iterator(); i.hasNext(); ) {
String str = i.next();
if (!oneAway(str, curr.getLast()))
continue;
if (to.equals(str)) {
curr.add(to);
System.out.println(String.join(" -> ", curr));
return;
}
Deque<String> temp = new ArrayDeque<>(curr);
temp.add(str);
queue.add(temp);
i.remove();
}
}
}
System.out.printf("%s into %s cannot be done.\n", from, to);
}
} |
Word search | Java 7 | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
;Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
;Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
| import java.io.*;
import static java.lang.String.format;
import java.util.*;
public class WordSearch {
static class Grid {
int numAttempts;
char[][] cells = new char[nRows][nCols];
List<String> solutions = new ArrayList<>();
}
final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
final static int nRows = 10;
final static int nCols = 10;
final static int gridSize = nRows * nCols;
final static int minWords = 25;
final static Random rand = new Random();
public static void main(String[] args) {
printResult(createWordSearch(readWords("unixdict.txt")));
}
static List<String> readWords(String filename) {
int maxLen = Math.max(nRows, nCols);
List<String> words = new ArrayList<>();
try (Scanner sc = new Scanner(new FileReader(filename))) {
while (sc.hasNext()) {
String s = sc.next().trim().toLowerCase();
if (s.matches("^[a-z]{3," + maxLen + "}$"))
words.add(s);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
return words;
}
static Grid createWordSearch(List<String> words) {
Grid grid = null;
int numAttempts = 0;
outer:
while (++numAttempts < 100) {
Collections.shuffle(words);
grid = new Grid();
int messageLen = placeMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
for (String word : words) {
cellsFilled += tryPlaceWord(grid, word);
if (cellsFilled == target) {
if (grid.solutions.size() >= minWords) {
grid.numAttempts = numAttempts;
break outer;
} else break; // grid is full but we didn't pack enough words, start over
}
}
}
return grid;
}
static int placeMessage(Grid grid, String msg) {
msg = msg.toUpperCase().replaceAll("[^A-Z]", "");
int messageLen = msg.length();
if (messageLen > 0 && messageLen < gridSize) {
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++) {
int pos = i * gapSize + rand.nextInt(gapSize);
grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);
}
return messageLen;
}
return 0;
}
static int tryPlaceWord(Grid grid, String word) {
int randDir = rand.nextInt(dirs.length);
int randPos = rand.nextInt(gridSize);
for (int dir = 0; dir < dirs.length; dir++) {
dir = (dir + randDir) % dirs.length;
for (int pos = 0; pos < gridSize; pos++) {
pos = (pos + randPos) % gridSize;
int lettersPlaced = tryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
static int tryLocation(Grid grid, String word, int dir, int pos) {
int r = pos / nCols;
int c = pos % nCols;
int len = word.length();
// check bounds
if ((dirs[dir][0] == 1 && (len + c) > nCols)
|| (dirs[dir][0] == -1 && (len - 1) > c)
|| (dirs[dir][1] == 1 && (len + r) > nRows)
|| (dirs[dir][1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
// check cells
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))
return 0;
cc += dirs[dir][0];
rr += dirs[dir][1];
}
// place
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] == word.charAt(i))
overlaps++;
else
grid.cells[rr][cc] = word.charAt(i);
if (i < len - 1) {
cc += dirs[dir][0];
rr += dirs[dir][1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0) {
grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr));
}
return lettersPlaced;
}
static void printResult(Grid grid) {
if (grid == null || grid.numAttempts == 0) {
System.out.println("No grid to display");
return;
}
int size = grid.solutions.size();
System.out.println("Attempts: " + grid.numAttempts);
System.out.println("Number of words: " + size);
System.out.println("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++) {
System.out.printf("%n%d ", r);
for (int c = 0; c < nCols; c++)
System.out.printf(" %c ", grid.cells[r][c]);
}
System.out.println("\n");
for (int i = 0; i < size - 1; i += 2) {
System.out.printf("%s %s%n", grid.solutions.get(i),
grid.solutions.get(i + 1));
}
if (size % 2 == 1)
System.out.println(grid.solutions.get(size - 1));
}
} |
Word wrap | Java | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
;Basic task:
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
;Extra credit:
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
| package rosettacode;
import java.util.StringTokenizer;
public class WordWrap
{
int defaultLineWidth=80;
int defaultSpaceWidth=1;
void minNumLinesWrap(String text)
{
minNumLinesWrap(text,defaultLineWidth);
}
void minNumLinesWrap(String text,int LineWidth)
{
StringTokenizer st=new StringTokenizer(text);
int SpaceLeft=LineWidth;
int SpaceWidth=defaultSpaceWidth;
while(st.hasMoreTokens())
{
String word=st.nextToken();
if((word.length()+SpaceWidth)>SpaceLeft)
{
System.out.print("\n"+word+" ");
SpaceLeft=LineWidth-word.length();
}
else
{
System.out.print(word+" ");
SpaceLeft-=(word.length()+SpaceWidth);
}
}
}
public static void main(String[] args)
{
WordWrap now=new WordWrap();
String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
System.out.println("DEFAULT:");
now.minNumLinesWrap(wodehouse);
System.out.println("\n\nLINEWIDTH=120");
now.minNumLinesWrap(wodehouse,120);
}
}
|
World Cup group stage | Java 1.5+ | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
:::* A win is worth three points.
:::* A draw/tie is worth one point.
:::* A loss is worth zero points.
;Task:
:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
:* Calculate the standings points for each team with each combination of outcomes.
:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
| import java.util.Arrays;
public class GroupStage{
//team left digit vs team right digit
static String[] games = {"12", "13", "14", "23", "24", "34"};
static String results = "000000";//start with left teams all losing
private static boolean nextResult(){
if(results.equals("222222")) return false;
int res = Integer.parseInt(results, 3) + 1;
results = Integer.toString(res, 3);
while(results.length() < 6) results = "0" + results; //left pad with 0s
return true;
}
public static void main(String[] args){
int[][] points = new int[4][10]; //playing 3 games, points range from 0 to 9
do{
int[] records = {0,0,0,0};
for(int i = 0; i < 6; i++){
switch(results.charAt(i)){
case '2': records[games[i].charAt(0) - '1'] += 3; break; //win for left team
case '1': //draw
records[games[i].charAt(0) - '1']++;
records[games[i].charAt(1) - '1']++;
break;
case '0': records[games[i].charAt(1) - '1'] += 3; break; //win for right team
}
}
Arrays.sort(records); //sort ascending, first place team on the right
points[0][records[0]]++;
points[1][records[1]]++;
points[2][records[2]]++;
points[3][records[3]]++;
}while(nextResult());
System.out.println("First place: " + Arrays.toString(points[3]));
System.out.println("Second place: " + Arrays.toString(points[2]));
System.out.println("Third place: " + Arrays.toString(points[1]));
System.out.println("Fourth place: " + Arrays.toString(points[0]));
}
} |
Write float arrays to a text file | Java | Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| import java.io.*;
public class FloatArray {
public static void writeDat(String filename, double[] x, double[] y,
int xprecision, int yprecision)
throws IOException {
assert x.length == y.length;
PrintWriter out = new PrintWriter(filename);
for (int i = 0; i < x.length; i++)
out.printf("%."+xprecision+"g\t%."+yprecision+"g\n", x[i], y[i]);
out.close();
}
public static void main(String[] args) {
double[] x = {1, 2, 3, 1e11};
double[] y = new double[x.length];
for (int i = 0; i < x.length; i++)
y[i] = Math.sqrt(x[i]);
try {
writeDat("sqrt.dat", x, y, 3, 5);
} catch (IOException e) {
System.err.println("writeDat: exception: "+e);
}
try {
BufferedReader br = new BufferedReader(new FileReader("sqrt.dat"));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException e) { }
}
} |
Write language name in 3D ASCII | Java | Write/display a language's name in '''3D''' ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
;Related tasks:
* draw a sphere
* draw a cuboid
* draw a rotating cube
* draw a Deathstar
| public class F5{
char[]z={' ',' ','_','/',};
long[][]f={
{87381,87381,87381,87381,87381,87381,87381,},
{349525,375733,742837,742837,375733,349525,349525,},
{742741,768853,742837,742837,768853,349525,349525,},
{349525,375733,742741,742741,375733,349525,349525,},
{349621,375733,742837,742837,375733,349525,349525,},
{349525,375637,768949,742741,375733,349525,349525,},
{351157,374101,768949,374101,374101,349525,349525,},
{349525,375733,742837,742837,375733,349621,351157,},
{742741,768853,742837,742837,742837,349525,349525,},
{181,85,181,181,181,85,85,},
{1461,1365,1461,1461,1461,1461,2901,},
{742741,744277,767317,744277,742837,349525,349525,},
{181,181,181,181,181,85,85,},
{1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,},
{349525,768853,742837,742837,742837,349525,349525,},
{349525,375637,742837,742837,375637,349525,349525,},
{349525,768853,742837,742837,768853,742741,742741,},
{349525,375733,742837,742837,375733,349621,349621,},
{349525,744373,767317,742741,742741,349525,349525,},
{349525,375733,767317,351157,768853,349525,349525,},
{374101,768949,374101,374101,351157,349525,349525,},
{349525,742837,742837,742837,375733,349525,349525,},
{5592405,11883957,11883957,5987157,5616981,5592405,5592405,},
{366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,},
{349525,742837,375637,742837,742837,349525,349525,},
{349525,742837,742837,742837,375733,349621,375637,},
{349525,768949,351061,374101,768949,349525,349525,},
{375637,742837,768949,742837,742837,349525,349525,},
{768853,742837,768853,742837,768853,349525,349525,},
{375733,742741,742741,742741,375733,349525,349525,},
{192213,185709,185709,185709,192213,87381,87381,},
{1817525,1791317,1817429,1791317,1817525,1398101,1398101,},
{768949,742741,768853,742741,742741,349525,349525,},
{375733,742741,744373,742837,375733,349525,349525,},
{742837,742837,768949,742837,742837,349525,349525,},
{48053,23381,23381,23381,48053,21845,21845,},
{349621,349621,349621,742837,375637,349525,349525,},
{742837,744277,767317,744277,742837,349525,349525,},
{742741,742741,742741,742741,768949,349525,349525,},
{11883957,12278709,11908533,11883957,11883957,5592405,5592405,},
{11883957,12277173,11908533,11885493,11883957,5592405,5592405,},
{375637,742837,742837,742837,375637,349525,349525,},
{768853,742837,768853,742741,742741,349525,349525,},
{6010197,11885397,11909973,11885397,6010293,5592405,5592405,},
{768853,742837,768853,742837,742837,349525,349525,},
{375733,742741,375637,349621,768853,349525,349525,},
{12303285,5616981,5616981,5616981,5616981,5592405,5592405,},
{742837,742837,742837,742837,375637,349525,349525,},
{11883957,11883957,11883957,5987157,5616981,5592405,5592405,},
{3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,},
{11883957,5987157,5616981,5987157,11883957,5592405,5592405,},
{11883957,5987157,5616981,5616981,5616981,5592405,5592405,},
{12303285,5593941,5616981,5985621,12303285,5592405,5592405,},};
public static void main(String[]a){
new F5(a.length>0?a[0]:"Java");}
private F5(String s){
StringBuilder[]o=new StringBuilder[7];
for(int i=0;i<7;i++)o[i]=new StringBuilder();
for(int i=0,l=s.length();i<l;i++){
int c=s.charAt(i);
if(65<=c&&c<=90)c-=39;
else if(97<=c&&c<=122)c-=97;
else c=-1;
long[]d=f[++c];
for(int j=0;j<7;j++){
StringBuilder b=new StringBuilder();
long v=d[j];
while(v>0){
b.append(z[(int)(v&3)]);
v>>=2;}
o[j].append(b.reverse().toString());}}
for(int i=0;i<7;i++){
for(int j=0;j<7-i;j++)
System.out.print(' ');
System.out.println(o[i]);}}}
|
Write to Windows event log | Java | Write script status to the Windows Event Log
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class WriteToWindowsEventLog {
public static void main(String[] args) throws IOException, InterruptedException {
String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
if (!osName.startsWith("WINDOWS")) {
System.err.println("Not windows");
return;
}
Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
process.waitFor(10, TimeUnit.SECONDS);
int exitValue = process.exitValue();
System.out.printf("Process exited with value %d\n", exitValue);
if (exitValue != 0) {
InputStream errorStream = process.getErrorStream();
String result = new BufferedReader(new InputStreamReader(errorStream))
.lines()
.collect(Collectors.joining("\n"));
System.err.println(result);
}
}
} |
Yellowstone sequence | Java | The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
;Example:
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
;Task
: Find and show as output the first '''30''' Yellowstone numbers.
;Extra
: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
;Related tasks:
:* Greatest common divisor.
:* Plot coordinate pairs.
;See also:
:* The OEIS entry: A098550 The Yellowstone permutation.
:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
| import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Zeckendorf number representation | Java | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.
;Task:
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
;Also see:
* OEIS A014417 for the the sequence of required results.
* Brown's Criterion - Numberphile
;Related task:
* [[Fibonacci sequence]]
| import java.util.ArrayList;
import java.util.List;
public class Zeckendorf {
private List<Integer> getFibList(final int maxNum, final int n1, final int n2, final List<Integer> fibs){
if(n2 > maxNum) return fibs;
fibs.add(n2);
return getFibList(maxNum, n2, n1 + n2, fibs);
}
public String getZeckendorf(final int num) {
if (num <= 0) return "0";
final List<Integer> fibs = getFibList(num, 1, 2, new ArrayList<Integer>(){{ add(1); }});
return getZeckString("", num, fibs.size() - 1, fibs);
}
private String getZeckString(final String zeck, final int num, final int index, final List<Integer> fibs){
final int curFib = fibs.get(index);
final boolean placeZeck = num >= curFib;
final String outString = placeZeck ? zeck + "1" : zeck + "0";
final int outNum = placeZeck ? num - curFib : num;
if(index == 0) return outString;
return getZeckString(outString, outNum, index - 1, fibs);
}
public static void main(final String[] args) {
final Zeckendorf zeckendorf = new Zeckendorf();
for(int i =0; i <= 20; i++){
System.out.println("Z("+ i +"):\t" + zeckendorf.getZeckendorf(i));
}
}
} |
Zhang-Suen thinning algorithm | Java 7 | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
;Algorithm:
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
;Step 1:
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and P6 is white
* (4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
;Step 2:
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and '''P8''' is white
* (4) At least one of '''P2''' and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
;Iteration:
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
;Task:
# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
;Reference:
* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
* "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| import java.awt.Point;
import java.util.*;
public class ZhangSuen {
final static String[] image = {
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ",
" ######## ####### ################### ",
" ###### ####### ####### ###### ",
" ###### ####### ####### ",
" ################# ####### ",
" ################ ####### ",
" ################# ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ###### ",
" ######## ####### ################### ",
" ######## ####### ###### ################## ###### ",
" ######## ####### ###### ################ ###### ",
" ######## ####### ###### ############# ###### ",
" "};
final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},
{-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};
final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},
{0, 4, 6}}};
static List<Point> toWhite = new ArrayList<>();
static char[][] grid;
public static void main(String[] args) {
grid = new char[image.length][];
for (int r = 0; r < image.length; r++)
grid[r] = image[r].toCharArray();
thinImage();
}
static void thinImage() {
boolean firstStep = false;
boolean hasChanged;
do {
hasChanged = false;
firstStep = !firstStep;
for (int r = 1; r < grid.length - 1; r++) {
for (int c = 1; c < grid[0].length - 1; c++) {
if (grid[r][c] != '#')
continue;
int nn = numNeighbors(r, c);
if (nn < 2 || nn > 6)
continue;
if (numTransitions(r, c) != 1)
continue;
if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))
continue;
toWhite.add(new Point(c, r));
hasChanged = true;
}
}
for (Point p : toWhite)
grid[p.y][p.x] = ' ';
toWhite.clear();
} while (firstStep || hasChanged);
printResult();
}
static int numNeighbors(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')
count++;
return count;
}
static int numTransitions(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {
if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')
count++;
}
return count;
}
static boolean atLeastOneIsWhite(int r, int c, int step) {
int count = 0;
int[][] group = nbrGroups[step];
for (int i = 0; i < 2; i++)
for (int j = 0; j < group[i].length; j++) {
int[] nbr = nbrs[group[i][j]];
if (grid[r + nbr[1]][c + nbr[0]] == ' ') {
count++;
break;
}
}
return count > 1;
}
static void printResult() {
for (char[] row : grid)
System.out.println(row);
}
} |
100 doors | JavaScript | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| (function (n) {
"use strict";
function finalDoors(n) {
var lstRange = range(1, n);
return lstRange
.reduce(function (a, _, k) {
var m = k + 1;
return a.map(function (x, i) {
var j = i + 1;
return [j, j % m ? x[1] : !x[1]];
});
}, zip(
lstRange,
replicate(n, false)
));
};
function zip(xs, ys) {
return xs.length === ys.length ? (
xs.map(function (x, i) {
return [x, ys[i]];
})
) : undefined;
}
function replicate(n, a) {
var v = [a],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
}
function range(m, n, delta) {
var d = delta || 1,
blnUp = n > m,
lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,
a = Array(lng),
i = lng;
if (blnUp)
while (i--) a[i] = (d * i) + m;
else
while (i--) a[i] = m - (d * i);
return a;
}
return finalDoors(n)
.filter(function (tuple) {
return tuple[1];
})
.map(function (tuple) {
return {
door: tuple[0],
open: tuple[1]
};
});
})(100); |
100 doors | JavaScript Node.js 16.13.0 (LTS) | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| "use strict";
// Doors can be open or closed.
const open = "O";
const closed = "C";
// There are 100 doors in a row that are all initially closed.
const doorsCount = 100;
const doors = [];
for (let i = 0; i < doorsCount; doors[i] = closed, i++);
// You make 100 passes by the doors, visiting every door and toggle the door (if
// the door is closed, open it; if it is open, close it), according to the rules
// of the task.
for (let pass = 1; pass <= doorsCount; pass++)
for (let i = pass - 1; i < doorsCount; i += pass)
doors[i] = doors[i] == open ? closed : open;
// Answer the question: what state are the doors in after the last pass?
doors.forEach((v, i) =>
console.log(`Doors ${i + 1} are ${v == open ? 'opened' : 'closed'}.`));
// Which are open, which are closed?
let openKeyList = [];
let closedKeyList = [];
for (let door of doors.entries())
if (door[1] == open)
openKeyList.push(door[0] + 1);
else
closedKeyList.push(door[0] + 1);
console.log("These are open doors: " + openKeyList.join(", ") + ".");
console.log("These are closed doors: " + closedKeyList.join(", ") + ".");
// Assert:
const expected = [];
for (let i = 1; i * i <= doorsCount; expected.push(i * i), i++);
if (openKeyList.every((v, i) => v === expected[i]))
console.log("The task is solved.")
else
throw "These aren't the doors you're looking for."; |
100 prisoners | JavaScript Node.js 16.13.0 (LTS) | The Problem:
* 100 prisoners are individually numbered 1 to 100
* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
* Prisoners start outside the room
:* They can decide some strategy before any enter the room.
:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
:* A prisoner can open no more than 50 drawers.
:* A prisoner tries to find his own number.
:* A prisoner finding his own number is then held apart from the others.
* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand.
;The task:
# Simulate several thousand instances of the game where the prisoners randomly open drawers
# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
:* First opening the drawer whose outside number is his prisoner number.
:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
;References:
# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
# [[wp:100 prisoners problem]]
# 100 Prisoners Escape Puzzle DataGenetics.
# Random permutation statistics#One hundred prisoners on Wikipedia.
| "use strict";
// Simulate several thousand instances of the game:
const gamesCount = 2000;
// ...where the prisoners randomly open drawers.
const randomResults = playGame(gamesCount, randomStrategy);
// ...where the prisoners use the optimal strategy mentioned in the Wikipedia article.
const optimalResults = playGame(gamesCount, optimalStrategy);
// Show and compare the computed probabilities of success for the two strategies.
console.log(`Games count: ${gamesCount}`);
console.log(`Probability of success with "random" strategy: ${computeProbability(randomResults, gamesCount)}`);
console.log(`Probability of success with "optimal" strategy: ${computeProbability(optimalResults, gamesCount)}`);
function playGame(gamesCount, strategy, prisonersCount = 100) {
const results = new Array();
for (let game = 1; game <= gamesCount; game++) {
// A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
// Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
const drawers = initDrawers(prisonersCount);
// A prisoner tries to find his own number.
// Prisoners start outside the room.
// They can decide some strategy before any enter the room.
let found = 0;
for (let prisoner = 1; prisoner <= prisonersCount; prisoner++, found++)
if (!find(prisoner, drawers, strategy)) break;
// If all 100 findings find their own numbers then they will all be pardoned. If any don't then all sentences stand.
results.push(found == prisonersCount);
}
return results;
}
function find(prisoner, drawers, strategy) {
// A prisoner can open no more than 50 drawers.
const openMax = Math.floor(drawers.length / 2);
// Prisoners start outside the room.
let card;
for (let open = 0; open < openMax; open++) {
// A prisoner tries to find his own number.
card = strategy(prisoner, drawers, card);
// A prisoner finding his own number is then held apart from the others.
if (card == prisoner)
break;
}
return (card == prisoner);
}
function randomStrategy(prisoner, drawers, card) {
// Simulate the game where the prisoners randomly open drawers.
const min = 0;
const max = drawers.length - 1;
return drawers[draw(min, max)];
}
function optimalStrategy(prisoner, drawers, card) {
// Simulate the game where the prisoners use the optimal strategy mentioned in the Wikipedia article.
// First opening the drawer whose outside number is his prisoner number.
// If the card within has his number then he succeeds...
if (typeof card === "undefined")
return drawers[prisoner - 1];
// ...otherwise he opens the drawer with the same number as that of the revealed card.
return drawers[card - 1];
}
function initDrawers(prisonersCount) {
const drawers = new Array();
for (let card = 1; card <= prisonersCount; card++)
drawers.push(card);
return shuffle(drawers);
}
function shuffle(drawers) {
const min = 0;
const max = drawers.length - 1;
for (let i = min, j; i < max; i++) {
j = draw(min, max);
if (i != j)
[drawers[i], drawers[j]] = [drawers[j], drawers[i]];
}
return drawers;
}
function draw(min, max) {
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function computeProbability(results, gamesCount) {
return Math.round(results.filter(x => x == true).length * 10000 / gamesCount) / 100;
} |
15 puzzle game | Javascript | Implement the Fifteen Puzzle Game.
The '''15-puzzle''' is also known as:
:::* '''Fifteen Puzzle'''
:::* '''Gem Puzzle'''
:::* '''Boss Puzzle'''
:::* '''Game of Fifteen'''
:::* '''Mystic Square'''
:::* '''14-15 Puzzle'''
:::* and some others.
;Related Tasks:
:* 15 Puzzle Solver
:* [[16 Puzzle Game]]
| var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1];
possibles = [];
for( var i = 0; i < 4; i++ ) {
ii = zx + cx[i]; jj = zy + cy[i];
if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue;
possibles.push( { x: ii, y: jj } );
}
}
function updateBtns() {
var b, v, id;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
id = "btn" + ( i + j * 4 );
b = document.getElementById( id );
v = board[i][j];
if( v < 16 ) {
b.innerHTML = ( "" + v );
b.className = "button"
}
else {
b.innerHTML = ( "" );
b.className = "empty";
}
}
}
clickCounter.innerHTML = "Clicks: " + clicks;
}
function shuffle() {
var v = 0, t;
do {
getPossibles();
while( true ) {
t = possibles[Math.floor( Math.random() * possibles.length )];
console.log( t.x, oldzx, t.y, oldzy )
if( t.x != oldzx || t.y != oldzy ) break;
}
oldzx = zx; oldzy = zy;
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
} while( ++v < 200 );
}
function restart() {
shuffle();
clicks = 0;
updateBtns();
}
function checkFinished() {
var a = 0;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
if( board[i][j] < a ) return false;
a = board[i][j];
}
}
return true;
}
function btnHandle( e ) {
getPossibles();
var c = e.target.i, r = e.target.j, p = -1;
for( var i = 0; i < possibles.length; i++ ) {
if( possibles[i].x == c && possibles[i].y == r ) {
p = i;
break;
}
}
if( p > -1 ) {
clicks++;
var t = possibles[p];
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
updateBtns();
if( checkFinished() ) {
setTimeout(function(){
alert( "WELL DONE!" );
restart();
}, 1);
}
}
}
function createBoard() {
board = new Array( 4 );
for( var i = 0; i < 4; i++ ) {
board[i] = new Array( 4 );
}
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
board[i][j] = ( i + j * 4 ) + 1;
}
}
zx = zy = 3; board[zx][zy] = 16;
}
function createBtns() {
var b, d = document.createElement( "div" );
d.className += "board";
document.body.appendChild( d );
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
b = document.createElement( "button" );
b.id = "btn" + ( i + j * 4 );
b.i = i; b.j = j;
b.addEventListener( "click", btnHandle, false );
b.appendChild( document.createTextNode( "" ) );
d.appendChild( b );
}
}
clickCounter = document.createElement( "p" );
clickCounter.className += "txt";
document.body.appendChild( clickCounter );
}
function start() {
createBtns();
createBoard();
restart();
}
|
21 game | Javascript | '''21''' is a two player game, the game is played by choosing
a number ('''1''', '''2''', or '''3''') to be added to the ''running total''.
The game is won by the player whose chosen number causes the ''running total''
to reach ''exactly'' '''21'''.
The ''running total'' starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the ''running total''.
;Task:
Write a computer program that will:
::* do the prompting (or provide a button menu),
::* check for errors and display appropriate error messages,
::* do the additions (add a chosen number to the ''running total''),
::* display the ''running total'',
::* provide a mechanism for the player to quit/exit/halt/stop/close the program,
::* issue a notification when there is a winner, and
::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| <!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="Game 21">
<meta name="description" content="
21 is a two player game, the game is played by choosing a number
(1, 2, or 3) to be added to the running total. The game is won by
the player whose chosen number causes the running total to reach
exactly 21. The running total starts at zero.
">
<!--DCMI metadata (Dublin Core Metadata Initiative)-->
<meta name="dc.publisher" content="Rosseta Code">
<meta name="dc.date" content="2020-07-23">
<meta name="dc.created" content="2020-07-23">
<meta name="dc.modified" content="2020-07-30">
<title>
21 Game
</title>
<!-- Remove the line below in the final/production version. -->
<meta http-equiv="cache-control" content="no-cache">
<style>
.ui div { width: 50%; display: inline-flex; justify-content: flex-end; }
div.total { margin-bottom: 1ch; }
label { padding-right: 1ch; }
button + button { margin-left: 1em; }
</style>
</head>
<body>
<h1>
21 Game in ECMA Script (Java Script)
</h1>
<p>
21 is a two player game, the game is played by choosing a number
(1, 2, or 3) to be added to the running total. The game is won by
the player whose chosen number causes the running total to reach
exactly 21. The running total starts at zero.
</p>
<p><span id="first"></span> Use buttons to play.</p>
<div class="ui">
<div class="total">
<label for="human">human last choice:</label>
<input type="text" id="human" readonly>
</div>
<div class="total">
<label for="AI">AI last choice:</label>
<input type="text" id="AI" readonly>
</div>
<div class="total">
<label for="runningTotalText">running total:</label>
<input type="text" id="runningTotalText" readonly>
</div>
<div class="buttons">
<button onclick="choice(1);" id="choice1"> one </button>
<button onclick="choice(2);" id="choice2"> two </button>
<button onclick="choice(3);" id="choice3"> three </button>
<button onclick="restart();"> restart </button>
</div>
</div>
<p id="message"></p>
<noscript>
No script, no fun. Turn on Javascript on.
</noscript>
<script>
// I really dislike global variables, but in any (?) WWW browser the global
// variables are in the window (separately for each tab) context space.
//
var runningTotal = 0;
const human = document.getElementById('human');
const AI = document.getElementById('AI');
const runningTotalText = document.getElementById('runningTotalText');
const first = document.getElementById('first')
const message = document.getElementById('message');
const choiceButtons = new Array(3);
// An function to restart game in any time, should be called as a callback
// from the WWW page, see above for an example.
//
function restart()
{
runningTotal = 0;
runningTotalText.value = runningTotal;
human.value = '';
AI.value = '';
for (let i = 1; i <= 3; i++)
{
let button = document.getElementById('choice' + i);
button.disabled = false;
choiceButtons[i] = button;
}
message.innerText = '';
if (Math.random() > 0.5)
{
update(AI, ai());
first.innerText = 'The first move is AI move.'
}
else
first.innerText = 'The first move is human move.'
}
// This function update an (read-only for a user) two text boxes
// as well as runningTotal. It should be called only once per a move/turn.
//
function update(textBox, n)
{
textBox.value = n;
runningTotal = runningTotal + n;
runningTotalText.value = runningTotal;
for (let i = 1; i <= 3; i++)
if (runningTotal + i > 21)
choiceButtons[i].disabled = true;
}
// An callback function called when the human player click the button.
//
function choice(n)
{
update(human, n);
if (runningTotal == 21)
message.innerText = 'The winner is human.';
else
{
update(AI, ai());
if (runningTotal == 21)
message.innerText = 'The winner is AI.';
}
}
// A rather simple function to calculate a computer move for the given total.
//
function ai()
{
for (let i = 1; i <= 3; i++)
if (runningTotal + i == 21)
return i;
for (let i = 1; i <= 3; i++)
if ((runningTotal + i - 1) % 4 == 0)
return i;
return 1;
}
// Run the script - actually this part do only some initialization, because
// the game is interactively driven by events from an UI written in HTML.
//
restart();
</script>
</body>
</html> |
24 game | JavaScript | The 24 Game tests one's mental arithmetic.
;Task
Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to '''24'''.
* Only the following operators/functions are allowed: multiplication, division, addition, subtraction
* Division should use floating point or rational arithmetic, etc, to preserve remainders.
* Brackets are allowed, if using an infix expression evaluator.
* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
* The order of the digits when given does not have to be preserved.
;Notes
* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
* The task is not for the program to generate the expression, or test whether an expression is even possible.
;Related tasks
* [[24 game/Solve]]
;Reference
* The 24 Game on h2g2.
| function twentyfour(numbers, input) {
var invalidChars = /[^\d\+\*\/\s-\(\)]/;
var validNums = function(str) {
// Create a duplicate of our input numbers, so that
// both lists will be sorted.
var mnums = numbers.slice();
mnums.sort();
// Sort after mapping to numbers, to make comparisons valid.
return str.replace(/[^\d\s]/g, " ")
.trim()
.split(/\s+/)
.map(function(n) { return parseInt(n, 10); })
.sort()
.every(function(v, i) { return v === mnums[i]; });
};
var validEval = function(input) {
try {
return eval(input);
} catch (e) {
return {error: e.toString()};
}
};
if (input.trim() === "") return "You must enter a value.";
if (input.match(invalidChars)) return "Invalid chars used, try again. Use only:\n + - * / ( )";
if (!validNums(input)) return "Wrong numbers used, try again.";
var calc = validEval(input);
if (typeof calc !== 'number') return "That is not a valid input; please try again.";
if (calc !== 24) return "Wrong answer: " + String(calc) + "; please try again.";
return input + " == 24. Congratulations!";
};
// I/O below.
while (true) {
var numbers = [1, 2, 3, 4].map(function() {
return Math.floor(Math.random() * 8 + 1);
});
var input = prompt(
"Your numbers are:\n" + numbers.join(" ") +
"\nEnter expression. (use only + - * / and parens).\n", +"'x' to exit.", "");
if (input === 'x') {
break;
}
alert(twentyfour(numbers, input));
}
|
24 game/Solve | JavaScript | Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].
Show examples of solutions generated by the program.
;Related task:
* [[Arithmetic Evaluator]]
| var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
function rnd(n){return Math.floor(Math.random()*n)}
function say(s){
try{document.write(s+"<br>")}
catch(e){WScript.Echo(s)}
}
function getvalue(x,dir){
var r=NOVAL;
if(dir>0)++x;
while(1){
if(val[x]!=NOVAL){
r=val[x];
val[x]=NOVAL;
break;
}
x+=dir;
}
return r*1;
}
function calc(){
var c=0,l,r,x;
val=ar.join('/').split('/');
while(c<3){
x=order[c];
l=getvalue(x,-1);
r=getvalue(x,1);
switch(op[x]){
case 0:val[x]=l+r;break;
case 1:val[x]=l-r;break;
case 2:val[x]=l*r;break;
case 3:
if(!r||l%r)return 0;
val[x]=l/r;
}
++c;
}
return getvalue(-1,1);
}
function shuffle(s,n){
var x=n,p=eval(s),r,t;
while(x--){
r=rnd(n);
t=p[x];
p[x]=p[r];
p[r]=t;
}
}
function parenth(n){
while(n>0)--n,out+='(';
while(n<0)++n,out+=')';
}
function getpriority(x){
for(var z=3;z--;)if(order[z]==x)return 3-z;
return 0;
}
function showsolution(){
var x=0,p=0,lp=0,v=0;
while(x<4){
if(x<3){
lp=p;
p=getpriority(x);
v=p-lp;
if(v>0)parenth(v);
}
out+=ar[x];
if(x<3){
if(v<0)parenth(v);
out+=oper.charAt(op[x]);
}
++x;
}
parenth(-p);
say(out);
}
function solve24(s){
var z=4,r;
while(z--)ar[z]=s.charCodeAt(z)-48;
out="";
for(z=100000;z--;){
r=rnd(256);
op[0]=r&3;
op[1]=(r>>2)&3;
op[2]=(r>>4)&3;
shuffle("ar",4);
shuffle("order",3);
if(calc()!=24)continue;
showsolution();
break;
}
}
solve24("1234");
solve24("6789");
solve24("1127"); |
4-rings or 4-squares puzzle | JavaScript from Haskell | Replace '''a, b, c, d, e, f,''' and
'''g ''' with the decimal
digits LOW ---> HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
+--------------+ +--------------+
| | | |
| a | | e |
| | | |
| +---+------+---+ +---+---------+
| | | | | | | |
| | b | | d | | f | |
| | | | | | | |
| | | | | | | |
+----------+---+ +---+------+---+ |
| c | | g |
| | | |
| | | |
+--------------+ +-------------+
Show all output here.
:* Show all solutions for each letter being unique with
LOW=1 HIGH=7
:* Show all solutions for each letter being unique with
LOW=3 HIGH=9
:* Show only the ''number'' of solutions when each letter can be non-unique
LOW=0 HIGH=9
;Related task:
* [[Solve the no connection puzzle]]
| (() => {
"use strict";
// ----------- 4-RINGS OR 4-SQUARES PUZZLE -----------
// rings :: noRepeatedDigits -> DigitList -> solutions
// rings :: Bool -> [Int] -> [[Int]]
const rings = uniq =>
digits => Boolean(digits.length) ? (
() => {
const ns = digits.sort(flip(compare));
// CENTRAL DIGIT :: d
return ns.flatMap(
ringTriage(uniq)(ns)
);
})() : [];
const ringTriage = uniq => ns => d => {
const
h = head(ns),
ts = ns.filter(x => (x + d) <= h);
// LEFT OF CENTRE :: c and a
return (
uniq ? (delete_(d)(ts)) : ns
)
.flatMap(c => {
const a = c + d;
// RIGHT OF CENTRE :: e and g
return a > h ? (
[]
) : (
uniq ? (
difference(ts)([d, c, a])
) : ns
)
.flatMap(subTriage(uniq)([ns, h, a, c, d]));
});
};
const subTriage = uniq =>
([ns, h, a, c, d]) => e => {
const g = d + e;
return ((g > h) || (
uniq && (g === c))
) ? (
[]
) : (() => {
const
agDelta = a - g,
bfs = uniq ? (
difference(ns)([
d, c, e, g, a
])
) : ns;
// MID LEFT, MID RIGHT :: b and f
return bfs.flatMap(b => {
const f = b + agDelta;
return (bfs).includes(f) && (
!uniq || ![
a, b, c, d, e, g
].includes(f)
) ? ([
[a, b, c, d, e, f, g]
]) : [];
});
})();
};
// ---------------------- TEST -----------------------
const main = () => unlines([
"rings(true, enumFromTo(1,7))\n",
unlines(
rings(true)(
enumFromTo(1)(7)
).map(show)
),
"\nrings(true, enumFromTo(3, 9))\n",
unlines(
rings(true)(
enumFromTo(3)(9)
).map(show)
),
"\nlength(rings(false, enumFromTo(0, 9)))\n",
rings(false)(
enumFromTo(0)(9)
)
.length
.toString(),
""
]);
// ---------------- GENERIC FUNCTIONS ----------------
// compare :: a -> a -> Ordering
const compare = (a, b) =>
a < b ? -1 : (a > b ? 1 : 0);
// delete :: Eq a => a -> [a] -> [a]
const delete_ = x => {
// xs with first instance of x (if any) removed.
const go = xs =>
Boolean(xs.length) ? (
(x === xs[0]) ? (
xs.slice(1)
) : [xs[0]].concat(go(xs.slice(1)))
) : [];
return go;
};
// difference :: Eq a => [a] -> [a] -> [a]
const difference = xs =>
ys => {
const s = new Set(ys);
return xs.filter(x => !s.has(x));
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// flip :: (a -> b -> c) -> b -> a -> c
const flip = op =>
// The binary function op with
// its arguments reversed.
1 !== op.length ? (
(a, b) => op(b, a)
) : (a => b => op(b)(a));
// head :: [a] -> a
const head = xs =>
// The first item (if any) in a list.
Boolean(xs.length) ? (
xs[0]
) : null;
// show :: a -> String
const show = x =>
JSON.stringify(x);
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join("\n");
// MAIN ---
return main();
})(); |
99 bottles of beer | JavaScript | Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''.
;The beer song:
The lyrics follow this form:
::: 99 bottles of beer on the wall
::: 99 bottles of beer
::: Take one down, pass it around
::: 98 bottles of beer on the wall
::: 98 bottles of beer on the wall
::: 98 bottles of beer
::: Take one down, pass it around
::: 97 bottles of beer on the wall
... and so on, until reaching '''0''' (zero).
Grammatical support for ''1 bottle of beer'' is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
;See also:
* http://99-bottles-of-beer.net/
* [[:Category:99_Bottles_of_Beer]]
* [[:Category:Programming language families]]
* Wikipedia 99 bottles of beer
| function Bottles(count) {
this.count = count || 99;
}
Bottles.prototype.take = function() {
var verse = [
this.count + " bottles of beer on the wall,",
this.count + " bottles of beer!",
"Take one down, pass it around",
(this.count - 1) + " bottles of beer on the wall!"
].join("\n");
console.log(verse);
this.count--;
};
Bottles.prototype.sing = function() {
while (this.count) {
this.take();
}
};
var bar = new Bottles(99);
bar.sing(); |
9 billion names of God the integer | JavaScript from Python | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a "name":
:The integer 1 has 1 name "1".
:The integer 2 has 2 names "1+1", and "2".
:The integer 3 has 3 names "1+1+1", "2+1", and "3".
:The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".
:The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".
;Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.
A function G(n) should return the sum of the n-th row.
Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345).
Optionally note that the sum of the n-th row P(n) is the integer partition function.
Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).
;Extra credit
If your environment is able, plot P(n) against n for n=1\ldots 999.
;Related tasks
* [[Partition function P]]
| (function () {
var cache = [
[1]
];
//this was never needed.
/* function PyRange(start, end, step) {
step = step || 1;
if (!end) {
end = start;
start = 0;
}
var arr = [];
for (var i = start; i < end; i += step) arr.push(i);
return arr;
}*/
function cumu(n) {
var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this
r, l, x, Aa, Mi;
// for (ll in ra) { too pythony
for (l=cache.length;l<n+1;l++) {
r = [0];
// l = ra[ll];
// ran = PyRange(1, l + 1);
// for (xx in ran) {
for(x=1;x<l+1;x++){
// x = ran[xx];
r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
}
cache.push(r);
}
return cache[n];
}
function row(n) {
var r = cumu(n),
// rra = PyRange(n),
leArray = [],
i;
// for (ii in rra) {
for (i=0;i<n;i++) {
// i = rra[ii];
leArray.push(r[i + 1] - r[i]);
}
return leArray;
}
console.log("Rows:");
for (iterator = 1; iterator < 12; iterator++) {
console.log(row(iterator));
}
// PL clearly this was not tested:
// console.log("Sums")[23, 123, 1234, 12345].foreach(function (a) {
console.log("Sums");
[23, 123, 1234, 12345].forEach(function (a) {
var s = cumu(a);
console.log(a, s[s.length - 1]);
});
})()
|
A+B | JavaScript | '''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
;Task:
Given two integers, '''A''' and '''B'''.
Their sum needs to be calculated.
;Input data:
Two integers are written in the input stream, separated by space(s):
: (-1000 \le A,B \le +1000)
;Output data:
The required output is one integer: the sum of '''A''' and '''B'''.
;Example:
::{|class="standard"
! input
! output
|-
| 2 2
| 4
|-
| 3 2
| 5
|}
| <html>
<body>
<div id='input'></div>
<div id='output'></div>
<script type='text/javascript'>
var a = window.prompt('enter A number', '');
var b = window.prompt('enter B number', '');
document.getElementById('input').innerHTML = a + ' ' + b;
var sum = Number(a) + Number(b);
document.getElementById('output').innerHTML = sum;
</script>
</body>
</html> |
ABC problem | JavaScript | You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
;Task:
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
::# Once a letter on a block is used that block cannot be used again
::# The function should be case-insensitive
::# Show the output on this page for the following 7 words in the following example
;Example:
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
| (function (strWords) {
var strBlocks =
'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM',
blocks = strBlocks.split(' ');
function abc(lstBlocks, strWord) {
var lngChars = strWord.length;
if (!lngChars) return [];
var b = lstBlocks[0],
c = strWord[0];
return chain(lstBlocks, function (b) {
return (b.indexOf(c.toUpperCase()) !== -1) ? [
(b + ' ').concat(
abc(removed(b, lstBlocks), strWord.slice(1)))
] : [];
})
}
// Monadic bind (chain) for lists
function chain(xs, f) {
return [].concat.apply([], xs.map(f));
}
// a -> [a] -> [a]
function removed(x, xs) {
var h = xs.length ? xs[0] : null,
t = h ? xs.slice(1) : [];
return h ? (
h === x ? t : [h].concat(removed(x, t))
) : [];
}
function solution(strWord) {
var strAttempt = abc(blocks, strWord)[0].split(',')[0];
// two chars per block plus one space -> 3
return strWord + ((strAttempt.length === strWord.length * 3) ?
' -> ' + strAttempt : ': [no solution]');
}
return strWords.split(' ').map(solution).join('\n');
})('A bark BooK TReAT COMMON squAD conFUSE'); |
ABC problem | JavaScript from Haskell | You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
;Task:
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
::# Once a letter on a block is used that block cannot be used again
::# The function should be case-insensitive
::# Show the output on this page for the following 7 words in the following example
;Example:
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
| (() => {
"use strict";
// ------------------- ABC BLOCKS --------------------
// spellWith :: [(Char, Char)] -> [Char] -> [[(Char, Char)]]
const spellWith = blocks =>
wordChars => !Boolean(wordChars.length) ? [
[]
] : (() => {
const [x, ...xs] = wordChars;
return blocks.flatMap(
b => b.includes(x) ? (
spellWith(
deleteBy(
p => q => (p[0] === q[0]) && (
p[1] === q[1]
)
)(b)(blocks)
)(xs)
.flatMap(bs => [b, ...bs])
) : []
);
})();
// ---------------------- TEST -----------------------
const main = () => {
const blocks = (
"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
).split(" ");
return [
"", "A", "BARK", "BoOK", "TrEAT",
"COmMoN", "SQUAD", "conFUsE"
]
.map(
x => JSON.stringify([
x, !Boolean(
spellWith(blocks)(
[...x.toLocaleUpperCase()]
)
.length
)
])
)
.join("\n");
};
// ---------------- GENERIC FUNCTIONS ----------------
// deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
const deleteBy = fEq =>
x => {
const go = xs => Boolean(xs.length) ? (
fEq(x)(xs[0]) ? (
xs.slice(1)
) : [xs[0], ...go(xs.slice(1))]
) : [];
return go;
};
// MAIN ---
return main();
})(); |
ASCII art diagram converter | JavaScript | Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Where (every column of the table is 1 bit):
ID is 16 bits
QR = Query (0) or Response (1)
Opcode = Four bits defining kind of query:
0: a standard query (QUERY)
1: an inverse query (IQUERY)
2: a server status request (STATUS)
3-15: reserved for future use
AA = Authoritative Answer bit
TC = Truncation bit
RD = Recursion Desired bit
RA = Recursion Available bit
Z = Reserved
RCODE = Response code
QC = Question Count
ANC = Answer Count
AUC = Authority Count
ADC = Additional Count
Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.
If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.
Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required.
Bonus: perform a thoroughly validation of the input string.
| // ------------------------------------------------------------[ Boilerplate ]--
const trimWhitespace = s => s.trim();
const isNotEmpty = s => s !== '';
const stringLength = s => s.length;
const hexToBin4 = s => parseInt(s, 16).toString(2).padStart(4, '0');
const concatHexToBin = (binStr, hexStr) => binStr.concat('', hexToBin4(hexStr));
const alignRight = n => s => `${s}`.padStart(n, ' ');
const alignLeft = n => s => `${s}`.padEnd(n, ' ');
const repeatChar = c => n => c.padStart(n, c);
const joinWith = c => arr => arr.join(c);
const joinNl = joinWith('\n');
const joinSp = joinWith(' ');
const printDiagramInfo = map => {
const pName = alignLeft(8);
const p5 = alignRight(5);
const line = repeatChar('-');
const res = [];
res.push(joinSp([pName('Name'), p5('Size'), p5('Start'), p5('End')]));
res.push(joinSp([line(8), line(5), line(5), line(5)]));
[...map.values()].forEach(({label, bitLength, start, end}) => {
res.push(joinSp([pName(label), p5(bitLength), p5(start), p5(end)]));
})
return res;
}
// -------------------------------------------------------------------[ Main ]--
const parseDiagram = dia => {
const arr = dia.split('\n').map(trimWhitespace).filter(isNotEmpty);
const hLine = arr[0];
const bitTokens = hLine.split('+').map(trimWhitespace).filter(isNotEmpty);
const bitWidth = bitTokens.length;
const bitTokenWidth = bitTokens[0].length;
const fields = arr.filter(e => e !== hLine);
const allFields = fields.reduce((p, c) => [...p, ...c.split('|')], [])
.filter(isNotEmpty);
const lookupMap = Array(bitWidth).fill('').reduce((p, c, i) => {
const v = i + 1;
const stringWidth = (v * bitTokenWidth) + (v - 1);
p.set(stringWidth, v);
return p;
}, new Map())
const fieldMetaMap = allFields.reduce((p, e, i) => {
const bitLength = lookupMap.get(e.length);
const label = trimWhitespace(e);
const start = i ? p.get(i - 1).end + 1 : 0;
const end = start - 1 + bitLength;
p.set(i, {label, bitLength, start, end})
return p;
}, new Map());
const pName = alignLeft(8);
const pBit = alignRight(5);
const pPat = alignRight(18);
const line = repeatChar('-');
const nl = '\n';
return hexStr => {
const binString = [...hexStr].reduce(concatHexToBin, '');
const res = printDiagramInfo(fieldMetaMap);
res.unshift(joinNl(['Diagram:', ...arr, nl]));
res.push(joinNl([nl, 'Test string in hex:', hexStr]));
res.push(joinNl(['Test string in binary:', binString, nl]));
res.push(joinSp([pName('Name'), pBit('Size'), pPat('Pattern')]));
res.push(joinSp([line(8), line(5), line(18)]));
[...fieldMetaMap.values()].forEach(({label, bitLength, start, end}) => {
res.push(joinSp(
[pName(label), pBit(bitLength),
pPat(binString.substr(start, bitLength))]))
})
return joinNl(res);
}
}
// --------------------------------------------------------------[ Run tests ]--
const dia = `
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
`;
const parser = parseDiagram(dia);
parser('78477bbf5496e12e1bf169a4'); |
AVL tree | Javascript | {{wikipedia|AVL tree}}
In computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
;Task:
Implement an AVL tree in the language of choice, and provide at least basic operations.
;Related task
[[Red_black_tree_sort]]
| function tree(less, val, more) {
return {
depth: 1+Math.max(less.depth, more.depth),
less: less,
val: val,
more: more,
};
}
function node(val) {
return tree({depth: 0}, val, {depth: 0});
}
function insert(x,y) {
if (0 == y.depth) return x;
if (0 == x.depth) return y;
if (1 == x.depth && 1 == y.depth) {
switch (Math.sign(y.val)-x.val) {
case -1: return tree(y, x.val, {depth: 0});
case 0: return y;
case 1: return tree(x, y.val, {depth: 0});
}
}
switch (Math.sign(y.val-x.val)) {
case -1: return balance(insert(x.less, y), x.val, x.more);
case 0: return balance(insert(x.less, y.less), x.val, insert(x.more, y.more));
case 1: return balance(x.less. x.val, insert(x.more, y));
}
}
function balance(less,val,more) {
if (2 > Math.abs(less.depth-more.depth))
return tree(less,val,more);
if (more.depth > less.depth) {
if (more.more.depth >= more.less.depth) {
// 'more' was heavy
return moreHeavy(less, val, more);
} else {
return moreHeavy(less,val,lessHeavy(more.less, more.val, more.more));
}
} else {
if(less.less.depth >= less.more.depth) {
return lessHeavy(less, val, more);
} else {
return lessHeavy(moreHeavy(less.less, less.val, less.more), val, more);
}
}
}
function moreHeavy(less,val,more) {
return tree(tree(less,val,more.less), more.val, more.more)
}
function lessHeavy(less,val,more) {
return tree(less.less, less.val, tree(less.more, val, more));
}
function remove(val, y) {
switch (y.depth) {
case 0: return y;
case 1:
if (val == y.val) {
return y.less;
} else {
return y;
}
default:
switch (Math.sign(y.val - val)) {
case -1: return balance(y.less, y.val, remove(val, y.more));
case 0: return insert(y.less, y.more);
case 1: return balance(remove(val, y.less), y.val, y.more)
}
}
}
function lookup(val, y) {
switch (y.depth) {
case 0: return y;
case 1: if (val == y.val) {
return y;
} else {
return {depth: 0};
}
default:
switch (Math.sign(y.val-val)) {
case -1: return lookup(val, y.more);
case 0: return y;
case 1: return lookup(val, y.less);
}
}
} |
Abbreviations, automatic | JavaScript | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbreviation length of that list could be automatically (programmatically) determined.
For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miercoles xueves vienres sabadu
Bazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mekredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^li utery str^eda c^tvrtek patek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato
pUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev
Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mercores Joves Venres Sabado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
popule po`akahi po`alua po`akolu po`aha po`alima po`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasarnap hetfo kedd szerda csutortok pentek szombat
Sunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
De_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn
domenica lunedi martedi mercoledi giovedi venerdi sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minomishi martes mierkoles misheushi bernashi mishabaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sphndag mandag tirsdag onsdag torsdag fredag lphrdag
lo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabierna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminica Luni Mart'i Miercuri Joi Vineri Sambata
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miercoles jueves viernes sabado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
sondag mandag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Le-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sabado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
djadomingu djaluna djamars djarason djaweps djabierne djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau
''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''
To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).
Notes concerning the above list of words
::* each line has a list of days-of-the-week for a language, separated by at least one blank
::* the words on each line happen to be in order, from Sunday --> Saturday
::* most lines have words in mixed case and some have all manner of accented words and other characters
::* some words were translated to the nearest character that was available to ''code page'' '''437'''
::* the characters in the words are not restricted except that they may not have imbedded blanks
::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word
;Task:
::* The list of words (days of the week) needn't be verified/validated.
::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.
::* A blank line (or a null line) should return a null string.
::* Process and show the output for at least the first '''five''' lines of the file.
::* Show all output here.
| Array.prototype.hasDoubles = function() {
let arr = this.slice();
while (arr.length > 1) {
let cur = arr.shift();
if (arr.includes(cur)) return true;
}
return false;
}
function getMinAbbrLen(arr) {
if (arr.length <= 1) return '';
let testArr = [],
len = 0, i;
do {
len++;
for (i = 0; i < arr.length; i++)
testArr[i] = arr[i].substr(0, len);
} while (testArr.hasDoubles());
return len;
}
// testing
for (let x = 0; x < list.length; x++) {
let days = list[x].split(' '),
l = getMinAbbrLen(days);
for (let y = 0; y < days.length; y++)
days[y] = days[y].substring(0, l);
document.write(`<p>(${l}): ${days.join('. ')}.</p>`);
}
|
Abbreviations, easy | JavaScript | This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].
For this task, the following ''command table'' will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the number of capital letters of the word in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''
::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters
::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''
::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| var abr=`Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up`
.split(/\W+/).map(_=>_.trim())
function escapeRegex(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var input = prompt();
console.log(input.length==0?null:input.trim().split(/\s+/)
.map(
(s=>abr.filter(
a=>(new RegExp('^'+escapeRegex(s),'i'))
.test(a)&&s.length>=a.match(/^[A-Z]+/)[0].length
)[0])
)
.map(_=>typeof _=="undefined"?"*error*":_).join(' ')
)
|
Abbreviations, simple | JavaScript from Python | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
For this task, the following ''command table'' will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* a command is followed by an optional number, which indicates the minimum abbreviation
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the word's minimum number in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''
::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters
::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''
::* if there isn't a number after the command, then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| (() => {
'use strict';
// withExpansions :: [(String, Int)] -> String -> String
const withExpansions = tbl => s =>
unwords(map(expanded(tbl), words(s)));
// expanded :: [(String, Int)] -> String -> String
const expanded = tbl => s => {
const
lng = s.length,
u = toUpper(s),
p = wn => {
const [w, n] = Array.from(wn);
return lng >= n && isPrefixOf(u, w);
}
return maybe(
'*error*',
fst,
0 < lng ? (
find(p, tbl)
) : Just(Tuple([], 0))
);
};
// cmdsFromString :: String -> [(String, Int)]
const cmdsFromString = s =>
fst(foldr(
(w, a) => {
const [xs, n] = Array.from(a);
return isDigit(head(w)) ? (
Tuple(xs, parseInt(w, 10))
) : Tuple(
[Tuple(toUpper(w), n)].concat(xs),
0
);
},
Tuple([], 0),
words(s)
));
// TEST -----------------------------------------------
const main = () => {
// table :: [(String, Int)]
const table = cmdsFromString(
`add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1
Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3
cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3
extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1
split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3
Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1
parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4
rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3
status 4 top transfer 3 type 1 up 1`
);
return fTable(
'Abbreviation tests:\n',
s => "'" + s + "'",
s => "\n\t'" + s + "'",
withExpansions(table),
[
'riG rePEAT copies put mo rest types fup. 6 poweRin',
''
]
);
};
// GENERIC FUNCTIONS ----------------------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (f, g) => x => f(g(x));
// find :: (a -> Bool) -> [a] -> Maybe a
const find = (p, xs) => {
for (let i = 0, lng = xs.length; i < lng; i++) {
if (p(xs[i])) return Just(xs[i]);
}
return Nothing();
};
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
1 < f.length ? (
(a, b) => f(b, a)
) : (x => y => f(y)(x));
// foldl1 :: (a -> a -> a) -> [a] -> a
const foldl1 = (f, xs) =>
1 < xs.length ? xs.slice(1)
.reduce(f, xs[0]) : xs[0];
// foldr :: (a -> b -> b) -> b -> [a] -> b
const foldr = (f, a, xs) => xs.reduceRight(flip(f), a);
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// fTable :: String -> (a -> String) ->
// (b -> String) -> (a -> b) -> [a] -> String
const fTable = (s, xShow, fxShow, f, xs) => {
// Heading -> x display function ->
// fx display function ->
// f -> values -> tabular string
const
ys = map(xShow, xs),
w = maximum(map(length, ys)),
rows = zipWith(
(a, b) => justifyRight(w, ' ', a) + ' -> ' + b,
ys,
map(compose(fxShow, f), xs)
);
return s + '\n' + unlines(rows);
};
// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;
// isDigit :: Char -> Bool
const isDigit = c => {
const n = ord(c);
return 48 <= n && 57 >= n;
};
// isPrefixOf takes two lists or strings and returns
// true iff the first is a prefix of the second.
// isPrefixOf :: [a] -> [a] -> Bool
// isPrefixOf :: String -> String -> Bool
const isPrefixOf = (xs, ys) => {
const go = (xs, ys) => {
const intX = xs.length;
return 0 < intX ? (
ys.length >= intX ? xs[0] === ys[0] && go(
xs.slice(1), ys.slice(1)
) : false
) : true;
};
return 'string' !== typeof xs ? (
go(xs, ys)
) : ys.startsWith(xs);
};
// justifyRight :: Int -> Char -> String -> String
const justifyRight = (n, cFiller, s) =>
n > s.length ? (
s.padStart(n, cFiller)
) : s;
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// maximum :: Ord a => [a] -> a
const maximum = xs =>
0 < xs.length ? (
foldl1((a, x) => x > a ? x : a, xs)
) : undefined;
// maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = (v, f, m) =>
m.Nothing ? v : f(m.Just);
// ord :: Char -> Int
const ord = c => c.codePointAt(0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// toUpper :: String -> String
const toUpper = s => s.toLocaleUpperCase();
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
// words :: String -> [String]
const words = s => s.split(/\s+/);
// Use of `take` and `length` here allows zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const
lng = Math.min(length(xs), length(ys)),
as = take(lng, xs),
bs = take(lng, ys);
return Array.from({
length: lng
}, (_, i) => f(as[i], bs[i], i));
};
// MAIN ---
return main();
})(); |
Abundant odd numbers | JavaScript from Python | An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',
or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.
;E.G.:
'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n''');
or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').
Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers.
To make things more interesting, this task is specifically about finding ''odd abundant numbers''.
;Task
*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
;References:
:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| (() => {
'use strict';
const main = () => {
// abundantTuple :: Int -> [(Int, Int)]
const abundantTuple = n => {
// Either a list containing the tuple of N
// and its divisor sum (if n is abundant),
// or otherwise an empty list.
const x = divisorSum(n);
return n < x ? ([
Tuple(n)(x)
]) : [];
};
// divisorSum :: Int -> Int
const divisorSum = n => {
// Sum of the divisors of n.
const
floatRoot = Math.sqrt(n),
intRoot = Math.floor(floatRoot),
lows = filter(x => 0 === n % x)(
enumFromTo(1)(intRoot)
);
return sum(lows.concat(map(quot(n))(
intRoot === floatRoot ? (
lows.slice(1, -1)
) : lows.slice(1)
)));
};
// TEST ---------------------------------------
console.log(
'First 25 abundant odd numbers, with their divisor sums:'
)
console.log(unlines(map(showTuple)(
take(25)(
concatMapGen(abundantTuple)(
enumFromThen(1)(3)
)
)
)));
console.log(
'\n\n1000th abundant odd number, with its divisor sum:'
)
console.log(showTuple(
take(1)(drop(999)(
concatMapGen(abundantTuple)(
enumFromThen(1)(3)
)
))[0]
))
console.log(
'\n\nFirst abundant odd number above 10^9, with divisor sum:'
)
const billion = Math.pow(10, 9);
console.log(showTuple(
take(1)(
concatMapGen(abundantTuple)(
enumFromThen(1 + billion)(3 + billion)
)
)[0]
))
};
// GENERAL REUSABLE FUNCTIONS -------------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// concatMapGen :: (a -> [b]) -> Gen [a] -> Gen [b]
const concatMapGen = f =>
function*(xs) {
let
x = xs.next(),
v = undefined;
while (!x.done) {
v = f(x.value);
if (0 < v.length) {
yield v[0];
}
x = xs.next();
}
};
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = n => xs =>
Infinity > length(xs) ? (
xs.slice(n)
) : (take(n)(xs), xs);
// dropAround :: (a -> Bool) -> [a] -> [a]
// dropAround :: (Char -> Bool) -> String -> String
const dropAround = p => xs => dropWhile(p)(
dropWhileEnd(p)(xs)
);
// dropWhile :: (a -> Bool) -> [a] -> [a]
// dropWhile :: (Char -> Bool) -> String -> String
const dropWhile = p => xs => {
const lng = xs.length;
return 0 < lng ? xs.slice(
until(i => i === lng || !p(xs[i]))(
i => 1 + i
)(0)
) : [];
};
// dropWhileEnd :: (a -> Bool) -> [a] -> [a]
// dropWhileEnd :: (Char -> Bool) -> String -> String
const dropWhileEnd = p => xs => {
let i = xs.length;
while (i-- && p(xs[i])) {}
return xs.slice(0, i + 1);
};
// enumFromThen :: Int -> Int -> Gen [Int]
const enumFromThen = x =>
// A non-finite stream of integers,
// starting with x and y, and continuing
// with the same interval.
function*(y) {
const d = y - x;
let v = y + d;
yield x;
yield y;
while (true) {
yield v;
v = d + v;
}
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m => n =>
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = f => xs => xs.filter(f);
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = f => xs =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// quot :: Int -> Int -> Int
const quot = n => m => Math.floor(n / m);
// show :: a -> String
const show = JSON.stringify;
// showTuple :: Tuple -> String
const showTuple = tpl =>
'(' + enumFromTo(0)(tpl.length - 1)
.map(x => unQuoted(show(tpl[x])))
.join(',') + ')';
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => xs =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p => f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// unQuoted :: String -> String
const unQuoted = s =>
dropAround(x => 34 === x.codePointAt(0))(
s
);
// MAIN ---
return main();
})(); |
Accumulator factory | JavaScript | {{requires|Mutable State}}
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function
:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''
;Task:
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| function accumulator(sum) {
return function(n) {
return sum += n;
}
}
var x = accumulator(1);
x(5);
console.log(accumulator(3).toString() + '<br>');
console.log(x(2.3)); |
Amb | JavaScript | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
#"the" "that" "a"
#"frog" "elephant" "thing"
#"walked" "treaded" "grows"
#"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| function ambRun(func) {
var choices = [];
var index;
function amb(values) {
if (values.length == 0) {
fail();
}
if (index == choices.length) {
choices.push({i: 0,
count: values.length});
}
var choice = choices[index++];
return values[choice.i];
}
function fail() { throw fail; }
while (true) {
try {
index = 0;
return func(amb, fail);
} catch (e) {
if (e != fail) {
throw e;
}
var choice;
while ((choice = choices.pop()) && ++choice.i == choice.count) {}
if (choice == undefined) {
return undefined;
}
choices.push(choice);
}
}
}
ambRun(function(amb, fail) {
function linked(s1, s2) {
return s1.slice(-1) == s2.slice(0, 1);
}
var w1 = amb(["the", "that", "a"]);
var w2 = amb(["frog", "elephant", "thing"]);
if (!linked(w1, w2)) fail();
var w3 = amb(["walked", "treaded", "grows"]);
if (!linked(w2, w3)) fail();
var w4 = amb(["slowly", "quickly"]);
if (!linked(w3, w4)) fail();
return [w1, w2, w3, w4].join(' ');
}); // "that thing grows slowly" |
Anagrams/Deranged anagrams | JavaScript | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.
;Task
Use the word list at unixdict to find and display the longest deranged anagram.
;Related
* [[Permutations/Derangements]]
* Best shuffle
{{Related tasks/Word plays}}
| #!/usr/bin/env js
function main() {
var wordList = read('unixdict.txt').split(/\s+/);
var anagrams = findAnagrams(wordList);
var derangedAnagrams = findDerangedAnagrams(anagrams);
var longestPair = findLongestDerangedPair(derangedAnagrams);
print(longestPair.join(' '));
}
function findLongestDerangedPair(danas) {
var longestLen = danas[0][0].length;
var longestPair = danas[0];
for (var i in danas) {
if (danas[i][0].length > longestLen) {
longestLen = danas[i][0].length;
longestPair = danas[i];
}
}
return longestPair;
}
function findDerangedAnagrams(anagrams) {
var deranged = [];
function isDeranged(w1, w2) {
for (var c = 0; c < w1.length; c++) {
if (w1[c] == w2[c]) {
return false;
}
}
return true;
}
function findDeranged(anas) {
for (var a = 0; a < anas.length; a++) {
for (var b = a + 1; b < anas.length; b++) {
if (isDeranged(anas[a], anas[b])) {
deranged.push([anas[a], anas[b]]);
}
}
}
}
for (var a in anagrams) {
var anas = anagrams[a];
findDeranged(anas);
}
return deranged;
}
function findAnagrams(wordList) {
var anagrams = {};
for (var wordNum in wordList) {
var word = wordList[wordNum];
var key = word.split('').sort().join('');
if (!(key in anagrams)) {
anagrams[key] = [];
}
anagrams[key].push(word);
}
for (var a in anagrams) {
if (anagrams[a].length < 2) {
delete(anagrams[a]);
}
}
return anagrams;
}
main(); |
Angle difference between two bearings | Javascript | Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]
;Task:
Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings.
Input bearings are expressed in the range '''-180''' to '''+180''' degrees.
The result is also expressed in the range '''-180''' to '''+180''' degrees.
Compute the angle for the following pairs:
* 20 degrees ('''b1''') and 45 degrees ('''b2''')
* -45 and 45
* -85 and 90
* -95 and 90
* -45 and 125
* -45 and 145
* 29.4803 and -88.6381
* -78.3251 and -159.036
;Optional extra:
Allow the input bearings to be any (finite) value.
;Test cases:
* -70099.74233810938 and 29840.67437876723
* -165313.6666297357 and 33693.9894517456
* 1174.8380510598456 and -154146.66490124757
* 60175.77306795546 and 42213.07192354373
| function relativeBearing(b1Rad, b2Rad)
{
b1y = Math.cos(b1Rad);
b1x = Math.sin(b1Rad);
b2y = Math.cos(b2Rad);
b2x = Math.sin(b2Rad);
crossp = b1y * b2x - b2y * b1x;
dotp = b1x * b2x + b1y * b2y;
if(crossp > 0.)
return Math.acos(dotp);
return -Math.acos(dotp);
}
function test()
{
var deg2rad = 3.14159265/180.0;
var rad2deg = 180.0/3.14159265;
return "Input in -180 to +180 range\n"
+relativeBearing(20.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-85.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-95.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 125.0*deg2rad)*rad2deg+"\n"
+relativeBearing(-45.0*deg2rad, 145.0*deg2rad)*rad2deg+"\n"
+relativeBearing(29.4803*deg2rad, -88.6381*deg2rad)*rad2deg+"\n"
+relativeBearing(-78.3251*deg2rad, -159.036*deg2rad)*rad2deg+"\n"
+ "Input in wider range\n"
+relativeBearing(-70099.74233810938*deg2rad, 29840.67437876723*deg2rad)*rad2deg+"\n"
+relativeBearing(-165313.6666297357*deg2rad, 33693.9894517456*deg2rad)*rad2deg+"\n"
+relativeBearing(1174.8380510598456*deg2rad, -154146.66490124757*deg2rad)*rad2deg+"\n"
+relativeBearing(60175.77306795546*deg2rad, 42213.07192354373*deg2rad)*rad2deg+"\n";
} |
Anti-primes | Javascript | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
;Task:
Generate and show here, the first twenty anti-primes.
;Related tasks:
:* [[Factors of an integer]]
:* [[Sieve of Eratosthenes]]
| function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (ifactors.length > maxFactors) {
antiprimes.push(i);
maxFactors = ifactors.length;
}
}
return antiprimes;
}
function go() {
var number = document.getElementById("n").value;
document.body.removeChild(document.getElementById("result-list"));
document.body.appendChild(showList(generateAntiprimes(number)));
}
function showList(array) {
var list = document.createElement("ul");
list.id = "result-list";
for (var i = 0; i < array.length; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
|
Arithmetic-geometric mean | JavaScript | {{wikipedia|Arithmetic-geometric mean}}
;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})
;Also see:
* mathworld.wolfram.com/Arithmetic-Geometric Mean
| (() => {
'use strict';
// ARITHMETIC-GEOMETRIC MEAN
// agm :: Num a => a -> a -> a
let agm = (a, g) => {
let abs = Math.abs,
sqrt = Math.sqrt;
return until(
m => abs(m.an - m.gn) < tolerance,
m => {
return {
an: (m.an + m.gn) / 2,
gn: sqrt(m.an * m.gn)
};
}, {
an: (a + g) / 2,
gn: sqrt(a * g)
}
)
.an;
},
// GENERIC
// until :: (a -> Bool) -> (a -> a) -> a -> a
until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// TEST
let tolerance = 0.000001;
return agm(1, 1 / Math.sqrt(2));
})(); |
Arithmetic evaluation | JavaScript | Create a program which parses and evaluates arithmetic expressions.
;Requirements:
* An abstract-syntax tree (AST) for the expression must be created from parsing the input.
* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
* The expression will be a string or list of symbols like "(1+3)*7".
* The four symbols + - * / must be supported as binary operators with conventional precedence rules.
* Precedence-control parentheses must also be supported.
;Note:
For those who don't remember, mathematical precedence is as follows:
* Parentheses
* Multiplication/Division (left to right)
* Addition/Subtraction (left to right)
;C.f:
* [[24 game Player]].
* [[Parsing/RPN calculator algorithm]].
* [[Parsing/RPN to infix conversion]].
| function evalArithmeticExp(s) {
s = s.replace(/\s/g,'').replace(/^\+/,'');
var rePara = /\([^\(\)]*\)/;
var exp = s.match(rePara);
while (exp = s.match(rePara)) {
s = s.replace(exp[0], evalExp(exp[0]));
}
return evalExp(s);
function evalExp(s) {
s = s.replace(/[\(\)]/g,'');
var reMD = /\d+\.?\d*\s*[\*\/]\s*[+-]?\d+\.?\d*/;
var reM = /\*/;
var reAS = /-?\d+\.?\d*\s*[\+-]\s*[+-]?\d+\.?\d*/;
var reA = /\d\+/;
var exp;
while (exp = s.match(reMD)) {
s = exp[0].match(reM)? s.replace(exp[0], multiply(exp[0])) : s.replace(exp[0], divide(exp[0]));
}
while (exp = s.match(reAS)) {
s = exp[0].match(reA)? s.replace(exp[0], add(exp[0])) : s.replace(exp[0], subtract(exp[0]));
}
return '' + s;
function multiply(s, b) {
b = s.split('*');
return b[0] * b[1];
}
function divide(s, b) {
b = s.split('/');
return b[0] / b[1];
}
function add(s, b) {
s = s.replace(/^\+/,'').replace(/\++/,'+');
b = s.split('+');
return Number(b[0]) + Number(b[1]);
}
function subtract(s, b) {
s = s.replace(/\+-|-\+/g,'-');
if (s.match(/--/)) {
return add(s.replace(/--/,'+'));
}
b = s.split('-');
return b.length == 3? -1 * b[1] - b[2] : b[0] - b[1];
}
}
} |
Array length | JavaScript | Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
| function last(list, defaultValue) {
return list.length ?list[list.length-1] :defaultValue;
} |
Ascending primes | JavaScript from Java | Generate and show all primes with strictly ascending decimal digits.
Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.
;See also
;* OEIS:A052015 - Primes with distinct digits in ascending order
;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)
| <!DOCTYPE html>
<html>
<body>
<noscript>
No script, no fun. Turn on Javascript on.
</noscript>
<script>
(()=>{
function isPrime(n) {
if (n == 2)
return true;
if (n == 1 || n % 2 == 0)
return false;
root = Math.sqrt(n)
for (let k = 3; k <= root; k += 2)
if (n % k == 0)
return false;
return true;
}
let queue = [];
let primes = [];
for (let k = 1; k <= 9; k++)
queue.push(k);
while (queue.length != 0)
{
let n = queue.shift();
if (isPrime(n))
primes.push(n);
for (let k = n % 10 + 1; k <= 9; k++)
queue.push(n * 10 + k);
}
document.writeln(primes);
})();
</script>
</body>
</html> |
Associative array/Merging | JavaScript | Define two associative arrays, where one represents the following "base" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}
And the other represents "update" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
| (() => {
'use strict';
console.log(JSON.stringify(
Object.assign({}, // Fresh dictionary.
{ // Base.
"name": "Rocket Skates",
"price": 12.75,
"color": "yellow"
}, { // Update.
"price": 15.25,
"color": "red",
"year": 1974
}
),
null, 2
))
})(); |
Attractive numbers | JavaScript | A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.
;Example:
The number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.
;Task:
Show sequence items up to '''120'''.
;Reference:
:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| (() => {
'use strict';
// attractiveNumbers :: () -> Gen [Int]
const attractiveNumbers = () =>
// An infinite series of attractive numbers.
filter(
compose(isPrime, length, primeFactors)
)(enumFrom(1));
// ----------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showCols(10)(
takeWhile(ge(120))(
attractiveNumbers()
)
);
// ---------------------- PRIMES ----------------------
// isPrime :: Int -> Bool
const isPrime = n => {
// True if n is prime.
if (2 === n || 3 === n) {
return true
}
if (2 > n || 0 === n % 2) {
return false
}
if (9 > n) {
return true
}
if (0 === n % 3) {
return false
}
return !enumFromThenTo(5)(11)(
1 + Math.floor(Math.pow(n, 0.5))
).some(x => 0 === n % x || 0 === n % (2 + x));
};
// primeFactors :: Int -> [Int]
const primeFactors = n => {
// A list of the prime factors of n.
const
go = x => {
const
root = Math.floor(Math.sqrt(x)),
m = until(
([q, _]) => (root < q) || (0 === (x % q))
)(
([_, r]) => [step(r), 1 + r]
)([
0 === x % 2 ? (
2
) : 3,
1
])[0];
return m > root ? (
[x]
) : ([m].concat(go(Math.floor(x / m))));
},
step = x => 1 + (x << 2) - ((x >> 1) << 1);
return go(n);
};
// ---------------- GENERIC FUNCTIONS -----------------
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n =>
xs => enumFromThenTo(0)(n)(
xs.length - 1
).reduce(
(a, i) => a.concat([xs.slice(i, (n + i))]),
[]
);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// enumFrom :: Enum a => a -> [a]
function* enumFrom(x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
while (true) {
yield v;
v = 1 + v;
}
}
// enumFromThenTo :: Int -> Int -> Int -> [Int]
const enumFromThenTo = x1 =>
x2 => y => {
const d = x2 - x1;
return Array.from({
length: Math.floor(y - x2) / d + 2
}, (_, i) => x1 + (d * i));
};
// filter :: (a -> Bool) -> Gen [a] -> [a]
const filter = p => xs => {
function* go() {
let x = xs.next();
while (!x.done) {
let v = x.value;
if (p(v)) {
yield v
}
x = xs.next();
}
}
return go(xs);
};
// ge :: Ord a => a -> a -> Bool
const ge = x =>
// True if x >= y
y => x >= y;
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padStart(n, c)
) : s;
// last :: [a] -> a
const last = xs =>
// The last item of a list.
0 < xs.length ? xs.slice(-1)[0] : undefined;
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => (
Array.isArray(xs) ? (
xs
) : xs.split('')
).map(f);
// showCols :: Int -> [a] -> String
const showCols = w => xs => {
const
ys = xs.map(str),
mx = last(ys).length;
return unlines(chunksOf(w)(ys).map(
row => row.map(justifyRight(mx)(' ')).join(' ')
))
};
// str :: a -> String
const str = x =>
x.toString();
// takeWhile :: (a -> Bool) -> Gen [a] -> [a]
const takeWhile = p => xs => {
const ys = [];
let
nxt = xs.next(),
v = nxt.value;
while (!nxt.done && p(v)) {
ys.push(v);
nxt = xs.next();
v = nxt.value
}
return ys;
};
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p => f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// MAIN ---
return main();
})(); |
Averages/Mean angle | JavaScript | {{Related tasks/Statistical measures}}
| function sum(a) {
var s = 0;
for (var i = 0; i < a.length; i++) s += a[i];
return s;
}
function degToRad(a) {
return Math.PI / 180 * a;
}
function meanAngleDeg(a) {
return 180 / Math.PI * Math.atan2(
sum(a.map(degToRad).map(Math.sin)) / a.length,
sum(a.map(degToRad).map(Math.cos)) / a.length
);
}
var a = [350, 10], b = [90, 180, 270, 360], c = [10, 20, 30];
console.log(meanAngleDeg(a));
console.log(meanAngleDeg(b));
console.log(meanAngleDeg(c)); |
Averages/Pythagorean means | JavaScript | {{Related tasks/Statistical measures}}
| (function () {
'use strict';
// arithmetic_mean :: [Number] -> Number
function arithmetic_mean(ns) {
return (
ns.reduce( // sum
function (sum, n) {
return (sum + n);
},
0
) / ns.length
);
}
// geometric_mean :: [Number] -> Number
function geometric_mean(ns) {
return Math.pow(
ns.reduce( // product
function (product, n) {
return (product * n);
},
1
),
1 / ns.length
);
}
// harmonic_mean :: [Number] -> Number
function harmonic_mean(ns) {
return (
ns.length / ns.reduce( // sum of inverses
function (invSum, n) {
return (invSum + (1 / n));
},
0
)
);
}
var values = [arithmetic_mean, geometric_mean, harmonic_mean]
.map(function (f) {
return f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}),
mean = {
Arithmetic: values[0], // arithmetic
Geometric: values[1], // geometric
Harmonic: values[2] // harmonic
}
return JSON.stringify({
values: mean,
test: "is A >= G >= H ? " +
(
mean.Arithmetic >= mean.Geometric &&
mean.Geometric >= mean.Harmonic ? "yes" : "no"
)
}, null, 2);
})();
|
Babbage problem | JavaScript | Charles Babbage
Charles Babbage's analytical engine.
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
{{quote
| What is the smallest positive integer whose square ends in the digits 269,696?
| Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
}}
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
;Task
The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
;Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| // Every line starting with a double slash will be ignored by the processing machine,
// just like these two.
//
// Since the square root of 269,696 is approximately 519, we create a variable named "n"
// and give it this value.
n = 519
// The while-condition is in parentheses
// * is for multiplication
// % is for modulo operation
// != is for "not equal"
while ( ((n * n) % 1000000) != 269696 )
n = n + 1
// n is incremented until the while-condition is met, so n should finally be the
// smallest positive integer whose square ends in the digits 269,696. To see n, we
// need to send it to the monitoring device (named console).
console.log(n)
|
Balanced brackets | JavaScript | '''Task''':
* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
;Examples:
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
return a.join('')
}
function isBalanced(str) {
var a = str, b
do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
return !a
}
var M = 20
while (M-- > 0) {
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
} |
Barnsley fern | JavaScript from PARI/GP | A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
;Task:
Create this fractal fern, using the following transformations:
* f1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
* f2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = -0.04 xn + 0.85 yn + 1.6
* f3 (chosen 7% of the time)
xn + 1 = 0.2 xn - 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
* f4 (chosen 7% of the time)
xn + 1 = -0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| // Barnsley fern fractal
//6/17/16 aev
function pBarnsleyFern(canvasId, lim) {
// DCLs
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
var x = 0.,
y = 0.,
xw = 0.,
yw = 0.,
r;
// Like in PARI/GP: return random number 0..max-1
function randgp(max) {
return Math.floor(Math.random() * max)
}
// Clean canvas
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
// MAIN LOOP
for (var i = 0; i < lim; i++) {
r = randgp(100);
if (r <= 1) {
xw = 0;
yw = 0.16 * y;
} else if (r <= 8) {
xw = 0.2 * x - 0.26 * y;
yw = 0.23 * x + 0.22 * y + 1.6;
} else if (r <= 15) {
xw = -0.15 * x + 0.28 * y;
yw = 0.26 * x + 0.24 * y + 0.44;
} else {
xw = 0.85 * x + 0.04 * y;
yw = -0.04 * x + 0.85 * y + 1.6;
}
x = xw;
y = yw;
ctx.fillStyle = "green";
ctx.fillRect(x * 50 + 260, -y * 50 + 540, 1, 1);
} //fend i
} |
Base64 decode data | JavaScript | See [[Base64 encode data]].
Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| // define base64 data; in this case the data is the string: "Hello, world!"
const base64 = Buffer.from('SGVsbG8sIHdvcmxkIQ==', 'base64');
// <Buffer>.toString() is a built-in method.
console.log(base64.toString()); |
Benford's law | JavaScript | {{Wikipedia|Benford's_law}}
'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability
:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
| const fibseries = n => [...Array(n)]
.reduce(
(fib, _, i) => i < 2 ? (
fib
) : fib.concat(fib[i - 1] + fib[i - 2]),
[1, 1]
);
const benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9]
.map(val => [val, array
.reduce(
(sum, item) => sum + (
`${item}` [0] === `${val}`
),
0
) / array.length, Math.log10(1 + 1 / val)
]);
console.log(benford(fibseries(1000))) |
Best shuffle | JavaScript | Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did ''not'' change.
;Example:
tree, eetr, (0)
;Test cases:
abracadabra
seesaw
elk
grrrrrr
up
a
;Related tasks
* [[Anagrams/Deranged anagrams]]
* [[Permutations/Derangements]]
| function raze(a) { // like .join('') except producing an array instead of a string
var r= [];
for (var j= 0; j<a.length; j++)
for (var k= 0; k<a[j].length; k++) r.push(a[j][k]);
return r;
}
function shuffle(y) {
var len= y.length;
for (var j= 0; j < len; j++) {
var i= Math.floor(Math.random()*len);
var t= y[i];
y[i]= y[j];
y[j]= t;
}
return y;
}
function bestShuf(txt) {
var chs= txt.split('');
var gr= {};
var mx= 0;
for (var j= 0; j<chs.length; j++) {
var ch= chs[j];
if (null == gr[ch]) gr[ch]= [];
gr[ch].push(j);
if (mx < gr[ch].length) mx++;
}
var inds= [];
for (var ch in gr) inds.push(shuffle(gr[ch]));
var ndx= raze(inds);
var cycles= [];
for (var k= 0; k < mx; k++) cycles[k]= [];
for (var j= 0; j<chs.length; j++) cycles[j%mx].push(ndx[j]);
var ref= raze(cycles);
for (var k= 0; k < mx; k++) cycles[k].push(cycles[k].shift());
var prm= raze(cycles);
var shf= [];
for (var j= 0; j<chs.length; j++) shf[ref[j]]= chs[prm[j]];
return shf.join('');
}
function disp(ex) {
var r= bestShuf(ex);
var n= 0;
for (var j= 0; j<ex.length; j++)
n+= ex.substr(j, 1) == r.substr(j,1) ?1 :0;
return ex+', '+r+', ('+n+')';
} |
Bioinformatics/Sequence mutation | JavaScript | Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
# Choosing a random base position in the sequence.
# Mutate the sequence by doing one of either:
## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
## '''D'''elete the chosen base at the position.
## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.
# Randomly generate a test DNA sequence of at least 200 bases
# "Pretty print" the sequence and a count of its size, and the count of each base in the sequence
# Mutate the sequence ten times.
# "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
;Extra credit:
* Give more information on the individual mutations applied.
* Allow mutations to be weighted and/or chosen.
| // Basic set-up
const numBases = 250
const numMutations = 30
const bases = ['A', 'C', 'G', 'T'];
// Utility functions
/**
* Return a shallow copy of an array
* @param {Array<*>} arr
* @returns {*[]}
*/
const copy = arr => [...arr];
/**
* Get a random int up to but excluding the the given number
* @param {number} max
* @returns {number}
*/
const randTo = max => (Math.random() * max) | 0;
/**
* Given an array return a random element and the index of that element from
* the array.
* @param {Array<*>} arr
* @returns {[*[], number]}
*/
const randSelect = arr => {
const at = randTo(arr.length);
return [arr[at], at];
};
/**
* Given a number or string, return a left padded string
* @param {string|number} v
* @returns {string}
*/
const pad = v => ('' + v).padStart(4, ' ');
/**
* Count the number of elements that match the given value in an array
* @param {Array<string>} arr
* @returns {function(string): number}
*/
const filterCount = arr => s => arr.filter(e => e === s).length;
/**
* Utility logging function
* @param {string|number} v
* @param {string|number} n
*/
const print = (v, n) => console.log(`${pad(v)}:\t${n}`)
/**
* Utility function to randomly select a new base, and an index in the given
* sequence.
* @param {Array<string>} seq
* @param {Array<string>} bases
* @returns {[string, string, number]}
*/
const getVars = (seq, bases) => {
const [newBase, _] = randSelect(bases);
const [extBase, randPos] = randSelect(seq);
return [newBase, extBase, randPos];
};
// Bias the operations
/**
* Given a map of function to ratio, return an array of those functions
* appearing ratio number of times in the array.
* @param weightMap
* @returns {Array<function>}
*/
const weightedOps = weightMap => {
return [...weightMap.entries()].reduce((p, [op, weight]) =>
[...p, ...(Array(weight).fill(op))], []);
};
// Pretty Print functions
const prettyPrint = seq => {
let idx = 0;
const rem = seq.reduce((p, c) => {
const s = p + c;
if (s.length === 50) {
print(idx, s);
idx = idx + 50;
return '';
}
return s;
}, '');
if (rem !== '') {
print(idx, rem);
}
}
const printBases = seq => {
const filterSeq = filterCount(seq);
let tot = 0;
[...bases].forEach(e => {
const cnt = filterSeq(e);
print(e, cnt);
tot = tot + cnt;
})
print('Σ', tot);
}
// Mutation definitions
const swap = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 1, newBase);
return [[...hist, `Swapped ${extBase} for ${newBase} at ${randPos}`], arr];
};
const del = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 1);
return [[...hist, `Deleted ${extBase} at ${randPos}`], arr];
}
const insert = ([hist, seq]) => {
const arr = copy(seq);
const [newBase, extBase, randPos] = getVars(arr, bases);
arr.splice(randPos, 0, newBase);
return [[...hist, `Inserted ${newBase} at ${randPos}`], arr];
}
// Create the starting sequence
const seq = Array(numBases).fill(undefined).map(
() => randSelect(bases)[0]);
// Create a weighted set of mutations
const weightMap = new Map()
.set(swap, 1)
.set(del, 1)
.set(insert, 1);
const operations = weightedOps(weightMap);
const mutations = Array(numMutations).fill(undefined).map(
() => randSelect(operations)[0]);
// Mutate the sequence
const [hist, mut] = mutations.reduce((p, c) => c(p), [[], seq]);
console.log('ORIGINAL SEQUENCE:')
prettyPrint(seq);
console.log('\nBASE COUNTS:')
printBases(seq);
console.log('\nMUTATION LOG:')
hist.forEach((e, i) => console.log(`${i}:\t${e}`));
console.log('\nMUTATED SEQUENCE:')
prettyPrint(mut);
console.log('\nMUTATED BASE COUNTS:')
printBases(mut);
|
Bioinformatics/base count | JavaScript | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
;Task:
:* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence
:* print the total count of each base in the string.
| const rowLength = 50;
const bases = ['A', 'C', 'G', 'T'];
// Create the starting sequence
const seq = `CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT`
.split('')
.filter(e => bases.includes(e))
/**
* Convert the given array into an array of smaller arrays each with the length
* given by n.
* @param {number} n
* @returns {function(!Array<*>): !Array<!Array<*>>}
*/
const chunk = n => a => a.reduce(
(p, c, i) => (!(i % n)) ? p.push([c]) && p : p[p.length - 1].push(c) && p,
[]);
const toRows = chunk(rowLength);
/**
* Given a number, return function that takes a string and left pads it to n
* @param {number} n
* @returns {function(string): string}
*/
const padTo = n => v => ('' + v).padStart(n, ' ');
const pad = padTo(5);
/**
* Count the number of elements that match the given value in an array
* @param {Array<string>} arr
* @returns {function(string): number}
*/
const countIn = arr => s => arr.filter(e => e === s).length;
/**
* Utility logging function
* @param {string|number} v
* @param {string|number} n
*/
const print = (v, n) => console.log(`${pad(v)}:\t${n}`)
const prettyPrint = seq => {
const chunks = toRows(seq);
console.log('SEQUENCE:')
chunks.forEach((e, i) => print(i * rowLength, e.join('')))
}
const printBases = (seq, bases) => {
const filterSeq = countIn(seq);
const counts = bases.map(filterSeq);
console.log('\nBASE COUNTS:')
counts.forEach((e, i) => print(bases[i], e));
print('Total', counts.reduce((p,c) => p + c, 0));
}
prettyPrint(seq);
printBases(seq, bases);
|
Box the compass | JavaScript | Avast me hearties!
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
;Task description:
# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
;Notes;
* The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| (() => {
'use strict';
// GENERIC FUNCTIONS
// toTitle :: String -> String
let toTitle = s => s.length ? (s[0].toUpperCase() + s.slice(1)) : '';
// COMPASS DATA AND FUNCTIONS
// Scale invariant keys for points of the compass
// (allows us to look up a translation for one scale of compass (32 here)
// for use in another size of compass (8 or 16 points)
// (Also semi-serviceable as more or less legible keys without translation)
// compassKeys :: Int -> [String]
let compassKeys = depth => {
let urCompass = ['N', 'S', 'N'],
subdivision = (compass, n) => n <= 1 ? (
compass
) : subdivision( // Borders between N and S engender E and W.
// other new boxes concatenate their parent keys.
compass.reduce((a, x, i, xs) => {
if (i > 0) {
return (n === depth) ? (
a.concat([x === 'N' ? 'W' : 'E'], x)
) : a.concat([xs[i - 1] + x, x]);
} else return a.concat(x);
}, []),
n - 1
);
return subdivision(urCompass, depth)
.slice(0, -1);
};
// https://zh.wikipedia.org/wiki/%E7%BD%97%E7%9B%98%E6%96%B9%E4%BD%8D
let lstLangs = [{
'name': 'English',
expansions: {
N: 'north',
S: 'south',
E: 'east',
W: 'west',
b: ' by ',
'-': '-'
},
'N': 'N',
'NNNE': 'NbE',
'NNE': 'N-NE',
'NNENE': 'NEbN',
'NE': 'NE',
'NENEE': 'NEbE',
'NEE': 'E-NE',
'NEEE': 'EbN',
'E': 'E',
'EEES': 'EbS',
'EES': 'E-SE',
'EESES': 'SEbE',
'ES': 'SE',
'ESESS': 'SEbS',
'ESS': 'S-SE',
'ESSS': 'SbE',
'S': 'S',
'SSSW': 'SbW',
'SSW': 'S-SW',
'SSWSW': 'SWbS',
'SW': 'SW',
'SWSWW': 'SWbW',
'SWW': 'W-SW',
'SWWW': 'WbS',
'W': 'W',
'WWWN': 'WbN',
'WWN': 'W-NW',
'WWNWN': 'NWbW',
'WN': 'NW',
'WNWNN': 'NWbN',
'WNN': 'N-NW',
'WNNN': 'NbW'
}, {
'name': 'Chinese',
'N': '北',
'NNNE': '北微东',
'NNE': '东北偏北',
'NNENE': '东北微北',
'NE': '东北',
'NENEE': '东北微东',
'NEE': '东北偏东',
'NEEE': '东微北',
'E': '东',
'EEES': '东微南',
'EES': '东南偏东',
'EESES': '东南微东',
'ES': '东南',
'ESESS': '东南微南',
'ESS': '东南偏南',
'ESSS': '南微东',
'S': '南',
'SSSW': '南微西',
'SSW': '西南偏南',
'SSWSW': '西南微南',
'SW': '西南',
'SWSWW': '西南微西',
'SWW': '西南偏西',
'SWWW': '西微南',
'W': '西',
'WWWN': '西微北',
'WWN': '西北偏西',
'WWNWN': '西北微西',
'WN': '西北',
'WNWNN': '西北微北',
'WNN': '西北偏北',
'WNNN': '北微西'
}];
// pointIndex :: Int -> Num -> Int
let pointIndex = (power, degrees) => {
let nBoxes = (power ? Math.pow(2, power) : 32);
return Math.ceil(
(degrees + (360 / (nBoxes * 2))) % 360 * nBoxes / 360
) || 1;
};
// pointNames :: Int -> Int -> [String]
let pointNames = (precision, iBox) => {
let k = compassKeys(precision)[iBox - 1];
return lstLangs.map(dctLang => {
let s = dctLang[k] || k, // fallback to key if no translation
dctEx = dctLang.expansions;
return dctEx ? toTitle(s.split('')
.map(c => dctEx[c])
.join(precision > 5 ? ' ' : ''))
.replace(/ /g, ' ') : s;
});
};
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
let maximumBy = (f, xs) =>
xs.reduce((a, x) => a === undefined ? x : (
f(x, a) > 0 ? x : a
), undefined);
// justifyLeft :: Int -> Char -> Text -> Text
let justifyLeft = (n, cFiller, strText) =>
n > strText.length ? (
(strText + replicate(n, cFiller)
.join(''))
.substr(0, n)
) : strText;
// justifyRight :: Int -> Char -> Text -> Text
let justifyRight = (n, cFiller, strText) =>
n > strText.length ? (
(replicate(n, cFiller)
.join('') + strText)
.slice(-n)
) : strText;
// replicate :: Int -> a -> [a]
let replicate = (n, a) => {
let v = [a],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
};
// transpose :: [[a]] -> [[a]]
let transpose = xs =>
xs[0].map((_, iCol) => xs.map((row) => row[iCol]));
// length :: [a] -> Int
// length :: Text -> Int
let length = xs => xs.length;
// compareByLength = (a, a) -> (-1 | 0 | 1)
let compareByLength = (a, b) => {
let [na, nb] = [a, b].map(length);
return na < nb ? -1 : na > nb ? 1 : 0;
};
// maxLen :: [String] -> Int
let maxLen = xs => maximumBy(compareByLength, xs)
.length;
// compassTable :: Int -> [Num] -> Maybe String
let compassTable = (precision, xs) => {
if (precision < 1) return undefined;
else {
let intPad = 2;
let lstIndex = xs.map(x => pointIndex(precision, x)),
lstStrIndex = lstIndex.map(x => x.toString()),
nIndexWidth = maxLen(lstStrIndex),
colIndex = lstStrIndex.map(
x => justifyRight(nIndexWidth, ' ', x)
);
let lstAngles = xs.map(x => x.toFixed(2) + '°'),
nAngleWidth = maxLen(lstAngles) + intPad,
colAngles = lstAngles.map(x => justifyRight(nAngleWidth, ' ', x));
let lstTrans = transpose(
lstIndex.map(i => pointNames(precision, i))
),
lstTransWidths = lstTrans.map(x => maxLen(x) + 2),
colsTrans = lstTrans
.map((lstLang, i) => lstLang
.map(x => justifyLeft(lstTransWidths[i], ' ', x))
);
return transpose([colIndex]
.concat([colAngles], [replicate(lstIndex.length, " ")])
.concat(colsTrans))
.map(x => x.join(''))
.join('\n');
}
}
// TEST
let xs = [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37,
84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,
185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13,
270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37,
354.38
];
// If we supply other precisions, like 4 or 6, (2^n -> 16 or 64 boxes)
// the bearings will be divided amongst smaller or larger numbers of boxes,
// either using name translations retrieved by the generic hash
// or using the hash itself (combined with any expansions)
// to substitute for missing names for very finely divided boxes.
return compassTable(5, xs); // 2^5 -> 32 boxes
})(); |
CSV data manipulation | JavaScript | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
;Task:
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| (function () {
'use strict';
// splitRegex :: Regex -> String -> [String]
function splitRegex(rgx, s) {
return s.split(rgx);
}
// lines :: String -> [String]
function lines(s) {
return s.split(/[\r\n]/);
}
// unlines :: [String] -> String
function unlines(xs) {
return xs.join('\n');
}
// macOS JavaScript for Automation version of readFile.
// Other JS contexts will need a different definition of this function,
// and some may have no access to the local file system at all.
// readFile :: FilePath -> maybe String
function readFile(strPath) {
var error = $(),
str = ObjC.unwrap(
$.NSString.stringWithContentsOfFileEncodingError(
$(strPath)
.stringByStandardizingPath,
$.NSUTF8StringEncoding,
error
)
);
return error.code ? error.localizedDescription : str;
}
// macOS JavaScript for Automation version of writeFile.
// Other JS contexts will need a different definition of this function,
// and some may have no access to the local file system at all.
// writeFile :: FilePath -> String -> IO ()
function writeFile(strPath, strText) {
$.NSString.alloc.initWithUTF8String(strText)
.writeToFileAtomicallyEncodingError(
$(strPath)
.stringByStandardizingPath, false,
$.NSUTF8StringEncoding, null
);
}
// EXAMPLE - appending a SUM column
var delimCSV = /,\s*/g;
var strSummed = unlines(
lines(readFile('~/csvSample.txt'))
.map(function (x, i) {
var xs = x ? splitRegex(delimCSV, x) : [];
return (xs.length ? xs.concat(
// 'SUM' appended to first line, others summed.
i > 0 ? xs.reduce(
function (a, b) {
return a + parseInt(b, 10);
}, 0
).toString() : 'SUM'
) : []).join(',');
})
);
return (
writeFile('~/csvSampleSummed.txt', strSummed),
strSummed
);
})(); |
CSV to HTML translation | JavaScript | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be ''escaped'' when converted to HTML
;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!
;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via preferably; CSS if you must).
| var csv = "Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!";
var lines = csv.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.split(/[\n\r]/)
.map(function(line) { return line.split(',')})
.map(function(row) {return '\t\t<tr><td>' + row[0] + '</td><td>' + row[1] + '</td></tr>';});
console.log('<table>\n\t<thead>\n' + lines[0] +
'\n\t</thead>\n\t<tbody>\n' + lines.slice(1).join('\n') +
'\t</tbody>\n</table>');
|
Calculating the value of e | Javascript | Calculate the value of ''e''.
(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)
See details: Calculating the value of e
| (() => {
"use strict";
// - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --
// eApprox : Int -> Float
const eApprox = n =>
sum(
scanl(mul)(1)(
enumFromTo(1)(n)
)
.map(x => 1 / x)
);
// ---------------------- TEST -----------------------
const main = () =>
eApprox(20);
// ---------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// mul (*) :: Num a => a -> a -> a
const mul = a =>
// The arithmetic product of a and b.
b => a * b;
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl = f => startValue => xs =>
// The series of interim values arising
// from a catamorphism. Parallel to foldl.
xs.reduce((a, x) => {
const v = f(a[0])(x);
return [v, a[1].concat(v)];
}, [startValue, [startValue]])[1];
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// MAIN ---
return main();
})(); |
Call a function | JavaScript | Demonstrate the different syntax and semantics provided for calling a function.
This may include:
:* Calling a function that requires no arguments
:* Calling a function with a fixed number of arguments
:* Calling a function with optional arguments
:* Calling a function with a variable number of arguments
:* Calling a function with named arguments
:* Using a function in statement context
:* Using a function in first-class context within an expression
:* Obtaining the return value of a function
:* Distinguishing built-in functions and user-defined functions
:* Distinguishing subroutines and functions
;* Stating whether arguments are passed by value or by reference
;* Is partial application possible and how
This task is ''not'' about defining functions.
| var mutate = function(victim) {
victim[0] = null;
victim = 42;
};
var foo = [1, 2, 3];
mutate(foo) // foo is now [null, 2, 3], not 42 |
Canonicalize CIDR | JavaScript | Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
;Example:
Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''
;Explanation:
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.
The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.
;More examples for testing
36.18.154.103/12 - 36.16.0.0/12
62.62.197.11/29 - 62.62.197.8/29
67.137.119.181/4 - 64.0.0.0/4
161.214.74.21/24 - 161.214.74.0/24
184.232.176.184/18 - 184.232.128.0/18
| const canonicalize = s => {
// Prepare a DataView over a 16 Byte Array buffer.
// Initialised to all zeros.
const dv = new DataView(new ArrayBuffer(16));
// Get the ip-address and cidr components
const [ip, cidr] = s.split('/');
// Make sure the cidr component is a usable int, and
// default to 32 if it does not exist.
const cidrInt = parseInt(cidr || 32, 10);
// Populate the buffer with uint8 ip address components.
// Use zero as the default for shorthand pool definitions.
ip.split('.').forEach(
(e, i) => dv.setUint8(i, parseInt(e || 0, 10))
);
// Grab the whole buffer as a uint32
const ipAsInt = dv.getUint32(0);
// Zero out the lower bits as per the CIDR number.
const normIpInt = (ipAsInt >> 32 - cidrInt) << 32 - cidrInt;
// Plonk it back into the buffer
dv.setUint32(0, normIpInt);
// Read each of the uint8 slots in the buffer and join them with a dot.
const canonIp = [...'0123'].map((e, i) => dv.getUint8(i)).join('.');
// Attach the cidr number to the back of the normalised IP address.
return [canonIp, cidrInt].join('/');
}
const test = s => console.log(s, '->', canonicalize(s));
[
'255.255.255.255/10',
'87.70.141.1/22',
'36.18.154.103/12',
'62.62.197.11/29',
'67.137.119.181/4',
'161.214.74.21/24',
'184.232.176.184/18',
'10.207.219.251/32',
'10.207.219.251',
'110.200.21/4',
'10..55/8',
'10.../8'
].forEach(test) |
Cantor set | JavaScript from Python | Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| (() => {
"use strict";
// -------------- CANTOR RATIONAL PAIRS --------------
// cantor :: [(Rational, Rational)] ->
// [(Rational, Rational)]
const cantor = xs => {
const go = ab => {
const [r1, r2] = Array.from(ab).map(rational);
const third = ratioDiv(ratioMinus(r2)(r1))(3);
return [
Tuple(r1)(ratioPlus(r1)(third)),
Tuple(ratioMinus(r2)(third))(r2)
];
};
return xs.flatMap(go);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const
xs = take(4)(
iterate(cantor)([Tuple(0)(1)])
);
return [
`${unlines(xs.map(intervalRatios))}\n`,
intervalBars(xs)
]
.join("\n\n");
};
// --------------------- DISPLAY ---------------------
// intervalRatios :: [(Rational, Rational)] -> String
const intervalRatios = xs => {
const go = ab =>
Array.from(ab).map(
compose(showRatio, rational)
)
.join(", ");
return `(${xs.map(go).join(") (")})`;
};
// intervalBars :: [[(Rational, Rational)]] -> String
const intervalBars = rs => {
const go = w => xs =>
snd(mapAccumL(
a => ab => {
const [wx, wy] = Array.from(ab).map(
r => ratioMult(w)(
rational(r)
)
);
return Tuple(wy)(
replicateString(
floor(ratioMinus(wx)(a))
)(" ") + replicateString(
floor(ratioMinus(wy)(wx))
)("█")
);
}
)(0)(xs)).join("");
const d = maximum(
last(rs).map(x => fst(x).d)
);
return unlines(rs.map(
go(Ratio(d)(1))
));
};
// ---------------- GENERIC FUNCTIONS ----------------
// Ratio :: Integral a => a -> a -> Ratio a
const Ratio = a => b => {
const go = (x, y) =>
0 !== y ? (() => {
const d = gcd(x)(y);
return {
type: "Ratio",
// numerator
"n": Math.trunc(x / d),
// denominator
"d": Math.trunc(y / d)
};
})() : undefined;
return go(a * signum(b), abs(b));
};
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2
});
// abs :: Num -> Num
const abs =
// Absolute value of a given number
// without the sign.
x => 0 > x ? (
-x
) : x;
// approxRatio :: Float -> Float -> Ratio
const approxRatio = eps =>
n => {
const
gcde = (e, x, y) => {
const _gcd = (a, b) =>
b < e ? (
a
) : _gcd(b, a % b);
return _gcd(Math.abs(x), Math.abs(y));
},
c = gcde(Boolean(eps) ? (
eps
) : (1 / 10000), 1, n);
return Ratio(
Math.floor(n / c)
)(
Math.floor(1 / c)
);
};
// floor :: Num -> Int
const floor = x => {
const
nr = (
"Ratio" !== x.type ? (
properFraction
) : properFracRatio
)(x),
n = nr[0];
return 0 > nr[1] ? n - 1 : n;
};
// fst :: (a, b) -> a
const fst = ab =>
// First member of a pair.
ab[0];
// gcd :: Integral a => a -> a -> a
const gcd = x =>
y => {
const zero = x.constructor(0);
const go = (a, b) =>
zero === b ? (
a
) : go(b, a % b);
return go(abs(x), abs(y));
};
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
// An infinite list of repeated
// applications of f to x.
function* (x) {
let v = x;
while (true) {
yield v;
v = f(v);
}
};
// last :: [a] -> a
const last = xs =>
// The last item of a list.
0 < xs.length ? (
xs.slice(-1)[0]
) : null;
// lcm :: Int -> Int -> Int
const lcm = x =>
// The smallest positive integer divisible
// without remainder by both x and y.
y => (x === 0 || y === 0) ? (
0
) : Math.abs(Math.floor(x / gcd(x)(y)) * y);
// mapAccumL :: (acc -> x -> (acc, y)) ->
// acc -> [x] -> (acc, [y])
const mapAccumL = f =>
// A tuple of an accumulation and a list
// obtained by a combined map and fold,
// with accumulation from left to right.
acc => xs => [...xs].reduce(
(a, x) => {
const ab = f(a[0])(x);
return [ab[0], a[1].concat(ab[1])];
},
[acc, []]
);
// maximum :: Ord a => [a] -> a
const maximum = xs => (
// The largest value in a non-empty list.
ys => 0 < ys.length ? (
ys.slice(1).reduce(
(a, y) => y > a ? (
y
) : a, ys[0]
)
) : undefined
)(xs);
// properFracRatio :: Ratio -> (Int, Ratio)
const properFracRatio = nd => {
const [q, r] = Array.from(quotRem(nd.n)(nd.d));
return Tuple(q)(Ratio(r)(nd.d));
};
// properFraction :: Real -> (Int, Real)
const properFraction = n => {
const i = Math.floor(n) + (n < 0 ? 1 : 0);
return Tuple(i)(n - i);
};
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = m =>
// The quotient, tupled with the remainder.
n => Tuple(
Math.trunc(m / n)
)(
m % n
);
// ratioDiv :: Rational -> Rational -> Rational
const ratioDiv = n1 => n2 => {
const [r1, r2] = [n1, n2].map(rational);
return Ratio(r1.n * r2.d)(
r1.d * r2.n
);
};
// ratioMinus :: Rational -> Rational -> Rational
const ratioMinus = n1 => n2 => {
const [r1, r2] = [n1, n2].map(rational);
const d = lcm(r1.d)(r2.d);
return Ratio(
(r1.n * (d / r1.d)) - (r2.n * (d / r2.d))
)(d);
};
// ratioMult :: Rational -> Rational -> Rational
const ratioMult = n1 => n2 => {
const [r1, r2] = [n1, n2].map(rational);
return Ratio(r1.n * r2.n)(
r1.d * r2.d
);
};
// ratioPlus :: Rational -> Rational -> Rational
const ratioPlus = n1 =>
n2 => {
const [r1, r2] = [n1, n2].map(rational);
const d = lcm(r1.d)(r2.d);
return Ratio(
(r1.n * (d / r1.d)) + (
r2.n * (d / r2.d)
)
)(d);
};
// rational :: Num a => a -> Rational
const rational = x =>
isNaN(x) ? x : Number.isInteger(x) ? (
Ratio(x)(1)
) : approxRatio(undefined)(x);
// replicateString :: Int -> String -> String
const replicateString = n =>
s => s.repeat(n);
// showRatio :: Ratio -> String
const showRatio = r =>
"Ratio" !== r.type ? (
r.toString()
) : r.n.toString() + (
1 !== r.d ? (
`/${r.d}`
) : ""
);
// signum :: Num -> Num
const signum = n =>
// | Sign of a number.
n.constructor(
0 > n ? (
-1
) : (
0 < n ? 1 : 0
)
);
// snd :: (a, b) -> b
const snd = ab =>
// Second member of a pair.
ab[1];
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat(...Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join("\n");
// MAIN ---
return main();
})(); |
Cartesian product of two or more lists | JavaScript | Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
:: {1, 2} x {} = {}
:: {} x {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}
:: {1, 2, 3} x {30} x {500, 100}
:: {1, 2, 3} x {} x {500, 100}
| (() => {
// CARTESIAN PRODUCT OF TWO LISTS ---------------------
// cartProd :: [a] -> [b] -> [[a, b]]
const cartProd = xs => ys =>
xs.flatMap(x => ys.map(y => [x, y]))
// TEST -----------------------------------------------
return [
cartProd([1, 2])([3, 4]),
cartProd([3, 4])([1, 2]),
cartProd([1, 2])([]),
cartProd([])([1, 2]),
].map(JSON.stringify).join('\n');
})(); |
Casting out nines | JavaScript | Task (in three parts):
;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.
With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.
;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]
| function main(s, e, bs, pbs) {
bs = bs || 10;
pbs = pbs || 10
document.write('start:', toString(s), ' end:', toString(e),
' base:', bs, ' printBase:', pbs)
document.write('<br>castOutNine: ');
castOutNine()
document.write('<br>kaprekar: ');
kaprekar()
document.write('<br><br>')
function castOutNine() {
for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1)
if (n % bsm1 == (n * n) % bsm1) k += 1,
document.write(toString(n), ' ')
document.write('<br>trying ', k, ' numbers instead of ', n = e - s + 1,
' numbers saves ', (100 - k / n * 100)
.toFixed(3), '%')
}
function kaprekar() {
for (var n = s; n <= e; n += 1)
if (isKaprekar(n)) document.write(toString(n), ' ')
function isKaprekar(n) {
if (n < 1) return false
if (n == 1) return true
var s = (n * n)
.toString(bs)
for (var i = 1, e = s.length; i < e; i += 1) {
var a = parseInt(s.substr(0, i), bs)
var b = parseInt(s.substr(i), bs)
if (b && a + b == n) return true
}
return false
}
}
function toString(n) {
return n.toString(pbs)
.toUpperCase()
}
}
main(1, 10 * 10 - 1)
main(1, 16 * 16 - 1, 16)
main(1, 17 * 17 - 1, 17)
main(parseInt('10', 17), parseInt('gg', 17), 17, 17) |
Casting out nines | JavaScript from Haskell | Task (in three parts):
;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.
With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.
;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]
| (() => {
'use strict';
// co9 :: Int -> Int
const co9 = n =>
n <= 8 ? n : co9(
digits(10, n)
.reduce((a, x) => x !== 9 ? a + x : a, 0)
);
// GENERIC FUNCTIONS
// digits :: Int -> Int -> [Int]
const digits = (base, n) => {
if (n < base) return [n];
const [q, r] = quotRem(n, base);
return [r].concat(digits(base, q));
};
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
// range :: Int -> Int -> [Int]
const range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// squared :: Num a => a -> a
const squared = n => Math.pow(n, 2);
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
// TESTS
return show({
test1: co9(232345), //-> 1
test2: co9(34234234), //-> 7
test3: co9(232345 + 34234234) === co9(232345) + co9(34234234), //-> true
test4: co9(232345 * 34234234) === co9(232345) * co9(34234234), //-> true,
task2: range(1, 100)
.filter(n => co9(n) === co9(squared(n))),
task3: (k => range(1, 100)
.filter(n => (n % k) === (squared(n) % k)))(16)
});
})(); |
Catalan numbers/Pascal's triangle | JavaScript from C++ | Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.
;See:
* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
;Related Tasks:
[[Pascal's triangle]]
| var n = 15;
for (var t = [0, 1], i = 1; i <= n; i++) {
for (var j = i; j > 1; j--) t[j] += t[j - 1];
t[i + 1] = t[i];
for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];
document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]);
} |
Catalan numbers/Pascal's triangle | JavaScript from Haskell | Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.
;See:
* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
;Related Tasks:
[[Pascal's triangle]]
| (() => {
'use strict';
// CATALAN
// catalanSeries :: Int -> [Int]
let catalanSeries = n => {
let alternate = xs => xs.reduce(
(a, x, i) => i % 2 === 0 ? a.concat([x]) : a, []
),
diff = xs => xs.length > 1 ? xs[0] - xs[1] : xs[0];
return alternate(pascal(n * 2))
.map((xs, i) => diff(drop(i, xs)));
}
// PASCAL
// pascal :: Int -> [[Int]]
let pascal = n => until(
m => m.level <= 1,
m => {
let nxt = zipWith(
(a, b) => a + b, [0].concat(m.row), m.row.concat(0)
);
return {
row: nxt,
triangle: m.triangle.concat([nxt]),
level: m.level - 1
}
}, {
level: n,
row: [1],
triangle: [
[1]
]
}
)
.triangle;
// GENERIC FUNCTIONS
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
let zipWith = (f, xs, ys) =>
xs.length === ys.length ? (
xs.map((x, i) => f(x, ys[i]))
) : undefined;
// until :: (a -> Bool) -> (a -> a) -> a -> a
let until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
}
// drop :: Int -> [a] -> [a]
let drop = (n, xs) => xs.slice(n);
// tail :: [a] -> [a]
let tail = xs => xs.length ? xs.slice(1) : undefined;
return tail(catalanSeries(16));
})(); |
Catamorphism | JavaScript | ''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
;Task:
Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.
;See also:
* Wikipedia article: Fold
* Wikipedia article: Catamorphism
| (function (xs) {
'use strict';
// foldl :: (b -> a -> b) -> b -> [a] -> b
function foldl(f, acc, xs) {
return xs.reduce(f, acc);
}
// foldr :: (b -> a -> b) -> b -> [a] -> b
function foldr(f, acc, xs) {
return xs.reduceRight(f, acc);
}
// Test folds in both directions
return [foldl, foldr].map(function (f) {
return f(function (acc, x) {
return acc + (x * 2).toString() + ' ';
}, [], xs);
});
})([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); |
Chaocipher | JavaScript from C | Description:
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
;Task:
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| const L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ENCRYPT = 0;
const DECRYPT = 1;
function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function chao(text, mode, show_steps) {
var left = L_ALPHABET;
var right = R_ALPHABET;
var out = text;
var temp = "01234567890123456789012345";
var i = 0;
var index, j, store;
if (show_steps) {
console.log("The left and right alphabets after each permutation during encryption are :");
}
while (i < text.length) {
if (show_steps) {
console.log(left + " " + right);
}
if (mode == ENCRYPT) {
index = right.indexOf(text[i]);
out = setCharAt(out, i, left[index]);
} else {
index = left.indexOf(text[i]);
out = setCharAt(out, i, right[index]);
}
if (i == text.length - 1) {
break;
}
//permute left
j = index;
while (j < 26) {
temp = setCharAt(temp, j - index, left[j])
j += 1;
}
j = 0;
while (j < index) {
temp = setCharAt(temp, 26 - index + j, left[j]);
j += 1;
}
store = temp[1];
j = 2;
while (j < 14) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 13, store);
left = temp;
//permute right
j = index;
while (j < 26) {
temp = setCharAt(temp, j - index, right[j]);
j += 1;
}
j = 0;
while (j < index) {
temp = setCharAt(temp, 26 - index + j, right[j]);
j += 1;
}
store = temp[0];
j = 1;
while (j < 26) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 25, store);
store = temp[2];
j = 3;
while (j < 14) {
temp = setCharAt(temp, j - 1, temp[j]);
j += 1;
}
temp = setCharAt(temp, 13, store);
right = temp;
i += 1;
}
return out;
}
function main() {
var out = document.getElementById("content");
const plain_text = "WELLDONEISBETTERTHANWELLSAID";
out.innerHTML = "<p>The original plaintext is : " + plain_text + "</p>";
var cipher_text = chao(plain_text, ENCRYPT, true);
out.innerHTML += "<p>The ciphertext is : " + cipher_text + "</p>";
var decipher_text = chao(cipher_text, DECRYPT, false);
out.innerHTML += "<p>The recovered plaintext is : " + decipher_text + "</p>";
} |
Chaos game | JavaScript | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
;Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
;See also
* The Game of Chaos
| <html>
<head>
<meta charset="UTF-8">
<title>Chaos Game</title>
</head>
<body>
<p>
<canvas id="sierpinski" width=400 height=346></canvas>
</p>
<p>
<button onclick="chaosGame()">Click here to see a Sierpiński triangle</button>
</p>
<script>
function chaosGame() {
var canv = document.getElementById('sierpinski').getContext('2d');
var x = Math.random() * 400;
var y = Math.random() * 346;
for (var i=0; i<30000; i++) {
var vertex = Math.floor(Math.random() * 3);
switch(vertex) {
case 0:
x = x / 2;
y = y / 2;
canv.fillStyle = 'green';
break;
case 1:
x = 200 + (200 - x) / 2
y = 346 - (346 - y) / 2
canv.fillStyle = 'red';
break;
case 2:
x = 400 - (400 - x) / 2
y = y / 2;
canv.fillStyle = 'blue';
}
canv.fillRect(x,y, 1,1);
}
}
</script>
</body>
</html> |
Cheryl's birthday | JavaScript | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
;Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
;Related task:
* [[Sum and Product Puzzle]]
;References
* Wikipedia article of the same name.
* Tuple Relational Calculus
| (() => {
'use strict';
// main :: IO ()
const main = () => {
const
month = fst,
day = snd;
showLog(
map(x => Array.from(x), (
// The month with only one remaining day,
// (A's month contains only one remaining day)
// (3 :: A "Then I also know")
uniquePairing(month)(
// among the days with unique months,
// (B's day is paired with only one remaining month)
// (2 :: B "I know now")
uniquePairing(day)(
// excluding months with unique days,
// (A's month is not among those with unique days)
// (1 :: A "I know that Bernard does not know")
monthsWithUniqueDays(false)(
// from the given month-day pairs:
// (0 :: Cheryl's list)
map(x => tupleFromList(words(strip(x))),
splitOn(/,\s+/,
`May 15, May 16, May 19,
June 17, June 18, July 14, July 16,
Aug 14, Aug 15, Aug 17`
)
)
)
)
)
))
);
};
// monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]
const monthsWithUniqueDays = blnInclude => xs => {
const months = map(fst, uniquePairing(snd)(xs));
return filter(
md => (blnInclude ? id : not)(
elem(fst(md), months)
),
xs
);
};
// uniquePairing :: ((a, a) -> a) ->
// -> [(Month, Day)] -> [(Month, Day)]
const uniquePairing = f => xs =>
bindPairs(xs,
md => {
const
dct = f(md),
matches = filter(
k => 1 === length(dct[k]),
Object.keys(dct)
);
return filter(tpl => elem(f(tpl), matches), xs);
}
);
// bindPairs :: [(Month, Day)] -> (Dict, Dict) -> [(Month, Day)]
const bindPairs = (xs, f) => f(
Tuple(
dictFromPairs(fst)(snd)(xs),
dictFromPairs(snd)(fst)(xs)
)
);
// dictFromPairs :: ((a, a) -> a) -> ((a, a) -> a) -> [(a, a)] -> Dict
const dictFromPairs = f => g => xs =>
foldl((a, tpl) => Object.assign(
a, {
[f(tpl)]: (a[f(tpl)] || []).concat(g(tpl).toString())
}
), {}, xs);
// GENERIC ABSTRACTIONS -------------------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// elem :: Eq a => a -> [a] -> Bool
const elem = (x, xs) => xs.includes(x);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
// foldl :: (a -> b -> a) -> a -> [b] -> a
const foldl = (f, a, xs) => xs.reduce(f, a);
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// id :: a -> a
const id = x => x;
// intersect :: (Eq a) => [a] -> [a] -> [a]
const intersect = (xs, ys) =>
xs.filter(x => -1 !== ys.indexOf(x));
// Returns Infinity over objects without finite length
// this enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// not :: Bool -> Bool
const not = b => !b;
// showLog :: a -> IO ()
const showLog = (...args) =>
console.log(
args
.map(JSON.stringify)
.join(' -> ')
);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// splitOn :: String -> String -> [String]
const splitOn = (pat, src) =>
src.split(pat);
// strip :: String -> String
const strip = s => s.trim();
// tupleFromList :: [a] -> (a, a ...)
const tupleFromList = xs =>
TupleN.apply(null, xs);
// TupleN :: a -> b ... -> (a, b ... )
function TupleN() {
const
args = Array.from(arguments),
lng = args.length;
return lng > 1 ? Object.assign(
args.reduce((a, x, i) => Object.assign(a, {
[i]: x
}), {
type: 'Tuple' + (2 < lng ? lng.toString() : ''),
length: lng
})
) : args[0];
};
// words :: String -> [String]
const words = s => s.split(/\s+/);
// MAIN ---
return main();
})(); |
Chinese remainder theorem | JavaScript | Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime.
Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences:
::: \begin{align}
x &\equiv a_1 \pmod{n_1} \\
x &\equiv a_2 \pmod{n_2} \\
&{}\ \ \vdots \\
x &\equiv a_k \pmod{n_k}
\end{align}
Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k.
;Task:
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k.
''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].
'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k
Again, to begin, the product N = n_1n_2 \ldots n_k is defined.
Then a solution x can be found as follows:
For each i, the integers n_i and N/n_i are co-prime.
Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1.
Then, one solution to the system of simultaneous congruences is:
::: x = \sum_{i=1}^k a_i s_i N/n_i
and the minimal solution,
::: x \pmod{N}.
| function crt(num, rem) {
let sum = 0;
const prod = num.reduce((a, c) => a * c, 1);
for (let i = 0; i < num.length; i++) {
const [ni, ri] = [num[i], rem[i]];
const p = Math.floor(prod / ni);
sum += ri * p * mulInv(p, ni);
}
return sum % prod;
}
function mulInv(a, b) {
const b0 = b;
let [x0, x1] = [0, 1];
if (b === 1) {
return 1;
}
while (a > 1) {
const q = Math.floor(a / b);
[a, b] = [b, a % b];
[x0, x1] = [x1 - q * x0, x0];
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
console.log(crt([3,5,7], [2,3,2])) |
Chinese zodiac | JavaScript from Haskell | Determine the Chinese zodiac sign and related associations for a given year.
Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.
Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.
Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.
The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.
Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.
;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
;Requisite information:
* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
* Each element gets two consecutive years; a yang followed by a yin.
* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.
Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle.
;Information for optional task:
* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
| (() => {
"use strict";
// ---------- TRADITIONAL CALENDAR STRINGS -----------
// ats :: Array Int (String, String)
const ats = () =>
// 天干 tiangan – 10 heavenly stems
zip(
chars("甲乙丙丁戊己庚辛壬癸")
)(
words("jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi")
);
// ads :: Array Int (String, String)
const ads = () =>
// 地支 dizhi – 12 terrestrial branches
zip(
chars("子丑寅卯辰巳午未申酉戌亥")
)(
words(
"zĭ chŏu yín măo chén sì " + (
"wŭ wèi shēn yŏu xū hài"
)
)
);
// aws :: Array Int (String, String, String)
const aws = () =>
// 五行 wuxing – 5 elements
zip3(
chars("木火土金水")
)(
words("mù huǒ tǔ jīn shuǐ")
)(
words("wood fire earth metal water")
);
// axs :: Array Int (String, String, String)
const axs = () =>
// 十二生肖 shengxiao – 12 symbolic animals
zip3(
chars("鼠牛虎兔龍蛇馬羊猴鸡狗豬")
)(
words(
"shǔ niú hǔ tù lóng shé " + (
"mǎ yáng hóu jī gǒu zhū"
)
)
)(
words(
"rat ox tiger rabbit dragon snake " + (
"horse goat monkey rooster dog pig"
)
)
);
// ays :: Array Int (String, String)
const ays = () =>
// 阴阳 yinyang
zip(
chars("阳阴")
)(
words("yáng yīn")
);
// --------------- TRADITIONAL CYCLES ----------------
const zodiac = y => {
const
iYear = y - 4,
iStem = iYear % 10,
iBranch = iYear % 12,
[hStem, pStem] = ats()[iStem],
[hBranch, pBranch] = ads()[iBranch],
[hElem, pElem, eElem] = aws()[quot(iStem)(2)],
[hAnimal, pAnimal, eAnimal] = axs()[iBranch],
[hYinyang, pYinyang] = ays()[iYear % 2];
return [
[
show(y), hStem + hBranch, hElem,
hAnimal, hYinyang
],
["", pStem + pBranch, pElem, pAnimal, pYinyang],
[
"", `${show((iYear % 60) + 1)}/60`,
eElem, eAnimal, ""
]
];
};
// ---------------------- TEST -----------------------
const main = () => [
1935, 1938, 1968, 1972, 1976, 1984,
new Date().getFullYear()
]
.map(showYear)
.join("\n\n");
// ------------------- FORMATTING --------------------
// fieldWidths :: [[Int]]
const fieldWidths = [
[6, 10, 7, 8, 3],
[6, 11, 8, 8, 4],
[6, 11, 8, 8, 4]
];
// showYear :: Int -> String
const showYear = y =>
zipWith(zip)(fieldWidths)(zodiac(y))
.map(
row => row.map(
([n, s]) => s.padEnd(n, " ")
)
.join("")
)
.join("\n");
// ---------------- GENERIC FUNCTIONS ----------------
// chars :: String -> [Char]
const chars = s => [...s];
// quot :: Integral a => a -> a -> a
const quot = n =>
m => Math.trunc(n / m);
// show :: Int -> a -> Indented String
// show :: a -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [
x[1], null, x[0]
] : x
);
// words :: String -> [String]
const words = s =>
// List of space-delimited sub-strings.
s.split(/\s+/u);
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs =>
// The paired members of xs and ys, up to
// the length of the shorter of the two lists.
ys => Array.from({
length: Math.min(xs.length, ys.length)
}, (_, i) => [xs[i], ys[i]]);
// zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
const zip3 = xs =>
ys => zs => xs.slice(
0,
Math.min(...[xs, ys, zs].map(x => x.length))
)
.map((x, i) => [x, ys[i], zs[i]]);
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.map(
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
// MAIN ---
return main();
})(); |
Church numerals | Javascript | In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''
* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''
* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
* Church Zero,
* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
* functions for Addition, Multiplication and Exponentiation over Church numerals,
* a function to convert integers to corresponding Church numerals,
* and a function to convert Church numerals to corresponding integers.
You should:
* Derive Church numerals three and four in terms of Church zero and a Church successor function.
* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
* convert each result back to an integer, and return it or print it to the console.
| (() => {
'use strict';
// ----------------- CHURCH NUMERALS -----------------
const churchZero = f =>
identity;
const churchSucc = n =>
f => compose(f)(n(f));
const churchAdd = m =>
n => f => compose(n(f))(m(f));
const churchMult = m =>
n => f => n(m(f));
const churchExp = m =>
n => n(m);
const intFromChurch = n =>
n(succ)(0);
const churchFromInt = n =>
compose(
foldl(compose)(identity)
)(
replicate(n)
);
// Or, by explicit recursion:
const churchFromInt_ = x => {
const go = i =>
0 === i ? (
churchZero
) : churchSucc(go(pred(i)));
return go(x);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const [cThree, cFour] = map(churchFromInt)([3, 4]);
return map(intFromChurch)([
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
]);
};
// --------------------- GENERIC ---------------------
// compose (>>>) :: (a -> b) -> (b -> c) -> a -> c
const compose = f =>
g => x => f(g(x));
// foldl :: (a -> b -> a) -> a -> [b] -> a
const foldl = f =>
a => xs => [...xs].reduce(
(x, y) => f(x)(y),
a
);
// identity :: a -> a
const identity = x => x;
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => [...xs].map(f);
// pred :: Enum a => a -> a
const pred = x =>
x - 1;
// replicate :: Int -> a -> [a]
const replicate = n =>
// n instances of x.
x => Array.from({
length: n
}, () => x);
// succ :: Enum a => a -> a
const succ = x =>
1 + x;
// MAIN ---
console.log(JSON.stringify(main()));
})(); |
Circles of given radius through two points | JavaScript | 2 circles with a given radius through 2 points in 2D space.
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
;Exceptions:
# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.
# If the points are too far apart then no circles can be drawn.
;Task detail:
* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.
* Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
;Related task:
* [[Total circles area]].
;See also:
* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));
const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]];
const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2);
const findC = (...args) => {
const [p1, p2, s] = args;
const solve = solveF(p1, s);
const halfDist = hDist(p1, p2);
let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `;
switch (Math.sign(s - halfDist)) {
case 0:
msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` :
'Radius Zero';
break;
case 1:
if (!halfDist) {
msg += 'Coincident point. Infinite solutions';
}
else {
let theta = pAng(p1, p2);
let theta2 = Math.acos(halfDist / s);
[1, -1].map(e => solve(theta + e * theta2)).forEach(
e => msg += `Circle at ${e} `);
}
break;
case -1:
msg += 'No intersection. Points further apart than circle diameter';
break;
}
return msg;
};
[
[[0.1234, 0.9876], [0.8765, 0.2345], 2.0],
[[0.0000, 2.0000], [0.0000, 0.0000], 1.0],
[[0.1234, 0.9876], [0.1234, 0.9876], 2.0],
[[0.1234, 0.9876], [0.8765, 0.2345], 0.5],
[[0.1234, 0.9876], [0.1234, 0.9876], 0.0]
].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`));
|
Cistercian numerals | JavaScript | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.
;How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
:* The '''upper-right''' quadrant represents the '''ones''' place.
:* The '''upper-left''' quadrant represents the '''tens''' place.
:* The '''lower-right''' quadrant represents the '''hundreds''' place.
:* The '''lower-left''' quadrant represents the '''thousands''' place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]
;Task
:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
:* Use the routine to show the following Cistercian numerals:
::* 0
::* 1
::* 20
::* 300
::* 4000
::* 5555
::* 6789
::* And a number of your choice!
;Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.
;See also
:* '''Numberphile - The Forgotten Number System'''
:* '''dcode.fr - Online Cistercian numeral converter'''
| // html
document.write(`
<p><input id="num" type="number" min="0" max="9999" value="0" onchange="showCist()"></p>
<p><canvas id="cist" width="200" height="300"></canvas></p>
<p> <!-- EXAMPLES (can be deleted for normal use) -->
<button onclick="set(0)">0</button>
<button onclick="set(1)">1</button>
<button onclick="set(20)">20</button>
<button onclick="set(300)">300</button>
<button onclick="set(4000)">4000</button>
<button onclick="set(5555)">5555</button>
<button onclick="set(6789)">6789</button>
<button onclick="set(Math.floor(Math.random()*1e4))">Random</button>
</p>
`);
// to show given examples
// can be deleted for normal use
function set(num) {
document.getElementById('num').value = num;
showCist();
}
const SW = 10; // stroke width
let canvas = document.getElementById('cist'),
cx = canvas.getContext('2d');
function showCist() {
// reset canvas
cx.clearRect(0, 0, canvas.width, canvas.height);
cx.lineWidth = SW;
cx.beginPath();
cx.moveTo(100, 0+.5*SW);
cx.lineTo(100, 300-.5*SW);
cx.stroke();
let num = document.getElementById('num').value;
while (num.length < 4) num = '0' + num; // fills leading zeros to $num
/***********************\
| POINTS: |
| ********************* |
| |
| a --- b --- c |
| | | | |
| d --- e --- f |
| | | | |
| g --- h --- i |
| | | | |
| j --- k --- l |
| |
\***********************/
let
a = [0+SW, 0+SW], b = [100, 0+SW], c = [200-SW, 0+SW],
d = [0+SW, 100], e = [100, 100], f = [200-SW, 100],
g = [0+SW, 200], h = [100, 200], i = [200-SW, 200],
j = [0+SW, 300-SW], k = [100, 300-SW], l = [200-SW, 300-SW];
function draw() {
let x = 1;
cx.beginPath();
cx.moveTo(arguments[0][0], arguments[0][1]);
while (x < arguments.length) {
cx.lineTo(arguments[x][0], arguments[x][1]);
x++;
}
cx.stroke();
}
// 1000s
switch (num[0]) {
case '1': draw(j, k); break; case '2': draw(g, h); break;
case '3': draw(g, k); break; case '4': draw(j, h); break;
case '5': draw(k, j, h); break; case '6': draw(g, j); break;
case '7': draw(g, j, k); break; case '8': draw(j, g, h); break;
case '9': draw(h, g, j, k); break;
}
// 100s
switch (num[1]) {
case '1': draw(k, l); break; case '2': draw(h, i); break;
case '3': draw(k, i); break; case '4': draw(h, l); break;
case '5': draw(h, l, k); break; case '6': draw(i, l); break;
case '7': draw(k, l, i); break; case '8': draw(h, i, l); break;
case '9': draw(h, i, l, k); break;
}
// 10s
switch (num[2]) {
case '1': draw(a, b); break; case '2': draw(d, e); break;
case '3': draw(d, b); break; case '4': draw(a, e); break;
case '5': draw(b, a, e); break; case '6': draw(a, d); break;
case '7': draw(d, a, b); break; case '8': draw(a, d, e); break;
case '9': draw(b, a, d, e); break;
}
// 1s
switch (num[3]) {
case '1': draw(b, c); break; case '2': draw(e, f); break;
case '3': draw(b, f); break; case '4': draw(e, c); break;
case '5': draw(b, c, e); break; case '6': draw(c, f); break;
case '7': draw(b, c, f); break; case '8': draw(e, f, c); break;
case '9': draw(b, c, f, e); break;
}
}
|
Closures/Value capture | JavaScript | Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: [[Multiple distinct objects]]
| var funcs = [];
for (var i = 0; i < 10; i++) {
funcs.push( (function(i) {
return function() { return i * i; }
})(i) );
}
window.alert(funcs[3]()); // alerts "9" |
Closures/Value capture | JavaScript 1.7+ | Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: [[Multiple distinct objects]]
| <script type="application/javascript;version=1.7">
var funcs = [];
for (var i = 0; i < 10; i++) {
let (i = i) {
funcs.push( function() { return i * i; } );
}
}
window.alert(funcs[3]()); // alerts "9"
</script> |
Closures/Value capture | JavaScript ES5 | Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: [[Multiple distinct objects]]
| (function () {
'use strict';
// Int -> Int -> [Int]
function range(m, n) {
return Array.apply(null, Array(n - m + 1))
.map(function (x, i) {
return m + i;
});
}
var lstFns = range(0, 10)
.map(function (i) {
return function () {
return i * i;
};
})
return lstFns[3]();
})(); |
Comma quibbling | JavaScript | Comma quibbling is a task originally set by Eric Lippert in his blog.
;Task:
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
# An input of no words produces the output string of just the two brace characters "{}".
# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
* [] # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| function quibble(words) {
return "{" +
words.slice(0, words.length-1).join(",") +
(words.length > 1 ? " and " : "") +
(words[words.length-1] || '') +
"}";
}
[[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]].forEach(
function(s) {
console.log(quibble(s));
}
); |
Comma quibbling | JavaScript from Haskell | Comma quibbling is a task originally set by Eric Lippert in his blog.
;Task:
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
# An input of no words produces the output string of just the two brace characters "{}".
# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
* [] # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| (() => {
'use strict';
// ----------------- COMMA QUIBBLING -----------------
// quibble :: [String] -> String
const quibble = xs =>
1 < xs.length ? (
intercalate(' and ')(
ap([
compose(
intercalate(', '),
reverse,
tail
),
head
])([reverse(xs)])
)
) : concat(xs);
// ---------------------- TEST -----------------------
const main = () =>
unlines(
map(compose(x => '{' + x + '}', quibble))(
append([
[],
["ABC"],
["ABC", "DEF"],
["ABC", "DEF", "G", "H"]
])(
map(words)([
"One two three four",
"Me myself I",
"Jack Jill",
"Loner"
])
)
));
// ---------------- GENERIC FUNCTIONS ----------------
// ap (<*>) :: [(a -> b)] -> [a] -> [b]
const ap = fs =>
// The sequential application of each of a list
// of functions to each of a list of values.
// apList([x => 2 * x, x => 20 + x])([1, 2, 3])
// -> [2, 4, 6, 21, 22, 23]
xs => fs.flatMap(f => xs.map(f));
// append (++) :: [a] -> [a] -> [a]
const append = xs =>
// A list defined by the
// concatenation of two others.
ys => xs.concat(ys);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs => (
ys => 0 < ys.length ? (
ys.every(Array.isArray) ? (
[]
) : ''
).concat(...ys) : ys
)(xs);
// head :: [a] -> a
const head = xs => (
ys => ys.length ? (
ys[0]
) : undefined
)(list(xs));
// intercalate :: String -> [String] -> String
const intercalate = s =>
// The concatenation of xs
// interspersed with copies of s.
xs => xs.join(s);
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => [...xs].map(f);
// reverse :: [a] -> [a]
const reverse = xs =>
'string' !== typeof xs ? (
xs.slice(0).reverse()
) : xs.split('').reverse().join('');
// tail :: [a] -> [a]
const tail = xs =>
// A new list consisting of all
// items of xs except the first.
xs.slice(1);
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// words :: String -> [String]
const words = s =>
// List of space-delimited sub-strings.
s.split(/\s+/);
// MAIN ---
return main();
})(); |
Compare a list of strings | JavaScript | Given a list of arbitrarily many strings, show how to:
* test if they are all lexically '''equal'''
* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is ''no'' need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
| (() => {
'use strict';
// allEqual :: [String] -> Bool
let allEqual = xs => and(zipWith(equal, xs, xs.slice(1))),
// azSorted :: [String] -> Bool
azSorted = xs => and(zipWith(azBefore, xs, xs.slice(1))),
// equal :: a -> a -> Bool
equal = (a, b) => a === b,
// azBefore :: String -> String -> Bool
azBefore = (a, b) => a.toLowerCase() <= b.toLowerCase();
// GENERIC
// and :: [Bool] -> Bool
let and = xs => xs.reduceRight((a, x) => a && x, true),
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith = (f, xs, ys) => {
let ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map((x, i) => f(x, ys[i]));
};
// TEST
let lists = [
['isiZulu', 'isiXhosa', 'isiNdebele', 'Xitsonga',
'Tshivenda', 'Setswana', 'Sesotho sa Leboa', 'Sesotho',
'English', 'Afrikaans'
],
['Afrikaans', 'English', 'isiNdebele', 'isiXhosa',
'isiZulu', 'Sesotho', 'Sesotho sa Leboa', 'Setswana',
'Tshivenda', 'Xitsonga',
],
['alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha',
'alpha', 'alpha', 'alpha', 'alpha', 'alpha', 'alpha'
]
];
return {
allEqual: lists.map(allEqual),
azSorted: lists.map(azSorted)
};
})(); |
Convert decimal number to rational | JavaScript | The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...
Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518) = 0.518518...
Acceptable output:
* 0.9054054 - 4527027 / 5000000
* 0.518518 - 259259 / 500000
Finite decimals are of course no problem:
* 0.75 - 3 / 4
| (() => {
'use strict';
const main = () =>
showJSON(
map( // Using a tolerance epsilon of 1/10000
n => showRatio(approxRatio(0.0001)(n)),
[0.9054054, 0.518518, 0.75]
)
);
// Epsilon -> Real -> Ratio
// approxRatio :: Real -> Real -> Ratio
const approxRatio = eps => n => {
const
gcde = (e, x, y) => {
const _gcd = (a, b) => (b < e ? a : _gcd(b, a % b));
return _gcd(Math.abs(x), Math.abs(y));
},
c = gcde(Boolean(eps) ? eps : (1 / 10000), 1, n);
return Ratio(
Math.floor(n / c), // numerator
Math.floor(1 / c) // denominator
);
};
// GENERIC FUNCTIONS ----------------------------------
// Ratio :: Int -> Int -> Ratio
const Ratio = (n, d) => ({
type: 'Ratio',
'n': n, // numerator
'd': d // denominator
});
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// showJSON :: a -> String
const showJSON = x => JSON.stringify(x, null, 2);
// showRatio :: Ratio -> String
const showRatio = nd =>
nd.n.toString() + '/' + nd.d.toString();
// MAIN ---
return main();
})(); |
Convert seconds to compound duration | JavaScript | Write a function or program which:
* takes a positive integer representing a duration in seconds as input (e.g., 100), and
* returns a string which shows the same duration decomposed into:
:::* weeks,
:::* days,
:::* hours,
:::* minutes, and
:::* seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
'''''Test Cases'''''
:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}
'''''Details'''''
The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}
However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| (function () {
'use strict';
// angloDuration :: Int -> String
function angloDuration(intSeconds) {
return zip(
weekParts(intSeconds),
['wk', 'd', 'hr', 'min','sec']
)
.reduce(function (a, x) {
return a.concat(x[0] ? (
[(x[0].toString() + ' ' + x[1])]
) : []);
}, [])
.join(', ');
}
// weekParts :: Int -> [Int]
function weekParts(intSeconds) {
return [undefined, 7, 24, 60, 60]
.reduceRight(function (a, x) {
var intRest = a.remaining,
intMod = isNaN(x) ? intRest : intRest % x;
return {
remaining:(intRest - intMod) / (x || 1),
parts: [intMod].concat(a.parts)
};
}, {
remaining: intSeconds,
parts: []
})
.parts
}
// GENERIC ZIP
// zip :: [a] -> [b] -> [(a,b)]
function zip(xs, ys) {
return xs.length === ys.length ? (
xs.map(function (x, i) {
return [x, ys[i]];
})
) : undefined;
}
// TEST
return [7259, 86400, 6000000]
.map(function (intSeconds) {
return intSeconds.toString() +
' -> ' + angloDuration(intSeconds);
})
.join('\n');
})();
|
Count the coins | JavaScript | There are four types of common coins in US currency:
:::# quarters (25 cents)
:::# dimes (10 cents)
:::# nickels (5 cents), and
:::# pennies (1 cent)
There are six ways to make change for 15 cents:
:::# A dime and a nickel
:::# A dime and 5 pennies
:::# 3 nickels
:::# 2 nickels and 5 pennies
:::# A nickel and 10 pennies
:::# 15 pennies
;Task:
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
;Optional:
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.
| function countcoins(t, o) {
'use strict';
var targetsLength = t + 1;
var operandsLength = o.length;
t = [1];
for (var a = 0; a < operandsLength; a++) {
for (var b = 1; b < targetsLength; b++) {
// initialise undefined target
t[b] = t[b] ? t[b] : 0;
// accumulate target + operand ways
t[b] += (b < o[a]) ? 0 : t[b - o[a]];
}
}
return t[targetsLength - 1];
} |
Count the coins | JavaScript from C# | There are four types of common coins in US currency:
:::# quarters (25 cents)
:::# dimes (10 cents)
:::# nickels (5 cents), and
:::# pennies (1 cent)
There are six ways to make change for 15 cents:
:::# A dime and a nickel
:::# A dime and 5 pennies
:::# 3 nickels
:::# 2 nickels and 5 pennies
:::# A nickel and 10 pennies
:::# 15 pennies
;Task:
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
;Optional:
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.
| var amount = 100,
coin = [1, 5, 10, 25]
var t = [1];
for (t[amount] = 0, a = 1; a < amount; a++) t[a] = 0 // initialise t[0..amount]=[1,0,...,0]
for (var i = 0, e = coin.length; i < e; i++)
for (var ci = coin[i], a = ci; a <= amount; a++)
t[a] += t[a - ci]
document.write(t[amount]) |
Create an HTML table | JavaScript | Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.
| (() => {
'use strict';
// HTML ---------------------------------------------
// treeHTML :: tree
// {tag :: String, text :: String, kvs :: Dict}
// -> String
const treeHTML = tree =>
foldTree(
(x, xs) => `<${x.tag + attribString(x.kvs)}>` + (
'text' in x ? (
x.text
) : '\n'
) + concat(xs) + `</${x.tag}>\n`)(
tree
);
// attribString :: Dict -> String
const attribString = dct =>
dct ? (
' ' + Object.keys(dct)
.reduce(
(a, k) => a + k + '="' + dct[k] + '" ', ''
).trim()
) : '';
// TEST ---------------------------------------------
const main = () => {
const
tableStyle = {
style: "width:25%; border:2px solid silver;"
},
trStyle = {
style: "border:1px solid silver;text-align:right;"
},
strCaption = 'Table generated by JS';
const
n = 3,
colNames = take(n)(enumFrom('A')),
dataRows = map(
x => Tuple(x)(map(randomRInt(100)(9999))(
colNames
)))(take(n)(enumFrom(1)));
const
// TABLE AS TREE STRUCTURE -----------------
tableTree = Node({
tag: 'table',
kvs: tableStyle
},
append([
Node({
tag: 'caption',
text: 'Table source generated by JS'
}),
// HEADER ROW -----------------------
Node({
tag: 'tr',
},
map(k => Node({
tag: 'th',
kvs: {
style: "text-align:right;"
},
text: k
}))(cons('')(colNames))
)
// DATA ROWS ------------------------
])(map(tpl => Node({
tag: 'tr',
kvs: trStyle
}, cons(
Node({
tag: 'th',
text: fst(tpl)
}))(
map(v => Node({
tag: 'td',
text: v.toString()
}))(snd(tpl))
)))(dataRows))
);
// Return a value and/or apply console.log to it.
// (JS embeddings vary in their IO channels)
const strHTML = treeHTML(tableTree);
return (
console.log(strHTML)
//strHTML
);
};
// GENERIC FUNCTIONS --------------------------------
// Node :: a -> [Tree a] -> Tree a
const Node = (v, xs) => ({
type: 'Node',
root: v,
nest: xs || []
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = xs => ys => xs.concat(ys);
// chr :: Int -> Char
const chr = String.fromCodePoint;
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// cons :: a -> [a] -> [a]
const cons = x => xs => [x].concat(xs);
// enumFrom :: a -> [a]
function* enumFrom(x) {
let v = x;
while (true) {
yield v;
v = succ(v);
}
}
// enumFromToChar :: Char -> Char -> [Char]
const enumFromToChar = m => n => {
const [intM, intN] = [m, n].map(
x => x.charCodeAt(0)
);
return Array.from({
length: Math.floor(intN - intM) + 1
}, (_, i) => String.fromCodePoint(intM + i));
};
// foldTree :: (a -> [b] -> b) -> Tree a -> b
const foldTree = f => tree => {
const go = node =>
f(node.root, node.nest.map(go));
return go(tree);
};
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// isChar :: a -> Bool
const isChar = x =>
('string' === typeof x) && (1 === x.length);
// map :: (a -> b) -> [a] -> [b]
const map = f => xs =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// ord :: Char -> Int
const ord = c => c.codePointAt(0);
// randomRInt :: Int -> Int -> () -> Int
const randomRInt = low => high => () =>
low + Math.floor(
(Math.random() * ((high - low) + 1))
);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// succ :: Enum a => a -> a
const succ = x =>
isChar(x) ? (
chr(1 + ord(x))
) : isNaN(x) ? (
undefined
) : 1 + x;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => xs =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// MAIN ---
return main();
})(); |
Currency | JavaScript | Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
;Note:
The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16
Dollar signs and thousands separators are optional.
| const money = require('money-math')
let hamburgers = 4000000000000000
let hamburgerPrice = 5.50
let shakes = 2
let shakePrice = 2.86
let tax = 7.65
let hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice))
let shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice))
let subTotal = money.add(hamburgerTotal, shakeTotal)
let taxTotal = money.percent(subTotal, tax)
let total = money.add(subTotal, taxTotal)
console.log('Hamburger Total:', hamburgerTotal)
console.log('Shake Total:', shakeTotal)
console.log('Sub Total:', subTotal)
console.log('Tax:', taxTotal)
console.log('Total:', total)
|
Currying | JavaScript | {{Wikipedia|Currying}}
;Task:
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| (function () {
// curry :: ((a, b) -> c) -> a -> b -> c
function curry(f) {
return function (a) {
return function (b) {
return f(a, b);
};
};
}
// TESTS
// product :: Num -> Num -> Num
function product(a, b) {
return a * b;
}
// return typeof curry(product);
// --> function
// return typeof curry(product)(7)
// --> function
//return typeof curry(product)(7)(9)
// --> number
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.map(curry(product)(7))
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
})();
|
Damm algorithm | JavaScript | The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
;Task:
Verify the checksum, stored as last digit of an input.
| const table = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
];
const lookup = (p, c) => table[p][parseInt(c, 10)]
const damm = input => [...input].reduce(lookup, 0) === 0;
// ----------------------------------------------------------[ Tests ]----
const test = () => ["5724", "5727", "112946", "112949"].forEach(e =>
console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)
);
test();
|
Deepcopy | JavaScript | Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.
This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.
If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.
The task should show:
* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.
* Any limitations of the method.
* That the structure and its copy are different.
* Suitable links to external documentation for common libraries.
| var deepcopy = function(o){
return JSON.parse(JSON.stringify(src));
};
var src = {foo:0,bar:[0,1]};
print(JSON.stringify(src));
var dst = deepcopy(src);
print(JSON.stringify(src));
|
Department numbers | Javascript | There is a highly organized city that has decided to assign a number to each of their departments:
::* police department
::* sanitation department
::* fire department
Each department can have a number between '''1''' and '''7''' (inclusive).
The three department numbers are to be unique (different from each other) and must add up to '''12'''.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
;Task:
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| (function () {
'use strict';
// concatMap :: (a -> [b]) -> [a] -> [b]
function concatMap(f, xs) {
return [].concat.apply([], xs.map(f));
};
return '(Police, Sanitation, Fire)\n' +
concatMap(function (x) {
return concatMap(function (y) {
return concatMap(function (z) {
return z !== y && 1 <= z && z <= 7 ? [
[x, y, z]
] : [];
}, [12 - (x + y)]);
}, [1, 2, 3, 4, 5, 6, 7]);
}, [2, 4, 6])
.map(JSON.stringify)
.join('\n');
})(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.