Strassen's algorithm

;Description
In linear algebra, the Strassen algorithm   (named after Volker Strassen),   is an algorithm for matrix multiplication.

It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices,   but would be slower than the fastest known algorithms for extremely large matrices.

;Task
Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.

While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than   512×512   according to Wikipedia),   for the purposes of this task you should not switch until reaching a size of 1 or 2.

;Related task
:* [[Matrix multiplication]]

;See also
:* Wikipedia article

Solution:
"""Matrix multiplication using Strassen's algorithm. Requires Python >= 3.7."""

from __future__ import annotations
from itertools import chain
from typing import List
from typing import NamedTuple
from typing import Optional

class Shape(NamedTuple):
    rows: int
    cols: int

class Matrix(List):
    """A matrix implemented as a two-dimensional list."""

    @classmethod
    def block(cls, blocks) -> Matrix:
        """Return a new Matrix assembled from nested blocks."""
        m = Matrix()
        for hblock in blocks:
            for row in zip(*hblock):
                m.append(list(chain.from_iterable(row)))

        return m

    def dot(self, b: Matrix) -> Matrix:
        """Return a new Matrix that is the product of this matrix and matrix `b`.
        Uses 'simple' or 'naive' matrix multiplication."""
        assert self.shape.cols == b.shape.rows
        m = Matrix()
        for row in self:
            new_row = []
            for c in range(len(b[0])):
                col = [b[r][c] for r in range(len(b))]
                new_row.append(sum(x * y for x, y in zip(row, col)))
            m.append(new_row)
        return m

    def __matmul__(self, b: Matrix) -> Matrix:
        return self.dot(b)

    def __add__(self, b: Matrix) -> Matrix:
        """Matrix addition."""
        assert self.shape == b.shape
        rows, cols = self.shape
        return Matrix(
            [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]
        )

    def __sub__(self, b: Matrix) -> Matrix:
        """Matrix subtraction."""
        assert self.shape == b.shape
        rows, cols = self.shape
        return Matrix(
            [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)]
        )

    def strassen(self, b: Matrix) -> Matrix:
        """Return a new Matrix that is the product of this matrix and matrix `b`.
        Uses strassen algorithm."""
        rows, cols = self.shape

        assert rows == cols, "matrices must be square"
        assert self.shape == b.shape, "matrices must be the same shape"
        assert rows and (rows & rows - 1) == 0, "shape must be a power of 2"

        if rows == 1:
            return self.dot(b)

        p = rows // 2  # partition

        a11 = Matrix([n[:p] for n in self[:p]])
        a12 = Matrix([n[p:] for n in self[:p]])
        a21 = Matrix([n[:p] for n in self[p:]])
        a22 = Matrix([n[p:] for n in self[p:]])

        b11 = Matrix([n[:p] for n in b[:p]])
        b12 = Matrix([n[p:] for n in b[:p]])
        b21 = Matrix([n[:p] for n in b[p:]])
        b22 = Matrix([n[p:] for n in b[p:]])

        m1 = (a11 + a22).strassen(b11 + b22)
        m2 = (a21 + a22).strassen(b11)
        m3 = a11.strassen(b12 - b22)
        m4 = a22.strassen(b21 - b11)
        m5 = (a11 + a12).strassen(b22)
        m6 = (a21 - a11).strassen(b11 + b12)
        m7 = (a12 - a22).strassen(b21 + b22)

        c11 = m1 + m4 - m5 + m7
        c12 = m3 + m5
        c21 = m2 + m4
        c22 = m1 - m2 + m3 + m6

        return Matrix.block([[c11, c12], [c21, c22]])

    def round(self, ndigits: Optional[int] = None) -> Matrix:
        return Matrix([[round(i, ndigits) for i in row] for row in self])

    @property
    def shape(self) -> Shape:
        cols = len(self[0]) if self else 0
        return Shape(len(self), cols)

def examples():
    a = Matrix(
        [
            [1, 2],
            [3, 4],
        ]
    )
    b = Matrix(
        [
            [5, 6],
            [7, 8],
        ]
    )
    c = Matrix(
        [
            [1, 1, 1, 1],
            [2, 4, 8, 16],
            [3, 9, 27, 81],
            [4, 16, 64, 256],
        ]
    )
    d = Matrix(
        [
            [4, -3, 4 / 3, -1 / 4],
            [-13 / 3, 19 / 4, -7 / 3, 11 / 24],
            [3 / 2, -2, 7 / 6, -1 / 4],
            [-1 / 6, 1 / 4, -1 / 6, 1 / 24],
        ]
    )
    e = Matrix(
        [
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 16],
        ]
    )
    f = Matrix(
        [
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1],
        ]
    )

    print("Naive matrix multiplication:")
    print(f"  a * b = {a @ b}")
    print(f"  c * d = {(c @ d).round()}")
    print(f"  e * f = {e @ f}")

    print("Strassen's matrix multiplication:")
    print(f"  a * b = {a.strassen(b)}")
    print(f"  c * d = {c.strassen(d).round()}")
    print(f"  e * f = {e.strassen(f)}")

if __name__ == "__main__":
    examples()


Stream merge

; 2-stream merge
: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.

; ''N''-stream merge
: The same as above, but reading from    ''N''    sources.
: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].

Assume streams are very big. You must not suck them whole in the memory, but read them as streams.

Solution:
/*
 * Rosetta Code - stream merge in C.
 *
 * Two streams (text files) with integer numbers, C89, Visual Studio 2010.
 *
 */

#define _CRT_SECURE_NO_WARNINGS
#include
#include

#define GET(N) { if(fscanf(f##N,"%d",&b##N ) != 1) f##N = NULL; }
#define PUT(N) { printf("%d\n", b##N); GET(N) }

void merge(FILE* f1, FILE* f2, FILE* out)
{
    int b1;
    int b2;

    if(f1) GET(1)
    if(f2) GET(2)

    while ( f1 && f2 )
    {
        if ( b1 <= b2 ) PUT(1)
        else            PUT(2)
    }
    while (f1 ) PUT(1)
    while (f2 ) PUT(2)
}

int main(int argc, char* argv[])
{
    if ( argc < 3 || argc > 3 )
    {
        puts("streammerge filename1 filename2");
        exit(EXIT_FAILURE);
    }
    else
        merge(fopen(argv[1],"r"),fopen(argv[2],"r"),stdout);

    return EXIT_SUCCESS;
}


Stream merge

Solution:
import heapq
import sys

sources = sys.argv[1:]
for item in heapq.merge(open(source) for source in sources):
    print(item)


;Task:
Strip control codes and extended characters from a string.

The solution should demonstrate how to achieve each of the following results:
:*   a string with control codes stripped (but extended characters not stripped)
:*   a string with control codes and extended characters stripped

In ASCII, the control codes have decimal codes 0 through to 31 and 127.

On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.

On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.

Solution:
#include
#include
#include

#define MAXBUF 256  /* limit */
#define STR_SZ 100  /* string size */

/* function prototypes */
int ascii (const unsigned char c);

int ascii_ext (const unsigned char c);

unsigned char* strip(unsigned char* str, const size_t n, int ext );

/* check a character
   return 1 for true
          0 for false
*/
int ascii (const unsigned char c)
{
  unsigned char min = 32;   /*  */
  unsigned char max = 126;  /* ~ tilde */

  if ( c>=min && c<=max ) return 1;

  return 0;
}

/* check if extended character
   return 1 for true
          0 for false
*/
int ascii_ext (const unsigned char c)
{
  unsigned char min_ext = 128;
  unsigned char max_ext = 255;

  if ( c>=min_ext && c<=max_ext )
       return 1;

  return 0;
}

/* fill buffer with only ASCII valid characters
   then rewrite string from buffer
   limit to n < MAX chars
*/

unsigned char* strip( unsigned char* str, const size_t n, int ext)
{

  unsigned char buffer[MAXBUF] = {'\0'};

  size_t i = 0;  // source index
  size_t j = 0;  // dest   index

  size_t max = (n


Solution:
(function (strTest) {

    // s -> s
    function strip(s) {
        return s.split('').filter(function (x) {
            var n = x.charCodeAt(0);

            return 31 < n && 127 > n;
        }).join('');
    }

    return strip(strTest);

})("\ba\x00b\n\rc\fd\xc3");


Solution:
stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127)

print(stripped("\ba\x00b\n\rc\fd\xc3"))


Subleq

One-Instruction Set Computer (OISC).

It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero.

;Task
Your task is to create an interpreter which emulates a SUBLEQ machine.

The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:
::::*   simple numeric values
::::*   memory addresses
::::*   characters for input or output

Any reasonable word size that accommodates all three of the above uses is fine.

The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:
:#   Let '''A''' be the value in the memory location identified by the instruction pointer;   let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.
:#   Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.
:#   If '''A''' is   '''-1'''   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by '''B'''.   '''C''' is unused.
:#   If '''B''' is   '''-1'''   (negative unity),   then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output.   '''C''' is unused.
:#   Otherwise, both '''A''' and '''B''' are treated as addresses.   The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B''').   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.
:#   If the instruction pointer becomes negative, execution halts.

Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   '''0'''   (zero).

For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program.

As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.

15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0

The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:

start:
    0f 11 ff subleq (zero), (message), -1
    11 ff ff subleq (message), -1, -1    ; output character at message
    10 01 ff subleq (neg1), (start+1), -1
    10 03 ff subleq (neg1), (start+3), -1
    0f 0f 00 subleq (zero), (zero), start
; useful constants
zero:
    00      .data 0
neg1:
    ff      .data -1
; the message to print
message: .data "Hello, world!\n\0"
    48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00

Solution:
#include
#include

void
subleq(int *code)
{
	int ip = 0, a, b, c, nextIP;
	char ch;
	while(0 <= ip) {
		nextIP = ip + 3;
		a = code[ip];
		b = code[ip + 1];
		c = code[ip + 2];
		if(a == -1) {
			scanf("%c", &ch);
			code[b] = (int)ch;
		} else if(b == -1) {
			printf("%c", (char)code[a]);
		} else {
			code[b] -= code[a];
			if(code[b] <= 0)
				nextIP = c;
		}
		ip = nextIP;
	}
}

void
processFile(char *fileName)
{
	int *dataSet, i, num;
	FILE *fp = fopen(fileName, "r");
	fscanf(fp, "%d", #);
	dataSet = (int *)malloc(num * sizeof(int));
	for(i = 0; i < num; i++)
		fscanf(fp, "%d", &dataSet[i]);
	fclose(fp);
	subleq(dataSet);
}

int
main(int argC, char *argV[])
{
	if(argC != 2)
		printf("Usage : %s \n", argV[0]);
	else
		processFile(argV[1]);
	return 0;
}


Subleq

Solution:
import sys

def subleq(a):
    i = 0
    try:
        while i >= 0:
            if a[i] == -1:
                a[a[i + 1]] = ord(sys.stdin.read(1))
            elif a[i + 1] == -1:
                print(chr(a[a[i]]), end="")
            else:
                a[a[i + 1]] -= a[a[i]]
                if a[a[i + 1]] <= 0:
                    i = a[i + 2]
                    continue
            i += 3
    except (ValueError, IndexError, KeyboardInterrupt):
        print("abort")
        print(a)

subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15,
        0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111,
        114, 108, 100, 33, 10, 0])


Substring/Top and tail

[[Category:String manipulation]]
The task is to demonstrate how to remove the first and last characters from a string.

The solution should demonstrate how to obtain the following results:

* String with first character removed
* String with last character removed
* String with both the first and last characters removed

If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.

The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.

Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.

Solution:
#include
#include
#include

int main( int argc, char ** argv ){
  const char * str_a = "knight";
  const char * str_b = "socks";
  const char * str_c = "brooms";

  char * new_a = malloc( strlen( str_a ) - 1 );
  char * new_b = malloc( strlen( str_b ) - 1 );
  char * new_c = malloc( strlen( str_c ) - 2 );

  strcpy( new_a, str_a + 1 );
  strncpy( new_b, str_b, strlen( str_b ) - 1 );
  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );

  printf( "%s\n%s\n%s\n", new_a, new_b, new_c );

  free( new_a );
  free( new_b );
  free( new_c );

  return 0;
}


Substring/Top and tail

Solution:
alert("knight".slice(1));       // strip first character
alert("socks".slice(0, -1));    // strip last character
alert("brooms".slice(1, -1));   // strip both first and last characters


Substring/Top and tail

Solution:
from functools import (reduce)

def main():
    for xs in transpose(
        (chunksOf(3)(
            ap([tail, init, compose(init)(tail)])(
                ['knights', 'socks', 'brooms']
            )
        ))
    ):
        print(xs)

# GENERIC -------------------------------------------------

# tail :: [a] -> [a]
def tail(xs):
    return xs[1:]

# init::[a] - > [a]
def init(xs):
    return xs[:-1]

# ap (<*>) :: [(a -> b)] -> [a] -> [b]
def ap(fs):
    return lambda xs: reduce(
        lambda a, f: a + reduce(
            lambda a, x: a + [f(x)], xs, []
        ), fs, []
    )

# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    return lambda f: lambda x: g(f(x))

# transpose :: [[a]] -> [[a]]
def transpose(xs):
    return list(map(list, zip(*xs)))

if __name__ == '__main__':
    main()


Suffixation of decimal numbers

'''Suffixation''':   a letter or a group of letters added to the end of a word to change its meaning.
:::::::       ─────   or, as used herein   ─────
'''Suffixation''':   the addition of a metric or "binary" metric suffix to a number, with/without rounding.

;Task:
Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a
number   (displayed in decimal).

The number may be rounded   (as per user specification)   (via shortening of the number when the number of
digits past the decimal point are to be used).

;Task requirements:
::*   write a function (or functions) to add   (if possible)   a suffix to a number
::*   the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
::*   the sign should be preserved   (if present)
::*   the number may have commas within the number   (the commas need not be preserved)
::*   the number may have a decimal point and/or an exponent as in:   -123.7e-01
::*   the suffix that might be appended should be in uppercase;   however, the   '''i'''   should be in lowercase
::*   support:
::::*   the            metric suffixes:   '''K  M  G  T  P  E  Z  Y  X  W  V  U'''
::::*   the binary metric suffixes:   '''Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui'''
::::*   the (full name) suffix:   '''googol'''   (lowercase)   (equal to '''1e100''')     (optional)
::::*   a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits
::*   validation of the (supplied/specified) arguments is optional but recommended
::*   display   (with identifying text):
::::*   the original number   (with identifying text)
::::*   the number of digits past the decimal point being used   (or none, if not specified)
::::*   the type of suffix being used   (metric or "binary" metric)
::::*   the (new) number with the appropriate   (if any)   suffix
::::*   all output here on this page

;Metric suffixes to be supported   (whether or not they're officially sanctioned):
      '''K'''     multiply the number by  '''10^3'''              kilo      (1,000)
      '''M'''     multiply the number by  '''10^6'''              mega      (1,000,000)
      '''G'''     multiply the number by  '''10^9'''              giga      (1,000,000,000)
      '''T'''     multiply the number by  '''10^12'''             tera      (1,000,000,000,000)
      '''P'''     multiply the number by  '''10^15'''             peta      (1,000,000,000,000,000)
      '''E'''     multiply the number by  '''10^18'''             exa       (1,000,000,000,000,000,000)
      '''Z'''     multiply the number by  '''10^21'''             zetta     (1,000,000,000,000,000,000,000)
      '''Y'''     multiply the number by  '''10^24'''             yotta     (1,000,000,000,000,000,000,000,000)
      '''X'''     multiply the number by  '''10^27'''             xenta     (1,000,000,000,000,000,000,000,000,000)
      '''W'''     multiply the number by  '''10^30'''             wekta     (1,000,000,000,000,000,000,000,000,000,000)
      '''V'''     multiply the number by  '''10^33'''             vendeka   (1,000,000,000,000,000,000,000,000,000,000,000)
      '''U'''     multiply the number by  '''10^36'''             udekta    (1,000,000,000,000,000,000,000,000,000,000,000,000)

;"Binary" suffixes to be supported   (whether or not they're officially sanctioned):
      '''Ki'''    multiply the number by  '''2^10'''              kibi      (1,024)
      '''Mi'''    multiply the number by  '''2^20'''              mebi      (1,048,576)
      '''Gi'''    multiply the number by  '''2^30'''              gibi      (1,073,741,824)
      '''Ti'''    multiply the number by  '''2^40'''              tebi      (1,099,571,627,776)
      '''Pi'''    multiply the number by  '''2^50'''              pebi      (1,125,899,906,884,629)
      '''Ei'''    multiply the number by  '''2^60'''              exbi      (1,152,921,504,606,846,976)
      '''Zi'''    multiply the number by  '''2^70'''              zebi      (1,180,591,620,717,411,303,424)
      '''Yi'''    multiply the number by  '''2^80'''              yobi      (1,208,925,819,614,629,174,706,176)
      '''Xi'''    multiply the number by  '''2^90'''              xebi      (1,237,940,039,285,380,274,899,124,224)
      '''Wi'''    multiply the number by  '''2^100'''             webi      (1,267,650,600,228,229,401,496,703,205,376)
      '''Vi'''    multiply the number by  '''2^110'''             vebi      (1,298,074,214,633,706,907,132,624,082,305,024)
      '''Ui'''    multiply the number by  '''2^120'''             uebi      (1,329,227,995,784,915,872,903,807,060,280,344,576)

;For instance, with this pseudo─code:
                                  /* 1st arg: the number to be transformed.*/
                                  /* 2nd arg: # digits past the dec. point.*/
                                  /* 3rd arg: the type of suffix to use.   */
                                  /*         2   indicates "binary" suffix.*/
                                  /*        10   indicates  decimal suffix.*/
      a = '456,789,100,000,000'   /* "A"  has  eight  trailing zeros.      */
      say ' aa=' suffize(a)       /* Display a suffized number to terminal.*/
                                  /* The  "1"   below shows one decimal ···*/
                                  /*         digit past the decimal point. */
      n = suffize(a, 1)           /* SUFFIZE  is the function name.        */
      n = suffize(a, 1, 10)       /* (identical to the above statement.)   */
      say '  n=' n                /* Display value of  N  to terminal.     */
                                  /* Note the rounding that occurs.        */
      f = suffize(a, 1,  2)       /* SUFFIZE  with one fractional digit    */
      say '  f=' f                /* Display value of  F  to terminal.     */
                                  /* Display value in "binary" metric.     */
      bin = suffize(a, 5, 2)      /* SUFFIZE with binary metric suffix.    */
      say 'bin=' bin              /* Display value of  BIN  to terminal.   */
      win = suffize(a, 0, 2)      /* SUFFIZE with binary metric suffix.    */
      say 'win=' win              /* Display value of  WIN  to terminal.   */
      xvi = ' +16777216 '         /* this used to be a big computer ···    */
      big = suffize(xvi, , 2)     /* SUFFIZE with binary metric suffix.    */
      say 'big=' big              /* Display value of  BIG  to terminal.   */
would display:
       aa= 456.7891T
        n= 456.8T
        f= 415.4Ti
      bin= 415.44727Ti
      win= 415Ti
      big= 16Mi

;Use these test cases:
                87,654,321
               -998,877,665,544,332,211,000      3
               +112,233                          0
                16,777,216                       1
                456,789,100,000,000              2
                456,789,100,000,000              2      10
                456,789,100,000,000              5       2
                456,789,100,000.000e+00          0      10
               +16777216                         ,       2
                1.2e101
                (your primary disk free space)   1                  ◄■■■■■■■ optional

Use whatever parameterizing your computer language supports,   and it's permitted to create as many
separate functions as are needed   (if needed)   if   function arguments aren't allowed to
be omitted or varied.

Solution:
import math
import os

def suffize(num, digits=None, base=10):
    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']

    exponent_distance = 10 if base == 2 else 3
    num = num.strip().replace(',', '')
    num_sign = num[0] if num[0] in '+-' else ''

    num = abs(float(num))

    if base == 10 and num >= 1e100:
        suffix_index = 13
        num /= 1e100
    elif num > 1:
        magnitude = math.floor(math.log(num, base))
        suffix_index = min(math.floor(magnitude / exponent_distance), 12)
        num /= base ** (exponent_distance * suffix_index)
    else:
        suffix_index = 0

    if digits is not None:
        num_str = f'{num:.{digits}f}'
    else:
        num_str = f'{num:.3f}'.strip('0').strip('.')

    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')

tests = [('87,654,321',),
         ('-998,877,665,544,332,211,000', 3),
         ('+112,233', 0),
         ('16,777,216', 1),
         ('456,789,100,000,000', 2),
         ('456,789,100,000,000', 2, 10),
         ('456,789,100,000,000', 5, 2),
         ('456,789,100,000.000e+00', 0, 10),
         ('+16777216', None, 2),
         ('1.2e101',)]

for test in tests:
    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))


Sum and product puzzle

Solve the "Impossible Puzzle":

X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph.

The following conversation occurs:

* S says "P does not know X and Y."
* P says "Now I know X and Y."
* S says "Now I also know X and Y!"

What are X and Y?
}}

It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:

{| class="wikitable"
|-
!
! Quote
! Implied fact
|-
! 1)
| S says "P does not know X and Y."
| For every possible sum decomposition of the number X+Y, the product has in turn ''more than one'' product decomposition.
|-
! 2)
| P says "Now I know X and Y."
| The number X*Y has ''only one'' product decomposition for which fact 1 is true.
|-
! 3)
| S says "Now I also know X and Y."
| The number X+Y has ''only one'' sum decomposition for which fact 2 is true.
|}

Terminology:
* ''"sum decomposition" of a number'' = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
* ''"product decomposition" of a number'' = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B.

Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.

*   Wikipedia:   Sum and Product Puzzle

Solution:
#include
#include
#include

typedef struct node_t {
    int x, y;
    struct node_t *prev, *next;
} node;

node *new_node(int x, int y) {
    node *n = malloc(sizeof(node));
    n->x = x;
    n->y = y;
    n->next = NULL;
    n->prev = NULL;
    return n;
}

void free_node(node **n) {
    if (n == NULL) {
        return;
    }

    (*n)->prev = NULL;
    (*n)->next = NULL;

    free(*n);

    *n = NULL;
}

typedef struct list_t {
    node *head;
    node *tail;
} list;

list make_list() {
    list lst = { NULL, NULL };
    return lst;
}

void append_node(list *const lst, int x, int y) {
    if (lst == NULL) {
        return;
    }

    node *n = new_node(x, y);

    if (lst->head == NULL) {
        lst->head = n;
        lst->tail = n;
    } else {
        n->prev = lst->tail;
        lst->tail->next = n;
        lst->tail = n;
    }
}

void remove_node(list *const lst, const node *const n) {
    if (lst == NULL || n == NULL) {
        return;
    }

    if (n->prev != NULL) {
        n->prev->next = n->next;
        if (n->next != NULL) {
            n->next->prev = n->prev;
        } else {
            lst->tail = n->prev;
        }
    } else {
        if (n->next != NULL) {
            n->next->prev = NULL;
            lst->head = n->next;
        }
    }

    free_node(&n);
}

void free_list(list *const lst) {
    node *ptr;

    if (lst == NULL) {
        return;
    }
    ptr = lst->head;

    while (ptr != NULL) {
        node *nxt = ptr->next;
        free_node(&ptr);
        ptr = nxt;
    }

    lst->head = NULL;
    lst->tail = NULL;
}

void print_list(const list *lst) {
    node *it;

    if (lst == NULL) {
        return;
    }

    for (it = lst->head; it != NULL; it = it->next) {
        int sum = it->x + it->y;
        int prod = it->x * it->y;
        printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
    }
}

void print_count(const list *const lst) {
    node *it;
    int c = 0;

    if (lst == NULL) {
        return;
    }

    for (it = lst->head; it != NULL; it = it->next) {
        c++;
    }

    if (c == 0) {
        printf("no candidates\n");
    } else    if (c == 1) {
        printf("one candidate\n");
    } else {
        printf("%d candidates\n", c);
    }
}

void setup(list *const lst) {
    int x, y;

    if (lst == NULL) {
        return;
    }

    // numbers must be greater than 1
    for (x = 2; x <= 98; x++) {
        // numbers must be unique, and sum no more than 100
        for (y = x + 1; y <= 98; y++) {
            if (x + y <= 100) {
                append_node(lst, x, y);
            }
        }
    }
}

void remove_by_sum(list *const lst, const int sum) {
    node *it;

    if (lst == NULL) {
        return;
    }

    it = lst->head;
    while (it != NULL) {
        int s = it->x + it->y;

        if (s == sum) {
            remove_node(lst, it);
            it = lst->head;
        } else {
            it = it->next;
        }
    }
}

void remove_by_prod(list *const lst, const int prod) {
    node *it;

    if (lst == NULL) {
        return;
    }

    it = lst->head;
    while (it != NULL) {
        int p = it->x * it->y;

        if (p == prod) {
            remove_node(lst, it);
            it = lst->head;
        } else {
            it = it->next;
        }
    }
}

void statement1(list *const lst) {
    short *unique = calloc(100000, sizeof(short));
    node *it, *nxt;

    for (it = lst->head; it != NULL; it = it->next) {
        int prod = it->x * it->y;
        unique[prod]++;
    }

    it = lst->head;
    while (it != NULL) {
        int prod = it->x * it->y;
        nxt = it->next;
        if (unique[prod] == 1) {
            remove_by_sum(lst, it->x + it->y);
            it = lst->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

void statement2(list *const candidates) {
    short *unique = calloc(100000, sizeof(short));
    node *it, *nxt;

    for (it = candidates->head; it != NULL; it = it->next) {
        int prod = it->x * it->y;
        unique[prod]++;
    }

    it = candidates->head;
    while (it != NULL) {
        int prod = it->x * it->y;
        nxt = it->next;
        if (unique[prod] > 1) {
            remove_by_prod(candidates, prod);
            it = candidates->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

void statement3(list *const candidates) {
    short *unique = calloc(100, sizeof(short));
    node *it, *nxt;

    for (it = candidates->head; it != NULL; it = it->next) {
        int sum = it->x + it->y;
        unique[sum]++;
    }

    it = candidates->head;
    while (it != NULL) {
        int sum = it->x + it->y;
        nxt = it->next;
        if (unique[sum] > 1) {
            remove_by_sum(candidates, sum);
            it = candidates->head;
        } else {
            it = nxt;
        }
    }

    free(unique);
}

int main() {
    list candidates = make_list();

    setup(&candidates);
    print_count(&candidates);

    statement1(&candidates);
    print_count(&candidates);

    statement2(&candidates);
    print_count(&candidates);

    statement3(&candidates);
    print_count(&candidates);

    print_list(&candidates);

    free_list(&candidates);
    return 0;
}


Sum and product puzzle

Solution:
(function () {
    'use strict';

    // GENERIC FUNCTIONS

    // concatMap :: (a -> [b]) -> [a] -> [b]
    var concatMap = function concatMap(f, xs) {
            return [].concat.apply([], xs.map(f));
        },

        // curry :: ((a, b) -> c) -> a -> b -> c
        curry = function curry(f) {
            return function (a) {
                return function (b) {
                    return f(a, b);
                };
            };
        },

        // intersectBy :: (a - > a - > Bool) - > [a] - > [a] - > [a]
        intersectBy = function intersectBy(eq, xs, ys) {
            return xs.length && ys.length ? xs.filter(function (x) {
                return ys.some(curry(eq)(x));
            }) : [];
        },

        // range :: Int -> Int -> Maybe Int -> [Int]
        range = function range(m, n, step) {
            var d = (step || 1) * (n >= m ? 1 : -1);
            return Array.from({
                length: Math.floor((n - m) / d) + 1
            }, function (_, i) {
                return m + i * d;
            });
        };

    // PROBLEM FUNCTIONS

    // add, mul :: (Int, Int) -> Int
    var add = function add(xy) {
            return xy[0] + xy[1];
        },
        mul = function mul(xy) {
            return xy[0] * xy[1];
        };

    // sumEq, mulEq :: (Int, Int) -> [(Int, Int)]
    var sumEq = function sumEq(p) {
            var addP = add(p);
            return s1.filter(function (q) {
                return add(q) === addP;
            });
        },
        mulEq = function mulEq(p) {
            var mulP = mul(p);
            return s1.filter(function (q) {
                return mul(q) === mulP;
            });
        };

    // pairEQ :: ((a, a) -> (a, a)) -> Bool
    var pairEQ = function pairEQ(a, b) {
        return a[0] === b[0] && a[1] === b[1];
    };

    // MAIN

    // xs :: [Int]
    var xs = range(1, 100);

    // s1 s2, s3, s4 :: [(Int, Int)]
    var s1 = concatMap(function (x) {
            return concatMap(function (y) {
                return 1 < x && x < y && x + y < 100 ? [
                    [x, y]
                ] : [];
            }, xs);
        }, xs),

        s2 = s1.filter(function (p) {
            return sumEq(p).every(function (q) {
                return mulEq(q).length > 1;
            });
        }),

        s3 = s2.filter(function (p) {
            return intersectBy(pairEQ, mulEq(p), s2).length === 1;
        }),

        s4 = s3.filter(function (p) {
            return intersectBy(pairEQ, sumEq(p), s3).length === 1;
        });

    return s4;
})();


Sum and product puzzle

Solution:
#!/usr/bin/env python

from collections import Counter

def decompose_sum(s):
    return [(a,s-a) for a in range(2,int(s/2+1))]

# Generate all possible pairs
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)

# Fact 1 --> Select pairs for which all sum decompositions have non-unique product
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_pairs = [(a,b) for a,b in all_pairs if
    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]

# Fact 2 --> Select pairs for which the product is unique
product_counts = Counter(c*d for c,d in s_pairs)
p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]

# Fact 3 --> Select pairs for which the sum is unique
sum_counts = Counter(c+d for c,d in p_pairs)
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]

print(final_pairs)


Sum digits of an integer

;Task:
Take a   Natural Number   in a given base and return the sum of its digits:
:*   '''1'''10                  sums to   '''1'''
:*   '''1234'''10       sums to   '''10'''
:*   '''fe'''16              sums to   '''29'''
:*   '''f0e'''16           sums to   '''29'''

Solution:
#include

int SumDigits(unsigned long long n, const int base) {
    int sum = 0;
    for (; n; n /= base)
    	sum += n % base;
    return sum;
}

int main() {
    printf("%d %d %d %d %d\n",
        SumDigits(1, 10),
        SumDigits(12345, 10),
        SumDigits(123045, 10),
        SumDigits(0xfe, 16),
        SumDigits(0xf0e, 16) );
    return 0;
}


Sum digits of an integer

Solution:
function sumDigits(n) {
	n += ''
	for (var s=0, i=0, e=n.length; i')


Sum digits of an integer

Solution:
def sumDigits(num, base=10):
    if base < 2:
        print("Error: base must be at least 2")
        return
    num, sum = abs(num), 0
    while num >= base:
        num, rem = divmod(num, base)
        sum += rem
    return sum + num

print(sumDigits(1))
print(sumDigits(12345))
print(sumDigits(-123045))
print(sumDigits(0xfe, 16))
print(sumDigits(0xf0e, 16))


Sum multiples of 3 and 5

;Task:
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''.

Show output for ''n'' = 1000.

This is is the same as [https://projecteuler.net/problem=1 Project Euler problem 1].

'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.

Solution:
#include
#include

unsigned long long sum35(unsigned long long limit)
{
    unsigned long long sum = 0;
    for (unsigned long long i = 0; i < limit; i++)
        if (!(i % 3) || !(i % 5))
            sum += i;
    return sum;
}

int main(int argc, char **argv)
{
    unsigned long long limit;

    if (argc == 2)
        limit = strtoull(argv[1], NULL, 10);
    else
        limit = 1000;

    printf("%lld\n", sum35(limit));
    return 0;
}


Sum multiples of 3 and 5

Solution:
(function (lstFactors, intExponent) {

    // [n] -> n -> n
    function sumMultiplesBelow(lstIntegers, limit) {
        return range(1, limit - 1).filter(function (x) {
            return isMultiple(lstIntegers, x);
        }).reduce(function (a, n) {
            return a + n;
        }, 0)
    }

    // [n] -> n -> bool
    function isMultiple(lst, n) {
        var i = lng;
        while (i--)
            if (n % (lst[i]) === 0) return true;
        return false;
    }

    // [m..n]
    function range(m, n) {
        var a = Array(n - m + 1),
            i = n + 1;
        while (i--) a[i - 1] = i;
        return a;
    }

    /*      TESTING     */

    // [[a]] -> bool -> s -> s
    function wikiTable(lstRows, blnHeaderRow, strStyle) {
        return '{| class="wikitable" ' + (
            strStyle ? 'style="' + strStyle + '"' : ''
        ) + lstRows.map(function (lstRow, iRow) {
            var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');

            return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
                return typeof v === 'undefined' ? ' ' : v;
            }).join(' ' + strDelim + strDelim + ' ');
        }).join('') + '\n|}';
    }

    var lng = lstFactors.length,
        lstSorted = lstFactors.slice(0).sort();

    var lstTable = [['Below', 'Sum']].concat(
        range(1, intExponent).map(function (x) {
            var pwr = Math.pow(10, x);

            return ['10^' + x, sumMultiplesBelow(lstSorted, pwr)];
        })
    );

    return 'For ' + JSON.stringify(lstFactors) + ':\n\n' +
        wikiTable(lstTable, true) + '\n\n' +
        JSON.stringify(lstTable);

})([3, 5], 8);


Sum multiples of 3 and 5

Solution:
def sum35a(n):
    'Direct count'
    # note: ranges go to n-1
    return sum(x for x in range(n) if x%3==0 or x%5==0)

def sum35b(n):
    "Count all the 3's; all the 5's; minus double-counted 3*5's"
    # note: ranges go to n-1
    return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))

def sum35c(n):
    'Sum the arithmetic progressions: sum3 + sum5 - sum15'
    consts = (3, 5, 15)
    # Note: stop at n-1
    divs = [(n-1) // c for c in consts]
    sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]
    return sums[0] + sums[1] - sums[2]

#test
for n in range(1001):
    sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)
    assert sa == sb == sc  # python tests aren't like those of c.

print('For n = %7i -> %i\n' % (n, sc))

# Pretty patterns
for p in range(7):
    print('For n = %7i -> %i' % (10**p, sum35c(10**p)))

# Scalability
p = 20
print('\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))


Sum of elements below main diagonal of matrix

;Task:
Find and display the sum of elements that are below the main diagonal of a matrix.

The matrix should be a square matrix.

::: ───   Matrix to be used:   ───

      [[1,3,7,8,10],
       [2,4,16,14,4],
       [3,1,9,18,11],
       [12,14,17,18,20],
       [7,1,3,9,5]]

Solution:
#include
#include

typedef struct{
	int rows,cols;
	int** dataSet;
}matrix;

matrix readMatrix(char* dataFile){
	FILE* fp = fopen(dataFile,"r");
	matrix rosetta;
	int i,j;

	fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);

	rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));

	for(i=0;i",argV[0]);

	matrix data = readMatrix(argV[1]);

	printf("\n\nMatrix is : \n\n");
	printMatrix(data);

	printf("\n\nSum below main diagonal : %d",findSum(data));

	return 0;
}


Solution:
(() => {
    "use strict";

    // -------- LOWER TRIANGLE OF A SQUARE MATRIX --------

    // lowerTriangle :: [[a]] -> Either String [[a]]
    const lowerTriangle = matrix =>
        // Either a message, if the matrix is not square,
        // or the lower triangle of the matrix.
        isSquare(matrix) ? (
            Right(
                matrix.reduce(
                    ([n, rows], xs) => [
                        1 + n,
                        rows.concat([xs.slice(0, n)])
                    ],
                    [0, []]
                )[1]
            )
        ) : Left("Not a square matrix");

    // isSquare :: [[a]] -> Bool
    const isSquare = rows => {
        // True if the length of every row in the matrix
        // matches the number of rows in the matrix.
        const n = rows.length;

        return rows.every(x => n === x.length);
    };

    // ---------------------- TEST -----------------------
    const main = () =>
        either(
            msg => `Lower triangle undefined :: ${msg}`
        )(
            rows => sum([].concat(...rows))
        )(
            lowerTriangle([
                [1, 3, 7, 8, 10],
                [2, 4, 16, 14, 4],
                [3, 1, 9, 18, 11],
                [12, 14, 17, 18, 20],
                [7, 1, 3, 9, 5]
            ])
        );

    // --------------------- GENERIC ---------------------

    // Left :: a -> Either a b
    const Left = x => ({
        type: "Either",
        Left: x
    });

    // Right :: b -> Either a b
    const Right = x => ({
        type: "Either",
        Right: x
    });

    // either :: (a -> c) -> (b -> c) -> Either a b -> c
    const either = fl =>
        // Application of the function fl to the
        // contents of any Left value in e, or
        // the application of fr to its Right value.
        fr => e => e.Left ? (
            fl(e.Left)
        ) : fr(e.Right);

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // MAIN ---
    return main();
})();


Solution:
'''Lower triangle of a matrix'''

from itertools import chain, islice
from functools import reduce

# lowerTriangle :: [[a]] -> None | [[a]]
def lowerTriangle(matrix):
    '''Either None, if the matrix is not square, or
       the rows of the matrix, each containing only
       those values that form part of the lower triangle.
    '''
    def go(n_rows, xs):
        n, rows = n_rows
        return 1 + n, rows + [list(islice(xs, n))]

    return reduce(
        go,
        matrix,
        (0, [])
    )[1] if isSquare(matrix) else None

# isSquare :: [[a]] -> Bool
def isSquare(matrix):
    '''True if all rows of the matrix share
       the length of the matrix itself.
    '''
    n = len(matrix)
    return all([n == len(x) for x in matrix])

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Sum of integers in the lower triangle of a matrix.
    '''
    rows = lowerTriangle([
        [1, 3, 7, 8, 10],
        [2, 4, 16, 14, 4],
        [3, 1, 9, 18, 11],
        [12, 14, 17, 18, 20],
        [7, 1, 3, 9, 5]
    ])

    print(
        "Not a square matrix." if None is rows else (
            sum(chain(*rows))
        )
    )

# MAIN ---
if __name__ == '__main__':
    main()


Sum to 100

;Task:
Find solutions to the    ''sum to one hundred''    puzzle.

Add (insert) the mathematical
operators      '''+'''    or    '''-'''      (plus
or minus)   before any of the digits in the
decimal numeric string    '''123456789'''    such that the
resulting mathematical expression adds up to a
particular sum    (in this iconic case,   '''100''').

Example:
              123 + 4 - 5 + 67 - 89   =   100

Show all output here.

:*   Show all solutions that sum to    '''100'''
:*   Show the sum that has the maximum   ''number''   of solutions   (from zero to infinity‡)
:*   Show the lowest positive sum that   ''can't''   be expressed   (has no solutions),   using the rules for this task
:*   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit)

‡   (where   ''infinity''   would be a relatively small   123,456,789)

An example of a sum that can't be expressed   (within the rules of this task)   is:   '''5074'''
(which,   of course,   isn't the lowest positive sum that can't be expressed).

Solution:
/*
 * RossetaCode: Sum to 100, C99, an algorithm using ternary numbers.
 *
 * Find solutions to the "sum to one hundred" puzzle.
 */

#include
#include

/*
 * There are only 13122 (i.e. 2*3**8) different possible expressions,
 * thus we can encode them as positive integer numbers from 0 to 13121.
 */
#define NUMBER_OF_EXPRESSIONS (2 * 3*3*3*3 * 3*3*3*3 )
enum OP { ADD, SUB, JOIN };
typedef int (*cmp)(const void*, const void*);

// Replacing struct Expression and struct CountSum by a tuple like
// struct Pair { int first; int last; } is possible but would make the source
// code less readable.

struct Expression{
    int sum;
    int code;
}expressions[NUMBER_OF_EXPRESSIONS];
int expressionsLength = 0;
int compareExpressionBySum(const struct Expression* a, const struct Expression* b){
    return a->sum - b->sum;
}

struct CountSum{
    int counts;
    int sum;
}countSums[NUMBER_OF_EXPRESSIONS];
int countSumsLength = 0;
int compareCountSumsByCount(const struct CountSum* a, const struct CountSum* b){
    return a->counts - b->counts;
}

int evaluate(int code){
    int value  = 0, number = 0, power  = 1;
    for ( int k = 9; k >= 1; k-- ){
        number = power*k + number;
        switch( code % 3 ){
            case ADD:  value = value + number; number = 0; power = 1; break;
            case SUB:  value = value - number; number = 0; power = 1; break;
            case JOIN: power = power * 10                ; break;
        }
        code /= 3;
    }
    return value;
}

void print(int code){
    static char s[19]; char* p = s;
    int a = 19683, b = 6561;
    for ( int k = 1; k <= 9; k++ ){
        switch((code % a) / b){
            case ADD: if ( k > 1 ) *p++ = '+'; break;
            case SUB:              *p++ = '-'; break;
        }
        a = b;
        b = b / 3;
        *p++ = '0' + k;
    }
    *p = 0;
    printf("%9d = %s\n", evaluate(code), s);
}

void comment(char* string){
    printf("\n\n%s\n\n", string);
}

void init(void){
    for ( int i = 0; i < NUMBER_OF_EXPRESSIONS; i++ ){
        expressions[i].sum = evaluate(i);
        expressions[i].code = i;
    }
    expressionsLength = NUMBER_OF_EXPRESSIONS;
    qsort(expressions,expressionsLength,sizeof(struct Expression),(cmp)compareExpressionBySum);

    int j = 0;
    countSums[0].counts = 1;
    countSums[0].sum = expressions[0].sum;
    for ( int i = 0; i < expressionsLength; i++ ){
        if ( countSums[j].sum != expressions[i].sum ){
            j++;
            countSums[j].counts = 1;
            countSums[j].sum = expressions[i].sum;
        }
        else
            countSums[j].counts++;
    }
    countSumsLength = j + 1;
    qsort(countSums,countSumsLength,sizeof(struct CountSum),(cmp)compareCountSumsByCount);
}

int main(void){

    init();

    comment("Show all solutions that sum to 100");
    const int givenSum = 100;
    struct Expression ex = { givenSum, 0 };
    struct Expression* found;
    if ( found = bsearch(&ex,expressions,expressionsLength,
        sizeof(struct Expression),(cmp)compareExpressionBySum) ){
        while ( found != expressions && (found-1)->sum == givenSum )
            found--;
        while ( found != &expressions[expressionsLength] && found->sum == givenSum )
            print(found++->code);
    }

    comment("Show the positve sum that has the maximum number of solutions");
    int maxSumIndex = countSumsLength - 1;
    while( countSums[maxSumIndex].sum < 0 )
        maxSumIndex--;
    printf("%d has %d solutions\n",
        countSums[maxSumIndex].sum, countSums[maxSumIndex].counts);

    comment("Show the lowest positive number that can't be expressed");
    for ( int value = 0; ; value++ ){
        struct Expression ex = { value, 0 };
        if (!bsearch(&ex,expressions,expressionsLength,
                sizeof(struct Expression),(cmp)compareExpressionBySum)){
            printf("%d\n", value);
            break;
        }
    }

    comment("Show the ten highest numbers that can be expressed");
    for ( int i = expressionsLength-1; i >= expressionsLength-10; i-- )
        print(expressions[i].code);

    return 0;
}


Sum to 100

Solution:
(function () {
    'use strict';

    // GENERIC FUNCTIONS ----------------------------------------------------

    // permutationsWithRepetition :: Int -> [a] -> [[a]]
    var permutationsWithRepetition = function (n, as) {
        return as.length > 0 ?
            foldl1(curry(cartesianProduct)(as), replicate(n, as)) : [];
    };

    // cartesianProduct :: [a] -> [b] -> [[a, b]]
    var cartesianProduct = function (xs, ys) {
        return [].concat.apply([], xs.map(function (x) {
            return [].concat.apply([], ys.map(function (y) {
                return [
                    [x].concat(y)
                ];
            }));
        }));
    };

    // curry :: ((a, b) -> c) -> a -> b -> c
    var curry = function (f) {
        return function (a) {
            return function (b) {
                return f(a, b);
            };
        };
    };

    // flip :: (a -> b -> c) -> b -> a -> c
    var flip = function (f) {
        return function (a, b) {
            return f.apply(null, [b, a]);
        };
    };

    // foldl1 :: (a -> a -> a) -> [a] -> a
    var foldl1 = function (f, xs) {
        return xs.length > 0 ? xs.slice(1)
            .reduce(f, xs[0]) : [];
    };

    // replicate :: Int -> a -> [a]
    var replicate = function (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);
    };

    // group :: Eq a => [a] -> [[a]]
    var group = function (xs) {
        return groupBy(function (a, b) {
            return a === b;
        }, xs);
    };

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    var groupBy = function (f, xs) {
        var dct = xs.slice(1)
            .reduce(function (a, x) {
                var h = a.active.length > 0 ? a.active[0] : undefined,
                    blnGroup = h !== undefined && f(h, x);

                return {
                    active: blnGroup ? a.active.concat(x) : [x],
                    sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
                };
            }, {
                active: xs.length > 0 ? [xs[0]] : [],
                sofar: []
            });
        return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
    };

    // compare :: a -> a -> Ordering
    var compare = function (a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
    };

    // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
    var on = function (f, g) {
        return function (a, b) {
            return f(g(a), g(b));
        };
    };

    // nub :: [a] -> [a]
    var nub = function (xs) {
        return nubBy(function (a, b) {
            return a === b;
        }, xs);
    };

    // nubBy :: (a -> a -> Bool) -> [a] -> [a]
    var nubBy = function (p, xs) {
        var x = xs.length ? xs[0] : undefined;

        return x !== undefined ? [x].concat(nubBy(p, xs.slice(1)
            .filter(function (y) {
                return !p(x, y);
            }))) : [];
    };

    // find :: (a -> Bool) -> [a] -> Maybe a
    var find = function (f, xs) {
        for (var i = 0, lng = xs.length; i < lng; i++) {
            if (f(xs[i], i)) return xs[i];
        }
        return undefined;
    };

    // Int -> [a] -> [a]
    var take = function (n, xs) {
        return xs.slice(0, n);
    };

    // unlines :: [String] -> String
    var unlines = function (xs) {
        return xs.join('\n');
    };

    // show :: a -> String
    var show = function (x) {
        return JSON.stringify(x);
    }; //, null, 2);

    // head :: [a] -> a
    var head = function (xs) {
        return xs.length ? xs[0] : undefined;
    };

    // tail :: [a] -> [a]
    var tail = function (xs) {
        return xs.length ? xs.slice(1) : undefined;
    };

    // length :: [a] -> Int
    var length = function (xs) {
        return xs.length;
    };

    // SIGNED DIGIT SEQUENCES  (mapped to sums and to strings)

    // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )
    // asSum :: [Sign] -> Int
    var asSum = function (xs) {
        var dct = xs.reduceRight(function (a, sign, i) {
            var d = i + 1; //  zero-based index to [1-9] positions
            if (sign !== 0) {
                // Sum increased, digits cleared
                return {
                    digits: [],
                    n: a.n + sign * parseInt([d].concat(a.digits)
                        .join(''), 10)
                };
            } else return { // Digits extended, sum unchanged
                digits: [d].concat(a.digits),
                n: a.n
            };
        }, {
            digits: [],
            n: 0
        });
        return dct.n + (
            dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0
        );
    };

    // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus )
    // asString :: [Sign] -> String
    var asString = function (xs) {
        var ns = xs.reduce(function (a, sign, i) {
            var d = (i + 1)
                .toString();
            return sign === 0 ? a + d : a + (sign > 0 ? ' +' : ' -') + d;
        }, '');

        return ns[0] === '+' ? tail(ns) : ns;
    };

    // SUM T0 100 ------------------------------------------------------------

    // universe :: [[Sign]]
    var universe = permutationsWithRepetition(9, [0, 1, -1])
        .filter(function (x) {
            return x[0] !== 1;
        });

    // allNonNegativeSums :: [Int]
    var allNonNegativeSums = universe.map(asSum)
        .filter(function (x) {
            return x >= 0;
        })
        .sort();

    // uniqueNonNegativeSums :: [Int]
    var uniqueNonNegativeSums = nub(allNonNegativeSums);

    return ["Sums to 100:\n", unlines(universe.filter(function (x) {
                return asSum(x) === 100;
            })
            .map(asString)),

        "\n\n10 commonest sums (sum, followed by number of routes to it):\n",
        show(take(10, group(allNonNegativeSums)
            .sort(on(flip(compare), length))
            .map(function (xs) {
                return [xs[0], xs.length];
            }))),

        "\n\nFirst positive integer not expressible as a sum of this kind:\n",
        show(find(function (x, i) {
            return x !== i;
        }, uniqueNonNegativeSums.sort(compare)) - 1), // zero-based index

        "\n10 largest sums:\n",
        show(take(10, uniqueNonNegativeSums.sort(flip(compare))))
    ].join('\n') + '\n';
})();


Sum to 100

Solution:
from itertools import product, islice

def expr(p):
    return "{}1{}2{}3{}4{}5{}6{}7{}8{}9".format(*p)

def gen_expr():
    op = ['+', '-', '']
    return [expr(p) for p in product(op, repeat=9) if p[0] != '+']

def all_exprs():
    values = {}
    for expr in gen_expr():
        val = eval(expr)
        if val not in values:
            values[val] = 1
        else:
            values[val] += 1
    return values

def sum_to(val):
    for s in filter(lambda x: x[0] == val, map(lambda x: (eval(x), x), gen_expr())):
        print(s)

def max_solve():
    print("Sum {} has the maximum number of solutions: {}".
          format(*max(all_exprs().items(), key=lambda x: x[1])))

def min_solve():
    values = all_exprs()
    for i in range(123456789):
        if i not in values:
            print("Lowest positive sum that can't be expressed: {}".format(i))
            return

def highest_sums(n=10):
    sums = map(lambda x: x[0],
               islice(sorted(all_exprs().items(), key=lambda x: x[0], reverse=True), n))
    print("Highest Sums: {}".format(list(sums)))

sum_to(100)
max_solve()
min_solve()
highest_sums()


Summarize and say sequence

There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
        0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.

Another way to generate a self-referential sequence is to summarize the previous term.

Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
        0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.

Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)

;Task:
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.

Seed Value(s): 9009 9090 9900

Iterations: 21

Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110

;Related tasks:
*   [[Fours is the number of letters in the ...]]
*   [[Look-and-say sequence]]
*   [[Number names]]
*   [[Self-describing numbers]]
*   [[Spelling of ordinal numbers]]

;Also see:
*   The On-Line Encyclopedia of Integer Sequences.

Solution:
#include
#include
#include

typedef struct rec_t rec_t;
struct rec_t {
	int depth;
	rec_t * p[10];
};

rec_t root = {0, {0}};

#define USE_POOL_ALLOC
#ifdef USE_POOL_ALLOC /* not all that big a deal */
rec_t *tail = 0, *head = 0;
#define POOL_SIZE (1 << 20)
inline rec_t *new_rec()
{
	if (head == tail) {
		head = calloc(sizeof(rec_t), POOL_SIZE);
		tail = head + POOL_SIZE;
	}
	return head++;
}
#else
#define new_rec() calloc(sizeof(rec_t), 1)
#endif

rec_t *find_rec(char *s)
{
	int i;
	rec_t *r = &root
	while (*s) {
		i = *s++ - '0';
		if (!r->p[i]) r->p[i] = new_rec();
		r = r->p[i];
	}
	return r;
}

/* speed up number to string conversion */
char number[100][4];
void init()
{
	int i;
	for (i = 0; i < 100; i++)
		sprintf(number[i], "%d", i);
}

void count(char *buf)
{
	int i, c[10] = {0};
	char *s;

	for (s = buf; *s; c[*s++ - '0']++);

	for (i = 9; i >= 0; i--) {
		if (!c[i]) continue;
		s = number[c[i]];

		*buf++ = s[0];
		if ((*buf = s[1])) buf++;

		*buf++ = i + '0';
	}

	*buf = '\0';
}

int depth(char *in, int d)
{
	rec_t *r = find_rec(in);

	if (r->depth > 0)
		return r->depth;

	d++;
	if (!r->depth)	r->depth = -d;
	else		r->depth += d;

	count(in);
	d = depth(in, d);

	if (r->depth <= 0) r->depth = d + 1;
	return r->depth;
}

int main(void)
{
	char a[100];
	int i, d, best_len = 0, n_best = 0;
	int best_ints[32];
	rec_t *r;

	init();

	for (i = 0; i < 1000000; i++) {
		sprintf(a, "%d", i);
		d = depth(a, 0);

		if (d < best_len) continue;
		if (d > best_len) {
			n_best = 0;
			best_len = d;
		}
		if (d == best_len)
			best_ints[n_best++] = i;
	}

	printf("longest length: %d\n", best_len);
	for (i = 0; i < n_best; i++) {
		printf("%d\n", best_ints[i]);
		sprintf(a, "%d", best_ints[i]);
		for (d = 0; d <= best_len; d++) {
			r = find_rec(a);
			printf("%3d: %s\n", r->depth, a);
			count(a);
		}
		putchar('\n');
	}

	return 0;
}


Summarize and say sequence

Solution:
from itertools import groupby, permutations

def A036058(number):
    return ''.join( str(len(list(g))) + k
                    for k,g in groupby(sorted(str(number), reverse=True)) )

def A036058_length(numberstring='0', printit=False):
    iterations, last_three, queue_index = 1, ([None] * 3), 0

    def A036058(number):
        # rely on external reverse-sort of digits of number
        return ''.join( str(len(list(g))) + k
                        for k,g in groupby(number) )

    while True:
        if printit:
            print("  %2i %s" % (iterations, numberstring))
        numberstring = ''.join(sorted(numberstring, reverse=True))
        if numberstring in last_three:
            break
        assert iterations < 1000000
        last_three[queue_index], numberstring = numberstring, A036058(numberstring)
        iterations += 1
        queue_index +=1
        queue_index %=3
    return iterations

def max_A036058_length( start_range=range(11) ):
    already_done = set()
    max_len = (-1, [])
    for n in start_range:
        sn = str(n)
        sns = tuple(sorted(sn, reverse=True))
        if sns not in already_done:
            already_done.add(sns)
            size = A036058_length(sns)
            if size > max_len[0]:
                max_len = (size, [n])
            elif size == max_len[0]:
                max_len[1].append(n)
    return max_len

lenmax, starts = max_A036058_length( range(1000000) )

# Expand
allstarts = []
for n in starts:
    allstarts += [int(''.join(x))
                  for x in set(k
                               for k in permutations(str(n), 4)
                               if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]

print ( '''\
The longest length, followed by the number(s) with the longest sequence length
for starting sequence numbers below 1000000 are:
  Iterations = %i and sequence-starts = %s.''' % (lenmax, allstarts)   )

print ( '''
Note that only the first of any sequences with the same digits is printed below.
(The others will differ only in their first term)''' )

for n in starts:
    print()
    A036058_length(str(n), printit=True)


Super-d numbers

A super-d number is a positive, decimal (base ten) integer   '''n'''   such that   '''d × nd'''   has at least   '''d'''   consecutive digits   '''d'''   where
    2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.

'''Super-d'''   numbers are also shown on   '''MathWorld'''™   as   '''super-''d'' '''   or   '''super-''d'''''.

;Task:
:* Write a function/procedure/routine to find super-d numbers.
:* For   '''d=2'''   through   '''d=6''',   use the routine to show the first   '''10'''   super-d numbers.

;Extra credit:
:* Show the first   '''10'''   super-7, super-8, and/or super-9 numbers   (optional).

;See also:
:*   [http://mathworld.wolfram.com/Super-dNumber.html Wolfram MathWorld - Super-d Number].
:*   [http://oeis.org/A014569 OEIS: A014569 - Super-3 Numbers].

Solution:
#include
#include
#include
#include

int main() {
    for (unsigned int d = 2; d <= 9; ++d) {
        printf("First 10 super-%u numbers:\n", d);
        char digits[16] = { 0 };
        memset(digits, '0' + d, d);
        mpz_t bignum;
        mpz_init(bignum);
        for (unsigned int count = 0, n = 1; count < 10; ++n) {
            mpz_ui_pow_ui(bignum, n, d);
            mpz_mul_ui(bignum, bignum, d);
            char* str = mpz_get_str(NULL, 10, bignum);
            if (strstr(str, digits)) {
                printf("%u ", n);
                ++count;
            }
            free(str);
        }
        mpz_clear(bignum);
        printf("\n");
    }
    return 0;
}


Super-d numbers

Solution:
from itertools import islice, count

def superd(d):
    if d != int(d) or not 2 <= d <= 9:
        raise ValueError("argument must be integer from 2 to 9 inclusive")
    tofind = str(d) * d
    for n in count(2):
        if tofind in str(d * n ** d):
            yield n

if __name__ == '__main__':
    for d in range(2, 9):
        print(f"{d}:", ', '.join(str(n) for n in islice(superd(d), 10)))


Superellipse

A superellipse is a geometric figure defined as the set of all points (x, y) with

::: \left|\frac{x}{a}\right|^n\! + \left|\frac{y}{b}\right|^n\! = 1,

where ''n'', ''a'', and ''b'' are positive numbers.

;Task
Draw a superellipse with n = 2.5, and a = b = 200

Solution:
#include
#include
#include

#define pi M_PI

int main(){

	double a,b,n,i,incr = 0.0001;

	printf("Enter major and minor axes of the SuperEllipse : ");
	scanf("%lf%lf",&a,&b);

	printf("Enter n : ");
	scanf("%lf",&n);

	initwindow(500,500,"Superellipse");

	for(i=0;i<2*pi;i+=incr){
		putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2


Superellipse

Solution:
var n = 2.5, a = 200, b = 200, ctx;

function point( x, y ) {
    ctx.fillRect( x, y, 1, 1);
}

function start() {
    var can = document.createElement('canvas');
    can.width  = can.height = 600;
    ctx = can.getContext( "2d" );
    ctx.rect( 0, 0, can.width, can.height );
    ctx.fillStyle = "#000000"; ctx.fill();
    document.body.appendChild( can );

    ctx.fillStyle = "#ffffff";
    for( var t = 0; t < 1000; t += .1 ) {
       x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) );
       y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) );

       point( x + ( can.width >> 1 ), y + ( can.height >> 1 ) );
    }
}


Superellipse

Solution:
# Superellipse drawing in Python 2.7.9
# pic can see at http://www.imgup.cz/image/712

import matplotlib.pyplot as plt
from math import sin, cos, pi

def sgn(x):
	return ((x>0)-(x<0))*1

a,b,n=200,200,2.5 # param n making shape
na=2/n
step=100 # accuracy
piece=(pi*2)/step
xp=[];yp=[]

t=0
for t1 in range(step+1):
	# because sin^n(x) is mathematically the same as (sin(x))^n...
	x=(abs((cos(t)))**na)*a*sgn(cos(t))
	y=(abs((sin(t)))**na)*b*sgn(sin(t))
	xp.append(x);yp.append(y)
	t+=piece

plt.plot(xp,yp) # plotting all point from array xp, yp
plt.title("Superellipse with parameter "+str(n))
plt.show()


Superpermutation minimisation

A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.

For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.

A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.

A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.

The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.

Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.

The problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.

;Reference:
* [http://www.njohnston.ca/2013/04/the-minimal-superpermutation-problem/ The Minimal Superpermutation Problem]. by Nathaniel Johnston.
* [http://oeis.org/A180632 oeis A180632] gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
* [https://www.youtube.com/watch?v=wJGE4aEWc28 Superpermutations - Numberphile]. A video
* [https://www.youtube.com/watch?v=OZzIvl1tbPo Superpermutations: the maths problem solved by 4chan - Standupmaths]. A video of recent (2018) mathematical progress.
* [https://www.youtube.com/watch?v=_tpNuulTeSQ New Superpermutations Discovered!] Standupmaths & Numberphile.

Solution:
#include
#include
#include

#define MAX 12
char *super = 0;
int pos, cnt[MAX];

// 1! + 2! + ... + n!
int fact_sum(int n)
{
	int s, x, f;
	for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);
	return s;
}

int r(int n)
{
	if (!n) return 0;

	char c = super[pos - n];
	if (!--cnt[n]) {
		cnt[n] = n;
		if (!r(n-1)) return 0;
	}
	super[pos++] = c;
	return 1;
}

void superperm(int n)
{
	int i, len;

	pos = n;
	len = fact_sum(n);
	super = realloc(super, len + 1);
	super[len] = '\0';

	for (i = 0; i <= n; i++) cnt[i] = i;
	for (i = 1; i <= n; i++) super[i - 1] = i + '0';

	while (r(n));
}

int main(void)
{
	int n;
	for (n = 0; n < MAX; n++) {
		printf("superperm(%2d) ", n);
		superperm(n);
		printf("len = %d", (int)strlen(super));
		// uncomment next line to see the string itself
		// printf(": %s", super);
		putchar('\n');
	}

	return 0;
}


Superpermutation minimisation

Solution:
"Generate a short Superpermutation of n characters A... as a string using various algorithms."

from __future__ import print_function, division

from itertools import permutations
from math import factorial
import string
import datetime
import gc

MAXN = 7

def s_perm0(n):
    """
    Uses greedy algorithm of adding another char (or two, or three, ...)
    until an unseen perm is formed in the last n chars
    """
    allchars = string.ascii_uppercase[:n]
    allperms = [''.join(p) for p in permutations(allchars)]
    sp, tofind = allperms[0], set(allperms[1:])
    while tofind:
        for skip in range(1, n):
            for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):
                #print(sp, skip, trial_add)
                trial_perm = (sp + trial_add)[-n:]
                if trial_perm in tofind:
                    #print(sp, skip, trial_add)
                    sp += trial_add
                    tofind.discard(trial_perm)
                    trial_add = None    # Sentinel
                    break
            if trial_add is None:
                break
    assert all(perm in sp for perm in allperms) # Check it is a superpermutation
    return sp

def s_perm1(n):
    """
    Uses algorithm of concatenating all perms in order if not already part
    of concatenation.
    """
    allchars = string.ascii_uppercase[:n]
    allperms = [''.join(p) for p in sorted(permutations(allchars))]
    perms, sp = allperms[::], ''
    while perms:
        nxt = perms.pop()
        if nxt not in sp:
            sp += nxt
    assert all(perm in sp for perm in allperms)
    return sp

def s_perm2(n):
    """
    Uses algorithm of concatenating all perms in order first-last-nextfirst-
    nextlast... if not already part of concatenation.
    """
    allchars = string.ascii_uppercase[:n]
    allperms = [''.join(p) for p in sorted(permutations(allchars))]
    perms, sp = allperms[::], ''
    while perms:
        nxt = perms.pop(0)
        if nxt not in sp:
            sp += nxt
        if perms:
            nxt = perms.pop(-1)
            if nxt not in sp:
                sp += nxt
    assert all(perm in sp for perm in allperms)
    return sp

def _s_perm3(n, cmp):
    """
    Uses algorithm of concatenating all perms in order first,
    next_with_LEASTorMOST_chars_in_same_position_as_last_n_chars, ...
    """
    allchars = string.ascii_uppercase[:n]
    allperms = [''.join(p) for p in sorted(permutations(allchars))]
    perms, sp = allperms[::], ''
    while perms:
        lastn = sp[-n:]
        nxt = cmp(perms,
                  key=lambda pm:
                    sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))
        perms.remove(nxt)
        if nxt not in sp:
            sp += nxt
    assert all(perm in sp for perm in allperms)
    return sp

def s_perm3_max(n):
    """
    Uses algorithm of concatenating all perms in order first,
    next_with_MOST_chars_in_same_position_as_last_n_chars, ...
    """
    return _s_perm3(n, max)

def s_perm3_min(n):
    """
    Uses algorithm of concatenating all perms in order first,
    next_with_LEAST_chars_in_same_position_as_last_n_chars, ...
    """
    return _s_perm3(n, min)

longest = [factorial(n) * n for n in range(MAXN + 1)]
weight, runtime = {}, {}
print(__doc__)
for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:
    print('\n###\n### %s\n###' % algo.__name__)
    print(algo.__doc__)
    weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)
    for n in range(1, MAXN + 1):
        gc.collect()
        gc.disable()
        t = datetime.datetime.now()
        sp = algo(n)
        t = datetime.datetime.now() - t
        gc.enable()
        runtime[algo.__name__] += t
        lensp = len(sp)
        wt = (lensp / longest[n]) ** 2
        print('  For N=%i: SP length %5i Max: %5i Weight: %5.2f'
              % (n, lensp, longest[n], wt))
        weight[algo.__name__] *= wt
    weight[algo.__name__] **= 1 / n  # Geometric mean
    weight[algo.__name__] = 1 / weight[algo.__name__]
    print('%*s Overall Weight: %5.2f in %.1f seconds.'
          % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))

print('\n###\n### Algorithms ordered by shortest superpermutations first\n###')
print('\n'.join('%12s (%.3f)' % kv for kv in
                sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))

print('\n###\n### Algorithms ordered by shortest runtime first\n###')
print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in
                sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))


Sylvester's sequence

In number theory, '''Sylvester's sequence''' is an integer sequence in which each term of the sequence is the product of the previous terms,  plus one.

Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to '''1''' more rapidly than any other series of unit fractions with the same number of terms.

Further, the sum of the first '''k''' terms of the infinite series of reciprocals provides the closest possible underestimate of  '''1''' by any k-term Egyptian fraction.

;Task:
* Write a routine (function, procedure, generator, whatever) to calculate '''Sylvester's sequence'''.
* Use that routine to show the values of the first '''10''' elements in the sequence.
* Show the sum of the reciprocals of the first '''10''' elements on the sequence, ideally as an exact fraction.

;Related tasks:
* [[Egyptian fractions]]
* [[Harmonic series]]

;See also:
* OEIS A000058 - Sylvester's sequence

Solution:
'''Sylvester's sequence'''

from functools import reduce
from itertools import count, islice

# sylvester :: [Int]
def sylvester():
    '''Non-finite stream of the terms
       of Sylvester's sequence.
       (OEIS A000058)
    '''
    def go(n):
        return 1 + reduce(
            lambda a, x: a * go(x),
            range(0, n),
            1
        ) if 0 != n else 2

    return map(go, count(0))

# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''First terms, and sum of reciprocals.'''

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )

# MAIN ---
if __name__ == '__main__':
    main()


Tarjan

[[Category:Algorithm]]

Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.

It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.

Tarjan's Algorithm is named for its discoverer, Robert Tarjan.

;References:
* The article on Wikipedia.

See also: [[Kosaraju]]

Solution:
from collections import defaultdict

def from_edges(edges):
    '''translate list of edges to list of nodes'''

    class Node:
        def __init__(self):
            # root is one of:
            #   None: not yet visited
            #   -1: already processed
            #   non-negative integer: what Wikipedia pseudo code calls 'lowlink'
            self.root = None
            self.succ = []

    nodes = defaultdict(Node)
    for v,w in edges:
        nodes[v].succ.append(nodes[w])

    for i,v in nodes.items(): # name the nodes for final output
        v.id = i

    return nodes.values()

def trajan(V):
    def strongconnect(v, S):
        v.root = pos = len(S)
        S.append(v)

        for w in v.succ:
            if w.root is None:  # not yet visited
                yield from strongconnect(w, S)

            if w.root >= 0:  # still on stack
                v.root = min(v.root, w.root)

        if v.root == pos:  # v is the root, return everything above
            res, S[pos:] = S[pos:], []
            for w in res:
                w.root = -1
            yield [r.id for r in res]

    for v in V:
        if v.root is None:
            yield from strongconnect(v, [])

tables = [  # table 1
            [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
             (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],

            # table 2
            [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]

for table in (tables):
    for g in trajan(from_edges(table)):
        print(g)
    print()


Tau function

[[Category:Mathematics]]

Given a positive integer, count the number of its positive divisors.

;Task
Show the result for the first   '''100'''   positive integers.

;Related task
*  [[Tau number]]

Solution:
#include

// See https://en.wikipedia.org/wiki/Divisor_function
unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    // Odd prime factors up to the square root
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int n;

    printf("Count of divisors for the first %d positive integers:\n", limit);
    for (n = 1; n <= limit; ++n) {
        printf("%3d", divisor_count(n));
        if (n % 20 == 0) {
            printf("\n");
        }
    }

    return 0;
}


Tau function

Solution:
def factorize(n):
    assert(isinstance(n, int))
    if n < 0:
        n = -n
    if n < 2:
        return
    k = 0
    while 0 == n%2:
        k += 1
        n //= 2
    if 0 < k:
        yield (2,k)
    p = 3
    while p*p <= n:
        k = 0
        while 0 == n%p:
            k += 1
            n //= p
        if 0 < k:
            yield (p,k)
        p += 2
    if 1 < n:
        yield (n,1)

def tau(n):
    assert(n != 0)
    ans = 1
    for (p,k) in factorize(n):
        ans *= 1 + k
    return ans

if __name__ == "__main__":
    print(*map(tau, range(1, 101)))


Teacup rim text

On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   '''TEA'''   appears a number of times separated by bullet characters   (•).

It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three-letter word.

So start at the   '''T'''   and read   '''TEA'''.   Start at the   '''E'''   and read   '''EAT''',   or start at the   '''A'''   and read   '''ATE'''.

That got me thinking that maybe there are other words that could be used rather that   '''TEA'''.   And that's just English.   What about Italian or Greek or ... um ... Telugu.

For English, we will use the unixdict (now) located at:   [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict.txt].

(This will maintain continuity with other Rosetta Code tasks that also use it.)

;Task:
Search for a set of words that could be printed around the edge of a teacup.   The words in each set are to be of the same length, that length being greater than two (thus precluding   '''AH'''   and   '''HA''',   for example.)

Having listed a set, for example   ['''ate tea eat'''],   refrain from displaying permutations of that set, e.g.:   ['''eat tea ate''']   etc.

The words should also be made of more than one letter   (thus precluding   '''III'''   and   '''OOO'''   etc.)

The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second.   The first letter of the second becomes the last letter of the third.   So   '''ATE'''   becomes   '''TEA'''   and   '''TEA'''   becomes   '''EAT'''.

All of the possible permutations, using this particular permutation technique, must be words in the list.

The set you generate for   '''ATE'''   will never included the word   '''ETA'''   as that cannot be reached via the first-to-last movement method.

Display one line for each set of teacup rim words.

Solution:
#include
#include
#include
#include

int string_compare(gconstpointer p1, gconstpointer p2) {
    const char* const* s1 = p1;
    const char* const* s2 = p2;
    return strcmp(*s1, *s2);
}

GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
    GError* error = NULL;
    GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
    if (channel == NULL) {
        g_propagate_error(error_ptr, error);
        return NULL;
    }
    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
    GString* line = g_string_sized_new(64);
    gsize term_pos;
    while (g_io_channel_read_line_string(channel, line, &term_pos,
                                         &error) == G_IO_STATUS_NORMAL) {
        char* word = g_strdup(line->str);
        word[term_pos] = '\0';
        g_ptr_array_add(dict, word);
    }
    g_string_free(line, TRUE);
    g_io_channel_unref(channel);
    if (error != NULL) {
        g_propagate_error(error_ptr, error);
        g_ptr_array_free(dict, TRUE);
        return NULL;
    }
    g_ptr_array_sort(dict, string_compare);
    return dict;
}

void rotate(char* str, size_t len) {
    char c = str[0];
    memmove(str, str + 1, len - 1);
    str[len - 1] = c;
}

char* dictionary_search(const GPtrArray* dictionary, const char* word) {
    char** result = bsearch(&word, dictionary->pdata, dictionary->len,
                            sizeof(char*), string_compare);
    return result != NULL ? *result : NULL;
}

void find_teacup_words(GPtrArray* dictionary) {
    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
    GPtrArray* teacup_words = g_ptr_array_new();
    GString* temp = g_string_sized_new(8);
    for (size_t i = 0, n = dictionary->len; i < n; ++i) {
        char* word = g_ptr_array_index(dictionary, i);
        size_t len = strlen(word);
        if (len < 3 || g_hash_table_contains(found, word))
            continue;
        g_ptr_array_set_size(teacup_words, 0);
        g_string_assign(temp, word);
        bool is_teacup_word = true;
        for (size_t i = 0; i < len - 1; ++i) {
            rotate(temp->str, len);
            char* w = dictionary_search(dictionary, temp->str);
            if (w == NULL) {
                is_teacup_word = false;
                break;
            }
            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
                g_ptr_array_add(teacup_words, w);
        }
        if (is_teacup_word && teacup_words->len > 0) {
            printf("%s", word);
            g_hash_table_add(found, word);
            for (size_t i = 0; i < teacup_words->len; ++i) {
                char* teacup_word = g_ptr_array_index(teacup_words, i);
                printf(" %s", teacup_word);
                g_hash_table_add(found, teacup_word);
            }
            printf("\n");
        }
    }
    g_string_free(temp, TRUE);
    g_ptr_array_free(teacup_words, TRUE);
    g_hash_table_destroy(found);
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s dictionary\n", argv[0]);
        return EXIT_FAILURE;
    }
    GError* error = NULL;
    GPtrArray* dictionary = load_dictionary(argv[1], &error);
    if (dictionary == NULL) {
        if (error != NULL) {
            fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
                    argv[1], error->message);
            g_error_free(error);
        }
        return EXIT_FAILURE;
    }
    find_teacup_words(dictionary);
    g_ptr_array_free(dictionary, TRUE);
    return EXIT_SUCCESS;
}


Teacup rim text

Solution:
===Set() objects===
Reading a local dictionary with the macOS JS for Automation library:


Teacup rim text

Solution:
(() => {
    'use strict';

    // main :: IO ()
    const main = () =>
        showGroups(
            circularWords(
                // Local copy of:
                // https://www.mit.edu/~ecprice/wordlist.10000
                lines(readFile('~/mitWords.txt'))
            )
        );

    // circularWords :: [String] -> [String]
    const circularWords = ws =>
        ws.filter(isCircular(new Set(ws)), ws);

    // isCircular :: Set String -> String -> Bool
    const isCircular = lexicon => w => {
        const iLast = w.length - 1;
        return 1 < iLast && until(
            ([i, bln, s]) => iLast < i || !bln,
            ([i, bln, s]) => [1 + i, lexicon.has(s), rotated(s)],
            [0, true, rotated(w)]
        )[1];
    };

    // DISPLAY --------------------------------------------

    // showGroups :: [String] -> String
    const showGroups = xs =>
        unlines(map(
            gp => map(snd, gp).join(' -> '),
            groupBy(
                (a, b) => fst(a) === fst(b),
                sortBy(
                    comparing(fst),
                    map(x => Tuple(concat(sort(chars(x))), x),
                        xs
                    )
                )
            ).filter(gp => 1 < gp.length)
        ));

    // MAC OS JS FOR AUTOMATION ---------------------------

    // readFile :: FilePath -> IO String
    const readFile = fp => {
        const
            e = $(),
            uw = ObjC.unwrap,
            s = uw(
                $.NSString.stringWithContentsOfFileEncodingError(
                    $(fp)
                    .stringByStandardizingPath,
                    $.NSUTF8StringEncoding,
                    e
                )
            );
        return undefined !== s ? (
            s
        ) : uw(e.localizedDescription);
    };

    // GENERIC FUNCTIONS ----------------------------------

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = (a, b) => ({
        type: 'Tuple',
        '0': a,
        '1': b,
        length: 2
    });

    // chars :: String -> [Char]
    const chars = s => s.split('');

    // comparing :: (a -> b) -> (a -> a -> Ordering)
    const comparing = f =>
        (x, y) => {
            const
                a = f(x),
                b = f(y);
            return a < b ? -1 : (a > b ? 1 : 0);
        };

    // concat :: [[a]] -> [a]
    // concat :: [String] -> String
    const concat = xs =>
        0 < xs.length ? (() => {
            const unit = 'string' !== typeof xs[0] ? (
                []
            ) : '';
            return unit.concat.apply(unit, xs);
        })() : [];

    // fst :: (a, b) -> a
    const fst = tpl => tpl[0];

    // groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
    const groupBy = (f, xs) => {
        const tpl = xs.slice(1)
            .reduce((a, x) => {
                const h = a[1].length > 0 ? a[1][0] : undefined;
                return (undefined !== h) && f(h, x) ? (
                    Tuple(a[0], a[1].concat([x]))
                ) : Tuple(a[0].concat([a[1]]), [x]);
            }, Tuple([], 0 < xs.length ? [xs[0]] : []));
        return tpl[0].concat([tpl[1]]);
    };

    // lines :: String -> [String]
    const lines = s => s.split(/[\r\n]/);

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) =>
        (Array.isArray(xs) ? (
            xs
        ) : xs.split('')).map(f);

    // rotated :: String -> String
    const rotated = xs =>
        xs.slice(1) + xs[0];

    // showLog :: a -> IO ()
    const showLog = (...args) =>
        console.log(
            args
            .map(JSON.stringify)
            .join(' -> ')
        );

    // snd :: (a, b) -> b
    const snd = tpl => tpl[1];

    // sort :: Ord a => [a] -> [a]
    const sort = xs => xs.slice()
        .sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));

    // sortBy :: (a -> a -> Ordering) -> [a] -> [a]
    const sortBy = (f, xs) =>
        xs.slice()
        .sort(f);

    // 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;
    };

    // MAIN ---
    return main();
})();


Teacup rim text

Solution:
'''Teacup rim text'''

from itertools import chain, groupby
from os.path import expanduser
from functools import reduce

# main :: IO ()
def main():
    '''Circular anagram groups, of more than one word,
       and containing words of length > 2, found in:
       https://www.mit.edu/~ecprice/wordlist.10000
    '''
    print('\n'.join(
        concatMap(circularGroup)(
            anagrams(3)(
                # Reading from a local copy.
                lines(readFile('~/mitWords.txt'))
            )
        )
    ))

# anagrams :: Int -> [String] -> [[String]]
def anagrams(n):
    '''Groups of anagrams, of minimum group size n,
       found in the given word list.
    '''
    def go(ws):
        def f(xs):
            return [
                [snd(x) for x in xs]
            ] if n <= len(xs) >= len(xs[0][0]) else []
        return concatMap(f)(groupBy(fst)(sorted(
            [(''.join(sorted(w)), w) for w in ws],
            key=fst
        )))
    return go

# circularGroup :: [String] -> [String]
def circularGroup(ws):
    '''Either an empty list, or a list containing
       a string showing any circular subset found in ws.
    '''
    lex = set(ws)
    iLast = len(ws) - 1
    # If the set contains one word that is circular,
    # then it must contain all of them.
    (i, blnCircular) = until(
        lambda tpl: tpl[1] or (tpl[0] > iLast)
    )(
        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
    )(
        (0, False)
    )
    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []

# isCircular :: Set String -> String -> Bool
def isCircular(lexicon):
    '''True if all of a word's rotations
       are found in the given lexicon.
    '''
    def go(w):
        def f(tpl):
            (i, _, x) = tpl
            return (1 + i, x in lexicon, rotated(x))

        iLast = len(w) - 1
        return until(
            lambda tpl: iLast < tpl[0] or (not tpl[1])
        )(f)(
            (0, True, rotated(w))
        )[1]
    return go

# allRotations :: String -> [String]
def allRotations(w):
    '''All rotations of the string w.'''
    return takeIterate(len(w) - 1)(
        rotated
    )(w)

# GENERIC -------------------------------------------------

# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    '''A concatenated list over which a function has been mapped.
       The list monad can be derived by using a function f which
       wraps its output in a list,
       (using an empty list to represent computational failure).
    '''
    def go(xs):
        return chain.from_iterable(map(f, xs))
    return go

# fst :: (a, b) -> a
def fst(tpl):
    '''First member of a pair.'''
    return tpl[0]

# groupBy :: (a -> b) -> [a] -> [[a]]
def groupBy(f):
    '''The elements of xs grouped,
       preserving order, by equality
       in terms of the key function f.
    '''
    def go(xs):
        return [
            list(x[1]) for x in groupby(xs, key=f)
        ]
    return go

# lines :: String -> [String]
def lines(s):
    '''A list of strings,
       (containing no newline characters)
       derived from a single new-line delimited string.
    '''
    return s.splitlines()

# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumL(f):
    '''A tuple of an accumulation and a list derived by a
       combined map and fold,
       with accumulation from left to right.
    '''
    def go(a, x):
        tpl = f(a[0], x)
        return (tpl[0], a[1] + [tpl[1]])
    return lambda acc: lambda xs: (
        reduce(go, xs, (acc, []))
    )

# readFile :: FilePath -> IO String
def readFile(fp):
    '''The contents of any file at the path
       derived by expanding any ~ in fp.
    '''
    with open(expanduser(fp), 'r', encoding='utf-8') as f:
        return f.read()

# rotated :: String -> String
def rotated(s):
    '''A string rotated 1 character to the right.'''
    return s[1:] + s[0]

# snd :: (a, b) -> b
def snd(tpl):
    '''Second member of a pair.'''
    return tpl[1]

# takeIterate :: Int -> (a -> a) -> a -> [a]
def takeIterate(n):
    '''Each value of n iterations of f
       over a start value of x.
    '''
    def go(f):
        def g(x):
            def h(a, i):
                v = f(a) if i else x
                return (v, v)
            return mapAccumL(h)(x)(
                range(0, 1 + n)
            )[1]
        return g
    return go

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
    '''The result of repeatedly applying f until p holds.
       The initial seed value is x.
    '''
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go

# MAIN ---
if __name__ == '__main__':
    main()


Temperature conversion

There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Rankine.

The Celsius and Kelvin scales have the same magnitude, but different null points.

: 0 degrees Celsius corresponds to 273.15 kelvin.
: 0 kelvin is absolute zero.

The Fahrenheit and Rankine scales also have the same magnitude, but different null points.

: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
: 0 degrees Rankine is absolute zero.

The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.

;Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.

;Example:

K  21.00

C  -252.15

F  -421.87

R  37.80

Solution:
#include
#include

double kelvinToCelsius(double k){
    return k - 273.15;
}

double kelvinToFahrenheit(double k){
    return k * 1.8 - 459.67;
}

double kelvinToRankine(double k){
    return k * 1.8;
}
void convertKelvin(double kelvin) {
    printf("K %.2f\n", kelvin);
    printf("C %.2f\n", kelvinToCelsius(kelvin));
    printf("F %.2f\n", kelvinToFahrenheit(kelvin));
    printf("R %.2f", kelvinToRankine(kelvin));
}

int main(int argc, const char * argv[])
{
    if (argc > 1) {
        double kelvin = atof(argv[1]);
        convertKelvin(kelvin);
    }
    return 0;
}


Temperature conversion

Solution:
var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67

Number.prototype.toMaxDecimal = function (d) {
    return +this.toFixed(d) + ''
}

function kCnv(k) {
    document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°' )
}

kCnv(21)
kCnv(295)


Temperature conversion

Solution:
>>> toK = {'C': (lambda c: c + 273.15),
           'F': (lambda f: (f + 459.67) / 1.8),
           'R': (lambda r: r / 1.8),
           'K': (lambda k: k) }
>>> while True:
    magnitude, unit = input('  ? ').split()
    k = toK[unit](float(magnitude))
    print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
          % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))

  ? 222.2 K
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
  ? -50.95 C
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
  ? -59.71 F
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
  ? 399.96 R
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
  ?


Terminal control/Coloured text

[[Category:Terminal control]]

;Task:
Display a word in various colours on the terminal.

The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.

Optionally demonstrate:
* How the system should determine if the terminal supports colour
* Setting of the background colour
* How to cause blinking or flashing (if supported by the terminal)

Solution:
#include

void table(const char *title, const char *mode)
{
	int f, b;
	printf("\n\033[1m%s\033[m\n bg\t fg\n", title);
	for (b = 40; b <= 107; b++) {
		if (b == 48) b = 100;
		printf("%3d\t\033[%s%dm", b, mode, b);
		for (f = 30; f <= 97; f++) {
			if (f == 38) f = 90;
			printf("\033[%dm%3d ", f, f);
		}
		puts("\033[m");
	}
}

int main(void)
{
	int fg, bg, blink, inverse;

	table("normal ( ESC[22m or ESC[m )", "22;");
	table("bold ( ESC[1m )", "1;");
	table("faint ( ESC[2m ), not well supported", "2;");
	table("italic ( ESC[3m ), not well supported", "3;");
	table("underline ( ESC[4m ), support varies", "4;");
	table("blink ( ESC[5m )", "5;");
	table("inverted ( ESC[7m )", "7;");
	return 0;
}


Terminal control/Coloured text

Solution:
from colorama import init, Fore, Back, Style
init(autoreset=True)

print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW  + "Rosetta Code!"
print Fore.CYAN    + "Rosetta Code!"
print Fore.GREEN   + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"