task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/OLE_automation
OLE automation
OLE Automation   is an inter-process communication mechanism based on   Component Object Model   (COM) on Microsoft Windows. Task Provide an automation server implementing objects that can be accessed by a client running in a separate process. The client gets a proxy-object that can call methods on the object. The communication should be able to handle conversions of variants to and from the native value types.
#Wren
Wren
/* OLE_automation.wren */   class Ole { foreign static coInitialize(p) foreign static coUninitialize() }   class OleUtil { static createObject(programID) { return IUnknown.new(programID) }   foreign static putProperty(disp, name, param) foreign static mustGetProperty(disp, name) foreign static mustCallMethod(disp, name) foreign static mustCallMethod2(disp, name, param) }   foreign class GUID { construct new(guid) {} }   var IID_DISPATCH = GUID.new("{00020400-0000-0000-C000-000000000046}")   foreign class IUnknown { construct new(programID) {}   foreign queryInterface(iid, name) foreign static release(name) }   class Time { foreign static sleep(secs) }   Ole.coInitialize(0) var unknown = OleUtil.createObject("Word.application") var word = unknown.queryInterface(IID_DISPATCH, "word") OleUtil.putProperty(word, "Visible", true) var documents = OleUtil.mustGetProperty(word, "Documents") var document = OleUtil.mustCallMethod(documents, "Add") var content = OleUtil.mustGetProperty(document, "Content") var paragraphs = OleUtil.mustGetProperty(content, "Paragraphs") var paragraph = OleUtil.mustCallMethod(paragraphs, "Add") var range = OleUtil.mustGetProperty(paragraph, "Range")   OleUtil.putProperty(range, "Text", "This is a Rosetta Code test document.")   Time.sleep(10)   OleUtil.putProperty(document, "Saved", true) OleUtil.mustCallMethod2(document, "Close", false) OleUtil.mustCallMethod(word, "Quit") IUnknown.release(word)   Ole.coUninitialize()
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#Nim
Nim
import algorithm, math, sequtils, strformat, strutils, sugar   type   CorrectionType {.pure.} = enum BenjaminiHochberg = "Benjamini-Hochberg" BenjaminiYekutieli = "Benjamini-Yekutieli" Bonferroni = "Bonferroni" Hochberg = "Hochberg" Holm = "Holm" Hommel = "Hommel" Šidák = "Šidák"   Direction {.pure.} = enum Up, Down   PValues = seq[float]     template newPValues(length: Natural): PValues = ## Create a PValues object of given length. newSeq[float](length)     func ratchet(p: var PValues; dir: Direction) = var m = p[0] case dir of Up: for i in 1..p.high: if p[i] > m: p[i] = m m = p[i] of Down: for i in 1..p.high: if p[i] < m: p[i] = m m = p[i] for i in 0..p.high: if p[i] > 1: p[i] = 1     func schwartzian(p, mult: PValues; dir: Direction): PValues =   let length = p.len let sortOrder = if dir == Up: Descending else: Ascending let order1 = toSeq(p.pairs).sorted((x, y) => cmp(x.val, y.val), sortOrder).mapIt(it.key)   var pa = newPValues(length) for i in 0..pa.high: pa[i] = mult[i] * p[order1[i]]   ratchet(pa, dir)   let order2 = toSeq(order1.pairs).sortedByIt(it.val).mapIt(it.key) for idx in order2: result.add pa[idx]     proc adjust(p: PValues; ctype: CorrectionType): PValues = let length = p.len assert length > 0 let flength = length.toFloat   case ctype   of BenjaminiHochberg: var mult = newPValues(length) for i in 0..mult.high: mult[i] = flength / (flength - i.toFloat) return schwartzian(p, mult, Up)   of BenjaminiYekutieli: var q = 0.0 for i in 1..length: q += 1 / i var mult = newPValues(length) for i in 0..mult.high: mult[i] = (q * flength) / (flength - i.toFloat) return schwartzian(p, mult, Up)   of Bonferroni: result = newPValues(length) for i in 0..result.high: result[i] = min(p[i] * flength, 1) return   of Hochberg: var mult = newPValues(length) for i in 0..mult.high: mult[i] = i.toFloat + 1 return schwartzian(p, mult, Up)   of Holm: var mult = newPValues(length) for i in 0..mult.high: mult[i] = flength - i.toFloat return schwartzian(p, mult, Down)   of Hommel: let order1 = toSeq(p.pairs).sortedByIt(it.val).mapIt(it.key) let s = order1.mapIt(p[it]) var m = Inf for i in 0..s.high: m = min(m, s[i] * flength / (i + 1).toFloat) var q, pa = repeat(m, length)   for j in countdown(length - 1, 2): let lower = toSeq(0..length - j) let upper = toSeq((length - j + 1)..<length) var qmin = j.toFloat * s[upper[0]] / 2 for i in 1..upper.high: let val = s[upper[i]] * j.toFloat / (i + 2).toFloat if val < qmin: qmin = val for idx in lower: q[idx] = min(s[idx] * j.toFloat, qmin) for idx in upper: q[idx] = q[^j] for i, val in q: if pa[i] < val: pa[i] = val   let order2 = toSeq(order1.pairs).sortedByIt(it.val).mapIt(it.key) return order2.mapIt(pa[it])   of Šidák: result = newPValues(length) for i in 0..result.high: result[i] = 1 - (1 - p[i])^length return     func pformat(p: PValues; cols = 5): string = var lines: seq[string] for i in countup(0, p.high, cols): let fchunk = p[i..<(i + cols)] var schunk = newSeq[string](fchunk.len) for j in 0..<cols: schunk[j] = fchunk[j].formatFloat(ffDecimal, 10) lines.add &"[{i:2}] {schunk.join(\" \")}" result = lines.join("\n")     func adjusted(p: PValues; ctype: CorrectionType): string = doAssert p.len > 0 and min(p) >= 0 and max(p) <= 1, "p-values must be in range 0.0 to 1.0." result = &"\n{ctype}\n{pformat(p.adjust(ctype))}"   when isMainModule:   const PVals = @[ 4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03]   for ctype in CorrectionType: echo adjusted(PVals, ctype)
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Go
Go
package main   import ( "fmt" "sort" "strings" )   type indexSort struct { val sort.Interface ind []int }   func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], s.ind[j] = s.ind[j], s.ind[i] }   func disjointSliceSort(m, n []string) []string { s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))} used := make(map[int]bool) for _, nw := range n { for i, mw := range m { if used[i] || mw != nw { continue } used[i] = true s.ind = append(s.ind, i) break } } sort.Sort(s) return s.val.(sort.StringSlice) }   func disjointStringSort(m, n string) string { return strings.Join( disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ") }   func main() { for _, data := range []struct{ m, n string }{ {"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, } { mp := disjointStringSort(data.m, data.n) fmt.Printf("%s → %s » %s\n", data.m, data.n, mp) }   }
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Common_Lisp
Common Lisp
(defun sort-table (table &key (ordering #'string<) (column 0) reverse) (sort table (if reverse (complement ordering) ordering) :key (lambda (row) (elt row column))))
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#D
D
import std.stdio, std.algorithm, std.functional;   string[][] sortTable(string[][] table, in bool function(string[],string[]) ordering=null, in int column = 0, in bool reverse = false) { if (ordering is null) table.schwartzSort!(row => row[column])(); else table.sort!ordering(); if (reverse) table.reverse(); return table; }   void main() { auto data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]];   alias show = curry!(writefln, "%-(%s\n%)\n"); show(data); show(sortTable(data)); show(sortTable(data, null, 2)); show(sortTable(data, null, 1)); show(sortTable(data, null, 1, true)); show(sortTable(data, (a,b) => b.length > a.length)); }
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#Bracmat
Bracmat
( 1 2 3 4 5:?List1 & 1 2 1 5 2 2:?List2 & 1 2 1 5 2:?List3 & 1 2 1 5 2:?List4 & Cat Elephant Rat Cat:?List5 & Cat Elephant Rat:?List6 & Cat Cat Elephant:?List7 & ( gt = first second .  !arg:(?first,?second) & out $ ( (.!first)+(.!second)  : ((.!first)+(.!second)|2*(.!first)) & FALSE | TRUE ) ) & gt$(!List1,!List2) & gt$(!List2,!List3) & gt$(!List3,!List4) & gt$(!List4,!List5) & gt$(!List5,!List6) & gt$(!List6,!List7) );
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#TI-83_BASIC
TI-83 BASIC
PROGRAM:PASCALTR :Lbl IN :ClrHome :Disp "NUMBER OF ROWS" :Input N :If N < 1:Goto IN :{N,N}→dim([A]) :"CHEATING TO MAKE IT FASTER" :For(I,1,N) :1→[A](1,1) :End :For(I,2,N) :For(J,2,I) :[A](I-1,J-1)+[A](I-1,J)→[A](I,J) :End :End :[A]
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#FreeBASIC
FreeBASIC
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Furor
Furor
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#FutureBasic
FutureBasic
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Delphi
Delphi
  program POrderedWords;   {$APPTYPE CONSOLE}   uses SysUtils, Classes, IdHTTP;   function IsOrdered(const s:string): Boolean; var I: Integer; begin Result := Length(s)<2; // empty or 1 char strings are ordered for I := 2 to Length(s) do if s[I]<s[I-1] then // can improve using case/localization to order... Exit; Result := True; end;   function ProcessDictionary(const AUrl: string): string; var slInput: TStringList; I, WordSize: Integer; begin slInput := TStringList.Create; try with TIdHTTP.Create(nil) do try slInput.Text := Get(AUrl); finally Free; end; // or use slInput.LoadFromFile('yourfilename') to load from a local file WordSize :=0; for I := 0 to slInput.Count-1 do begin if IsOrdered(slInput[I]) then if (Length(slInput[I]) = WordSize) then Result := Result + slInput[I] + ' ' else if (Length(slInput[I]) > WordSize) then begin Result := slInput[I] + ' '; WordSize := Length(slInput[I]); end; end; finally slInput.Free; end; end;   begin try WriteLn(ProcessDictionary('http://www.puzzlers.org/pub/wordlists/unixdict.txt')); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#NetRexx
NetRexx
  y='In girum imus nocte et consumimur igni'   -- translation: We walk around in the night and -- we are burnt by the fire (of love) say say 'string = 'y say   pal=isPal(y)   if pal==0 then say "The string isn't palindromic." else say 'The string is palindromic.'   method isPal(x) static x=x.upper().space(0) /* removes all blanks (spaces) */ /* and translate to uppercase. */ return x==x.reverse() /* returns 1 if exactly equal */  
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Java
Java
  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class OneTimePad {   public static void main(String[] args) { String controlName = "AtomicBlonde"; generatePad(controlName, 5, 60, 65, 90); String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES"; String encrypted = parse(true, controlName, text.replaceAll(" ", "")); String decrypted = parse(false, controlName, encrypted); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted);   controlName = "AtomicBlondeCaseSensitive"; generatePad(controlName, 5, 60, 32, 126); text = "It was the best of times, it was the worst of times."; encrypted = parse(true, controlName, text); decrypted = parse(false, controlName, encrypted); System.out.println(); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); }   private static String parse(boolean encryptText, String controlName, String text) { StringBuilder sb = new StringBuilder(); int minCh = 0; int maxCh = 0; Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$"); Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$"); boolean validated = false; try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) { String inLine = null; while ( (inLine = in.readLine()) != null ) { Matcher minMatcher = minChPattern.matcher(inLine); if ( minMatcher.matches() ) { minCh = Integer.parseInt(minMatcher.group(1)); continue; } Matcher maxMatcher = maxChPattern.matcher(inLine); if ( maxMatcher.matches() ) { maxCh = Integer.parseInt(maxMatcher.group(1)); continue; } if ( ! validated && minCh > 0 && maxCh > 0 ) { validateText(text, minCh, maxCh); validated = true; } // # is comment. - is used key. if ( inLine.startsWith("#") || inLine.startsWith("-") ) { continue; } // Have encryption key. String key = inLine; if ( encryptText ) { for ( int i = 0 ; i < text.length(); i++) { sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh)); } } else { for ( int i = 0 ; i < text.length(); i++) { int decrypt = text.charAt(i) - key.charAt(i); if ( decrypt < 0 ) { decrypt += maxCh - minCh + 1; } decrypt += minCh; sb.append((char) decrypt); } } break; } } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); }   private static void validateText(String text, int minCh, int maxCh) { // Validate text is in range for ( char ch : text.toCharArray() ) { if ( ch != ' ' && (ch < minCh || ch > maxCh) ) { throw new IllegalArgumentException("ERROR 103: Invalid text."); } }   }   private static String getFileName(String controlName) { return controlName + ".1tp"; }   private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) { Random random = new Random(); try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) { writer.write("# Lines starting with '#' are ignored."); writer.newLine(); writer.write("# Lines starting with '-' are previously used."); writer.newLine(); writer.write("# MIN_CH = " + minCh); writer.newLine(); writer.write("# MAX_CH = " + maxCh); writer.newLine(); for ( int line = 0 ; line < keys ; line++ ) { StringBuilder sb = new StringBuilder(); for ( int ch = 0 ; ch < keyLength ; ch++ ) { sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh)); } writer.write(sb.toString()); writer.newLine(); } writer.write("# EOF"); writer.newLine(); } catch (Exception e) { throw new RuntimeException(e); } }   }  
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Nim
Nim
import bitops, strutils   func ownCalcPass(password, nonce: string): uint32 =   var start = true   for c in nonce: if c != '0' and start: result = parseInt(password).uint32 start = false case c of '0': discard of '1': result = result.rotateRightBits(7) of '2': result = result.rotateRightBits(4) of '3': result = result.rotateRightBits(3) of '4': result = result.rotateLeftBits(1) of '5': result = result.rotateLeftBits(5) of '6': result = result.rotateLeftBits(12) of '7': result = (result and 0x0000FF00) or result shl 24 or (result and 0x00FF0000) shr 16 or (result and 0xFF000000u32) shr 8 of '8': result = result shl 16 or result shr 24 or (result and 0x00FF0000) shr 8 of '9': result = not result else: raise newException(ValueError, "non-digit in nonce.")     when isMainModule:   proc testPasswordCalc(password, nonce: string; expected: uint32) =   let res = ownCalcPass(password, nonce) let m = "$# $# $# $#".format(password, nonce, res, expected) echo if res == expected: "PASS " else: "FAIL ", m   testPasswordCalc("12345", "603356072", 25280520u32) testPasswordCalc("12345", "410501656", 119537670u32) testPasswordCalc("12345", "630292165", 4269684735u32)
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Perl
Perl
use strict; use warnings; use feature 'say'; use integer; # required solely for 2's complement operation: $n1 = ~$n2   sub own_password { my($password, $nonce) = @_; my $n1 = 0; my $n2 = $password; for my $d (split //, $nonce) { if ($d == 1) { $n1 = ($n2 & 0xFFFFFF80) >> 7; $n2 <<= 25; } elsif ($d == 2) { $n1 = ($n2 & 0xFFFFFFF0) >> 4; $n2 <<= 28; } elsif ($d == 3) { $n1 = ($n2 & 0xFFFFFFF8) >> 3; $n2 <<= 29; } elsif ($d == 4) { $n1 = $n2 << 1; $n2 >>= 31; } elsif ($d == 5) { $n1 = $n2 << 5; $n2 >>= 27; } elsif ($d == 6) { $n1 = $n2 << 12; $n2 >>= 20; } elsif ($d == 7) { $n1 = ($n2 & 0x0000FF00) | (($n2 & 0x000000FF) << 24) | (($n2 & 0x00FF0000) >> 16); $n2 = ($n2 & 0xFF000000) >> 8; } elsif ($d == 8) { $n1 = ($n2 & 0x0000FFFF) << 16 | $n2 >> 24; $n2 = ($n2 & 0x00FF0000) >> 8; } elsif ($d == 9) { $n1 = ~$n2; } else { $n1 = $n2 } $n1 = ($n1 | $n2) & 0xFFFFFFFF if $d != 0 and $d != 9; $n2 = $n1; } $n1 }   say own_password( 12345, 603356072 ); say own_password( 12345, 410501656 ); say own_password( 12345, 630292165 );
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#C
C
#include <stdlib.h> #include <GL/gl.h> #include <GL/glut.h>   void paint(void) { glClearColor(0.3,0.3,0.3,0.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);   glShadeModel(GL_SMOOTH);   glLoadIdentity(); glTranslatef(-15.0, -15.0, 0.0);   glBegin(GL_TRIANGLES); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0, 0.0); glColor3f(0.0, 1.0, 0.0); glVertex2f(30.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.0, 30.0); glEnd();   glFlush(); }   void reshape(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0); glMatrixMode(GL_MODELVIEW); }   int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitWindowSize(640, 480); glutCreateWindow("Triangle");   glutDisplayFunc(paint); glutReshapeFunc(reshape);   glutMainLoop();   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Float_Random;   procedure One_Of_N is   Num_Of_Lines: constant Positive := 10;   package Rnd renames Ada.Numerics.Float_Random; Gen: Rnd.Generator; -- used globally   function Choose_One_Of_N(Last_Line_Number: Positive) return Natural is Current_Choice: Natural := 0; begin for Line_Number in 1 .. Last_Line_Number loop if (Rnd.Random(Gen) * Float(Line_Number) <= 1.0) then Current_Choice := Line_Number; end if; end loop; return Current_Choice; end Choose_One_Of_N;   Results: array(1 .. Num_Of_Lines) of Natural := (others => 0); Index: Integer range 1 .. Num_Of_Lines;   begin Rnd.Reset(Gen); for I in 1 .. 1_000_000 loop -- compute results Index := Choose_One_Of_N(Num_Of_Lines); Results(Index) := Results(Index) + 1; end loop;   for R in Results'Range loop -- output results Ada.Text_IO.Put(Integer'Image(Results(R))); end loop; end One_Of_N;
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#Perl
Perl
#!/usr/bin/env perl   use strict; use warnings FATAL => 'all'; use autodie ':all'; use List::Util 'min'; use feature 'say';   sub pmin { my $array = shift; my $x = 1; my @pmin_array; my $n = scalar @$array; for (my $index = 0; $index < $n; $index++) { $pmin_array[$index] = min(@$array[$index], $x); } @pmin_array }   sub cummin { my $array_ref = shift; my @cummin; my $cumulative_min = @$array_ref[0]; foreach my $p (@$array_ref) { if ($p < $cumulative_min) { $cumulative_min = $p; } push @cummin, $cumulative_min; } @cummin }   sub cummax { my $array_ref = shift; my @cummax; my $cumulative_max = @$array_ref[0]; foreach my $p (@$array_ref) { if ($p > $cumulative_max) { $cumulative_max = $p; } push @cummax, $cumulative_max; } @cummax }   sub order {#made to match R's "order" my $array_ref = shift; my $decreasing = 'false'; if (defined $_[0]) { my $option = shift; if ($option =~ m/true/i) { $decreasing = 'true'; } elsif ($option =~ m/false/i) { #do nothing, it's already set to false } else { print "2nd option should only be case-insensitive 'true' or 'false'"; die; } } my @array; my $max_index = scalar @$array_ref-1; if ($decreasing eq 'false') { @array = sort { @$array_ref[$a] <=> @$array_ref[$b] } 0..$max_index; } elsif ($decreasing eq 'true') { @array = sort { @$array_ref[$b] <=> @$array_ref[$a] } 0..$max_index; } @array }     sub p_adjust { my $pvalues_ref = shift; my $method; if (defined $_[0]) { $method = shift } else { $method = 'Holm' } my %methods = ( 'bh' => 1, 'fdr' => 1, 'by' => 1, 'holm' => 1, 'hommel' => 1, 'bonferroni' => 1, 'hochberg' => 1 ); my $method_found = 'no'; foreach my $key (keys %methods) { if ((uc $method) eq (uc $key)) { $method = $key; $method_found = 'yes'; last } } if ($method_found eq 'no') { if ($method =~ m/benjamini-?\s*hochberg/i) { $method = 'bh'; $method_found = 'yes'; } elsif ($method =~ m/benjamini-?\s*yekutieli/i) { $method = 'by'; $method_found = 'yes'; } } if ($method_found eq 'no') { print "No method could be determined from $method.\n"; die } my $lp = scalar @$pvalues_ref; my $n = $lp; my @qvalues; if ($method eq 'hochberg') { my @o = order($pvalues_ref, 'TRUE'); my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = ($index+1)* @$pvalues_ref[$o[$index]];#PVALUES[$o[$index]] is p[o] } my @cummin = cummin(\@cummin_input); my @pmin = pmin(\@cummin); my @ro = order(\@o); @qvalues = @pmin[@ro]; } elsif ($method eq 'bh') { my @o = order($pvalues_ref, 'TRUE'); my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = ($n/($n-$index))* @$pvalues_ref[$o[$index]];#PVALUES[$o[$index]] is p[o] } my @ro = order(\@o); my @cummin = cummin(\@cummin_input); my @pmin = pmin(\@cummin); @qvalues = @pmin[@ro]; } elsif ($method eq 'by') { my $q = 0.0; my @o = order($pvalues_ref, 'TRUE'); my @ro = order(\@o); for (my $index = 1; $index < ($n+1); $index++) { $q += 1.0 / $index; } my @cummin_input; for (my $index = 0; $index < $n; $index++) { $cummin_input[$index] = $q * ($n/($n-$index)) * @$pvalues_ref[$o[$index]];#PVALUES[$o[$index]] is p[o] } # say join (',', @cummin_input); # say '@cummin_input # of elements = ' . scalar @cummin_input; my @cummin = cummin(\@cummin_input); undef @cummin_input; my @pmin = pmin(\@cummin); @qvalues = @pmin[@ro]; } elsif ($method eq 'bonferroni') { for (my $index = 0; $index < $n; $index++) { my $q = @$pvalues_ref[$index]*$n; if ((0 <= $q) && ($q < 1)) { $qvalues[$index] = $q; } elsif ($q >= 1) { $qvalues[$index] = 1.0; } else { say 'Failed to get Bonferroni adjusted p.'; die; } } } elsif ($method eq 'holm') { my @o = order($pvalues_ref); my @cummax_input; for (my $index = 0; $index < $n; $index++) { $cummax_input[$index] = ($n - $index) * @$pvalues_ref[$o[$index]]; } my @ro = order(\@o); undef @o; my @cummax = cummax(\@cummax_input); undef @cummax_input; my @pmin = pmin(\@cummax); undef @cummax; @qvalues = @pmin[@ro]; } elsif ($method eq 'hommel') { my @o = order($pvalues_ref); my @p = @$pvalues_ref[@o]; my @ro = order(\@o); undef @o; my (@q, @pa); my $min = $n*$p[0]; for (my $index = 0; $index < $n; $index++) { my $temp = $n*$p[$index] / ($index + 1); $min = min($min, $temp); } for (my $index = 0; $index < $n; $index++) { $pa[$index] = $min;#q <- pa <- rep.int(min(n * p/i), n) $q[$index] = $min;#q <- pa <- rep.int(min(n * p/i), n) } for (my $j = ($n-1); $j >= 2; $j--) { my @ij = 0..($n - $j);#ij <- seq_len(n - j + 1) my $I2_LENGTH = $j - 1; my @i2; for (my $i = 0; $i < $I2_LENGTH; $i++) { $i2[$i] = $n-$j+2+$i-1; #R's indices are 1-based, C's are 0-based, I added the -1 }   my $q1 = $j * $p[$i2[0]] / 2.0; for (my $i = 1; $i < $I2_LENGTH; $i++) {#loop through 2:j my $TEMP_Q1 = $j * $p[$i2[$i]] / (2 + $i); $q1 = min($TEMP_Q1, $q1); } for (my $i = 0; $i < ($n - $j + 1); $i++) {#q[ij] <- pmin(j * p[ij], q1) $q[$ij[$i]] = min( $j*$p[$ij[$i]], $q1); }   for (my $i = 0; $i < $I2_LENGTH; $i++) {#q[i2] <- q[n - j + 1] $q[$i2[$i]] = $q[$n - $j]; }   for (my $i = 0; $i < $n; $i++) {#pa <- pmax(pa, q) if ($pa[$i] < $q[$i]) { $pa[$i] = $q[$i]; } } # printf("j = %zu, pa = \n", j); # double_say(pa, N); }#end j loop @qvalues = @pa[@ro]; } else { print "$method doesn't fit my types.\n"; die } @qvalues } my @pvalues = (4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03);   my %correct_answers = ( 'Benjamini-Hochberg' => [6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02], 'Benjamini-Yekutieli' => [1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02], 'Bonferroni' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01],   'Hochberg' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01], 'Holm' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01],   'Hommel' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01]);     foreach my $method ('Hochberg','Benjamini-Hochberg','Benjamini-Yekutieli', 'Bonferroni', 'Holm', 'Hommel') { print "$method\n"; my @qvalues = p_adjust(\@pvalues, $method); my $error = 0.0; foreach my $q (0..$#qvalues) { $error += abs($qvalues[$q] - $correct_answers{$method}[$q]); } printf("type $method has cumulative error of %g.\n", $error); }  
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Haskell
Haskell
import Data.List (mapAccumL, sort)   order :: Ord a => [[a]] -> [a] order [ms, ns] = snd . mapAccumL yu ls $ ks where ks = zip ms [(0 :: Int) ..] ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks yu ((u, v):us) (_, y) | v == y = (us, u) yu ys (x, _) = (ys, x) go (u:us, ys) (x, y) | u == x = (us, y : ys) go ts _ = ts   task :: [String] -> IO () task ls@[ms, ns] = putStrLn $ "M: " ++ ms ++ " | N: " ++ ns ++ " |> " ++ (unwords . order . map words $ ls)   main :: IO () main = mapM_ task [ ["the cat sat on the mat", "mat cat"] , ["the cat sat on the mat", "cat mat"] , ["A B C A B C A B C", "C A C A"] , ["A B C A B D A B E", "E A D A"] , ["A B", "B"] , ["A B", "B A"] , ["A B B A", "B A"] ]
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Delphi
Delphi
program Optional_parameters;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TRow = TArray<string>;   TOrderingFun = TFunc<TRow, TRow, Boolean>;   TTable = array of TRow;   TRowHelper = record helper for TRow public procedure Swap(var other: TRow); function ToString: string; function Length: Integer; end;   TTableHelper = record helper for TTable private procedure ExchangeRow(i, j: Integer); public procedure Sort(OrderingFun: TOrderingFun); procedure Reverse; function ToString: string; end;   function Max(a, b: Integer): Integer; begin if a > b then exit(a); Result := b; end;   { TRowHelper }   function TRowHelper.Length: Integer; begin Result := System.Length(self); end;   procedure TRowHelper.Swap(var other: TRow); var aLengthOther, aLengthSelf, aLength: Integer; tmp: string; i: Integer; begin aLengthOther := other.Length; aLengthSelf := self.Length; aLength := max(aLengthOther, aLengthSelf); if aLength = 0 then exit;   SetLength(self, aLength); SetLength(other, aLength);   for i := 0 to aLength - 1 do begin tmp := self[i]; self[i] := other[i]; other[i] := tmp; end;   SetLength(self, aLengthOther); SetLength(other, aLengthSelf); end;   function TRowHelper.ToString: string; var i: Integer; begin Result := '['; for i := 0 to High(self) do begin if i > 0 then Result := Result + ', '; Result := Result + '"' + self[i] + '"'; end; Result := Result + ']'; end;   { TTableHelper }   procedure TTableHelper.ExchangeRow(i, j: Integer); begin Self[i].Swap(self[j]); end;   procedure TTableHelper.reverse; var aLength, aHalfLength: Integer; i: Integer; begin aLength := Length(self); aHalfLength := aLength div 2; for i := 0 to aHalfLength - 1 do ExchangeRow(i, aLength - i - 1); end;   procedure TTableHelper.Sort(OrderingFun: TOrderingFun); var i, j, aLength: Integer; begin if not Assigned(OrderingFun) then exit;   aLength := Length(self); for i := 0 to aLength - 2 do for j := i + 1 to aLength - 1 do if OrderingFun(self[i], self[j]) then ExchangeRow(i, j); end;   function TTableHelper.ToString: string; var i: Integer; begin Result := '['; for i := 0 to High(self) do begin if i > 0 then Result := Result + #10; Result := Result + self[i].ToString; end; Result := Result + ']'; end;   function SortTable(table: TTable; Ordering: TOrderingFun = nil; column: Integer = 0; reverse: Boolean = false): TTable; var acolumn: Integer; begin acolumn := column; if not Assigned(Ordering) then Ordering := function(left, right: TRow): Boolean begin Result := left[acolumn] > right[acolumn]; end;   table.Sort(Ordering); if (reverse) then table.reverse(); Result := table; end;   var data: TTable = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']];   begin Writeln(data.ToString, #10); Writeln(SortTable(data).ToString, #10); Writeln(SortTable(data).ToString, #10); Writeln(SortTable(data, nil, 2).ToString, #10); Writeln(SortTable(data, nil, 1).ToString, #10); Writeln(SortTable(data, nil, 1, True).ToString, #10); Writeln(SortTable(data, function(left, right: TRow): Boolean begin Result := left.Length > right.Length; end).ToString, #10); Readln; end.
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#C
C
int list_cmp(int *a, int la, int *b, int lb) { int i, l = la; if (l > lb) l = lb; for (i = 0; i < l; i++) { if (a[i] == b[i]) continue; return (a[i] > b[i]) ? 1 : -1; } if (la == lb) return 0; return la > lb ? 1 : -1; }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Turing
Turing
proc pascal (n : int) for i : 0 .. n var c := 1 for k : 0 .. i put c : 4 .. c := c * (i - k) div (k + 1) end for put "" end for end pascal   pascal(5)
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Go
Go
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Haskell
Haskell
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Icon_and_Unicon
Icon and Unicon
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation  ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab  ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#E
E
pragma.enable("accumulator")   def words := <http://www.puzzlers.org/pub/wordlists/unixdict.txt>.getText().split("\n") def ordered := accum [] for word ? (word.sort() <=> word) in words { _.with(word) } def maxLen := accum 0 for word in ordered { _.max(word.size()) } def maxOrderedWords := accum [] for word ? (word.size() <=> maxLen) in ordered { _.with(word) } println(" ".rjoin(maxOrderedWords))
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#NewLISP
NewLISP
  (define (palindrome? s) (setq r s) (reverse r) ; Reverse is destructive. (= s r))   ;; Make ‘reverse’ non-destructive and avoid a global variable (define (palindrome? s) (= s (reverse (copy s))))  
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Julia
Julia
// version 1.2.31   import java.io.File import java.security.SecureRandom   const val CHARS_PER_LINE = 48 const val CHUNK_SIZE = 6 const val COLS = 8 const val DEMO = true // would normally be set to false   enum class FileType { OTP, ENC, DEC }   fun Char.isAlpha() = this in 'A'..'Z'   fun String.toAlpha() = this.filter { it.isAlpha() }   fun String.isOtpRelated() = endsWith(".1tp") || endsWith(".1tp_cpy") || endsWith(".1tp_enc") || endsWith(".1tp_dec")   fun makePad(nLines: Int): String { val nChars = nLines * CHARS_PER_LINE val sr = SecureRandom() val sb = StringBuilder(nChars) /* generate random upper case letters */ for (i in 0 until nChars) sb.append((sr.nextInt(26) + 65).toChar()) return sb.toString().inChunks(nLines, FileType.OTP) }   fun vigenere(text: String, key: String, encrypt: Boolean = true): String { val sb = StringBuilder(text.length) for ((i, c) in text.withIndex()) { val ci = if (encrypt) (c.toInt() + key[i].toInt() - 130) % 26 else (c.toInt() - key[i].toInt() + 26) % 26 sb.append((ci + 65).toChar()) } val temp = sb.length % CHARS_PER_LINE if (temp > 0) { // pad with random characters so each line is a full one val sr = SecureRandom() for (i in temp until CHARS_PER_LINE) sb.append((sr.nextInt(26) + 65).toChar()) } val ft = if (encrypt) FileType.ENC else FileType.DEC return sb.toString().inChunks(sb.length / CHARS_PER_LINE, ft) }   fun String.inChunks(nLines: Int, ft: FileType): String { val chunks = this.chunked(CHUNK_SIZE) val sb = StringBuilder(this.length + nLines * (COLS + 1)) for (i in 0 until nLines) { val j = i * COLS sb.append(" ${chunks.subList(j, j + COLS).joinToString(" ")}\n") } val s = " file\n" + sb.toString() return when (ft) { FileType.OTP -> "# OTP" + s FileType.ENC -> "# Encrypted" + s FileType.DEC -> "# Decrypted" + s } }   fun menu(): Int { println(""" | |1. Create one time pad file. | |2. Delete one time pad file. | |3. List one time pad files. | |4. Encrypt plain text. | |5. Decrypt cipher text. | |6. Quit program. | """.trimMargin()) var choice: Int? do { print("Your choice (1 to 6) : ") choice = readLine()!!.toIntOrNull() } while (choice == null || choice !in 1..6) return choice }   fun main(args: Array<String>) { mainLoop@ while (true) { val choice = menu() println() when (choice) { 1 -> { // Create OTP println("Note that encrypted lines always contain 48 characters.\n") print("OTP file name to create (without extension) : ") val fileName = readLine()!! + ".1tp" var nLines: Int?   do { print("Number of lines in OTP (max 1000) : ") nLines = readLine()!!.toIntOrNull() } while (nLines == null || nLines !in 1..1000)   val key = makePad(nLines) File(fileName).writeText(key) println("\n'$fileName' has been created in the current directory.") if (DEMO) { // a copy of the OTP file would normally be on a different machine val fileName2 = fileName + "_cpy" // copy for decryption File(fileName2).writeText(key) println("'$fileName2' has been created in the current directory.") println("\nThe contents of these files are :\n") println(key) } }   2 -> { // Delete OTP println("Note that this will also delete ALL associated files.\n") print("OTP file name to delete (without extension) : ") val toDelete1 = readLine()!! + ".1tp" val toDelete2 = toDelete1 + "_cpy" val toDelete3 = toDelete1 + "_enc" val toDelete4 = toDelete1 + "_dec" val allToDelete = listOf(toDelete1, toDelete2, toDelete3, toDelete4) var deleted = 0 println() for (name in allToDelete) { val f = File(name) if (f.exists()) { f.delete() deleted++ println("'$name' has been deleted from the current directory.") } } if (deleted == 0) println("There are no files to delete.") }   3 -> { // List OTPs println("The OTP (and related) files in the current directory are:\n") val otpFiles = File(".").listFiles().filter { it.isFile() && it.name.isOtpRelated() }.map { it.name }.toMutableList() otpFiles.sort() println(otpFiles.joinToString("\n")) }   4 -> { // Encrypt print("OTP file name to use (without extension) : ") val keyFile = readLine()!! + ".1tp" val kf = File(keyFile) if (kf.exists()) { val lines = File(keyFile).readLines().toMutableList() var first = lines.size for (i in 0 until lines.size) { if (lines[i].startsWith(" ")) { first = i break } } if (first == lines.size) { println("\nThat file has no unused lines.") continue@mainLoop } val lines2 = lines.drop(first) // get rid of comments and used lines   println("Text to encrypt :-\n") val text = readLine()!!.toUpperCase().toAlpha() val len = text.length var nLines = len / CHARS_PER_LINE if (len % CHARS_PER_LINE > 0) nLines++   if (lines2.size >= nLines) { val key = lines2.take(nLines).joinToString("").toAlpha() val encrypted = vigenere(text, key) val encFile = keyFile + "_enc" File(encFile).writeText(encrypted) println("\n'$encFile' has been created in the current directory.") for (i in first until first + nLines) { lines[i] = "-" + lines[i].drop(1) } File(keyFile).writeText(lines.joinToString("\n")) if (DEMO) { println("\nThe contents of the encrypted file are :\n") println(encrypted) } } else println("Not enough lines left in that file to do encryption") } else println("\nThat file does not exist.") }   5 -> { // Decrypt print("OTP file name to use (without extension) : ") val keyFile = readLine()!! + ".1tp_cpy" val kf = File(keyFile) if (kf.exists()) { val keyLines = File(keyFile).readLines().toMutableList() var first = keyLines.size for (i in 0 until keyLines.size) { if (keyLines[i].startsWith(" ")) { first = i break } } if (first == keyLines.size) { println("\nThat file has no unused lines.") continue@mainLoop } val keyLines2 = keyLines.drop(first) // get rid of comments and used lines   val encFile = keyFile.dropLast(3) + "enc" val ef = File(encFile) if (ef.exists()) { val encLines = File(encFile).readLines().drop(1) // exclude comment line val nLines = encLines.size if (keyLines2.size >= nLines) { val encrypted = encLines.joinToString("").toAlpha() val key = keyLines2.take(nLines).joinToString("").toAlpha() val decrypted = vigenere(encrypted, key, false) val decFile = keyFile.dropLast(3) + "dec" File(decFile).writeText(decrypted) println("\n'$decFile' has been created in the current directory.") for (i in first until first + nLines) { keyLines[i] = "-" + keyLines[i].drop(1) } File(keyFile).writeText(keyLines.joinToString("\n")) if (DEMO) { println("\nThe contents of the decrypted file are :\n") println(decrypted) } } else println("Not enough lines left in that file to do decryption") } else println("\n'$encFile' is missing.") } else println("\nThat file does not exist.") }   else -> return // Quit } } }
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Phix
Phix
with javascript_semantics function ownCalcPass(atom pwd, string nonce) bool start = true atom num1 = 0, num2 = 0 for i=1 to length(nonce) do integer c = nonce[i] if c!='0' and start then num2 = pwd start = false end if switch c do case '1': num1 = shift_bits(num2,7) num2 = shift_bits(num2,-25) case '2': num1 = shift_bits(num2,4) num2 = shift_bits(num2,-28) case '3': num1 = shift_bits(num2,3) num2 = shift_bits(num2,-29) case '4': num1 = shift_bits(num2,-1) num2 = shift_bits(num2,31) case '5': num1 = shift_bits(num2,-5) num2 = shift_bits(num2,27) case '6': num1 = shift_bits(num2,-12) num2 = shift_bits(num2,20) case '7': num1 = or_bits(and_bits(num2,0x0000FF00), or_bits(shift_bits(and_bits(num2,0x000000FF),-24), shift_bits(and_bits(num2,0x00FF0000),16))) num2 = shift_bits(and_bits(num2,0xFF000000),8) case '8': num1 = or_bits(shift_bits(and_bits(num2,0x0000FFFF),-16), shift_bits(num2,24)) num2 = shift_bits(and_bits(num2,0x00FF0000),8) case '9': num1 = not_bits(num2) default: num1 = num2 end switch if c!='0' and c!='9' then num1 = or_bits(num1,num2) end if num2 = num1 end for if num1<0 then num1 += #1_0000_0000 end if return num1 end function procedure testPasswordCalc(atom pwd, string nonce, atom expected) atom res := ownCalcPass(pwd, nonce) string pf = iff(res=expected?"PASS":"FAIL") printf(1,"%s  %d  %s  %-10d  %-10d\n", {pf, pwd, nonce, res, expected}) end procedure testPasswordCalc(12345, "603356072", 25280520) testPasswordCalc(12345, "410501656", 119537670) testPasswordCalc(12345, "630292165", 4269684735) testPasswordCalc(12345, "523781130", 537331200)
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#C.23
C#
using OpenTK; using OpenTK.Graphics; namespace OpenGLTest { class Program { static void Main(string[] args) { //Create the OpenGL window GameWindow window = new GameWindow(640, 480, GraphicsMode.Default, "OpenGL Example");   GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0); GL.MatrixMode(MatrixMode.Modelview);   //Add event handler to render to the window when called window.RenderFrame += new RenderFrameEvent(a_RenderFrame); //Starts the window's updating/rendering events window.Run(); } static void a_RenderFrame(GameWindow sender, RenderFrameEventArgs e) { GL.ClearColor(0.3f, 0.3f, 0.3f, 0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);   GL.ShadeModel(ShadingModel.Smooth);   GL.LoadIdentity(); GL.Translate(-15.0f, -15.0f, 0.0f);   GL.Begin(BeginMode.Triangles); GL.Color3(1.0f, 0.0f, 0.0f); GL.Vertex2(0.0f, 0.0f); GL.Color3(0.0f, 1.0f, 0.0f); GL.Vertex2(30f, 0.0f); GL.Color3(0.0f, 0.0f, 1.0f); GL.Vertex2(0.0f, 30.0f); GL.End(); //Swaps the buffers on the window so that what we draw becomes visible sender.SwapBuffers(); } } }
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#Aime
Aime
one_of_n(integer n) { integer i, r;   i = r = 0; while ((r += 1) < n) { i = drand(r) ? i : r; }   i; }   main(void) { integer i; index x;   i = 1000000; do { x[one_of_n(10)] += 1; } while (i -= 1);   x.ucall(o_winteger, 1, 7); o_newline();   0; }
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#ALGOL_68
ALGOL 68
BEGIN INT max lines = 10; CO Should be read from a file. CO [max lines]INT stats; FOR i TO max lines DO stats[i] := 0 OD; first random (42); CO Should have rather more entropy! CO PROC one of n = (INT n) INT : BEGIN INT result := 1; FOR i TO n DO (random < 1/i | result := i) OD; result END; TO 1000000 DO stats[one of n (max lines)] +:= 1 OD; print (("Line Number times chosen", newline)); FOR i TO max lines DO printf (($g(0)7xg(0)l$, i, stats[i])) OD END
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#Phix
Phix
with javascript_semantics enum UP, DOWN function ratchet(sequence p, integer direction) atom m = p[1] for i=1 to length(p) do if iff(direction=UP?p[i]>m:p[i]<m) then p[i] = m end if m = p[i] end for return sq_min(p,1) end function function schwartzian(sequence p, mult, integer direction) sequence order = custom_sort(p,tagset(length(p))) if direction=UP then order = reverse(order) end if sequence pa = ratchet(sq_mul(mult,extract(p,order)), direction) return extract(pa,order,invert:=true) end function function adjust(sequence p, string method) integer size = length(p) sequence mult = tagset(size) switch method case "Benjamini-Hochberg": mult = sq_div(size,sq_sub(size+1,mult)) return schwartzian(p, mult, UP) case "Benjamini-Yekutieli": atom q = sum(sq_div(1,mult)) mult = sq_div(q*size,sq_sub(size+1,mult)) return schwartzian(p, mult, UP) case "Bonferroni": return sq_min(sq_mul(p,size),1) case "Hochberg": return schwartzian(p, mult, UP) case "Holm": mult = sq_sub(size+1,mult) return schwartzian(p, mult, DOWN) case "Hommel": sequence ivdx = repeat(0,size) for i=1 to size do ivdx[i] = {p[i],i} end for ivdx = sort(ivdx) sequence s = vslice(ivdx,1), m = sq_div(sq_mul(s,size),mult), qh = repeat(min(m),size), pa = repeat(min(m),size), order = vslice(ivdx,2) for j=size-1 to 2 by -1 do sequence lwr = tagset(size-j+1), upr = sq_add(size-j+1,tagset(j-1)) atom qmin = j*s[upr[1]]/2 for i=2 to length(upr) do qmin = min(s[upr[i]]*j/(i+1),qmin) end for for i=1 to length(lwr) do qh[lwr[i]] = min(s[lwr[i]]*j, qmin) end for for i=1 to length(upr) do qh[upr[i]] = qh[size-j+1] end for pa = sq_max(pa,qh) end for return extract(pa,order,invert:=true) case "Sidak": p = deep_copy(p) for i=1 to length(p) do p[i] = 1 - power(1-p[i],size) end for return p else return {} -- (unknown method) end switch return p end function constant {types,correct_answers} = columnize({ {"Benjamini-Hochberg", {6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02}}, {"Benjamini-Yekutieli", {1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02}}, {"Bonferroni", {1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01}}, {"Hochberg", {9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01}}, {"Holm", {1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01}}, {"Hommel", {9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01}}, {"Sidak", {1.0000000000, 1.0000000000, 0.9946598274, 0.9914285749, 0.9999515274, 1.0000000000, 0.9999999688, 1.0000000000, 1.0000000000, 1.0000000000, 1.0000000000, 1.0000000000, 0.9999999995, 1.0000000000, 0.9999998801, 1.0000000000, 1.0000000000, 1.0000000000, 0.9999999855, 0.9231179729, 0.9999999956, 1.0000000000, 1.0000000000, 0.9999317605, 1.0000000000, 0.9983109511, 1.0000000000, 0.5068253940, 1.0000000000, 0.9703301333, 0.1832692440, 0.0150545753, 0.4320729669, 0.6993672225, 0.0286818157, 0.0152621104, 0.3391808707, 0.0656206307, 0.4959194266, 0.0186503726, 0.0009001752, 0.0000125222, 0.8142104886, 0.3772612062, 0.0430222116, 0.0108312558, 0.0473319661, 0.0032997780, 0.7705015898, 0.2499384839}}}) -- {"Unknown",{1}}}) constant pValues = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} if length(pValues)=0 or min(pValues)<0 or max(pValues)>1 then crash("p-values must be in range 0.0 to 1.0") end if for i=1 to length(types) do string ti = types[i] sequence res = adjust(pValues,ti) if res={} then printf(1,"\nSorry, do not know how to do %s correction.\n"& "Perhaps you want one of these?:\n  %s\n", {ti,join(types[1..$-1],"\n ")}) exit end if -- printf(1,"%s\n",{ti}) -- res = correct_answers[i] -- (for easier comparison only) -- pp(res,{pp_FltFmt,"%13.10f",pp_IntFmt,"%13.10f",pp_Maxlen,75,pp_Pause,0}) atom error = sum(sq_abs(sq_sub(res,correct_answers[i]))) printf(1,"%s has cumulative error of %g\n", {ti,error}) end for
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every write(" -> ",odli("the cat sat on the mat","mat cat")) every write(" -> ",odli("the cat sat on the mat","cat mat")) every write(" -> ",odli("A B C A B C A B C","C A C A")) every write(" -> ",odli("A B C A B D A B E","E A D A")) every write(" -> ",odli("A B","B")) every write(" -> ",odli("A B","B A")) every write(" -> ",odli("A B B A","B A")) end   procedure odli(M,N) writes(M," :: ",N) Mp := "" P := N ||:= " " (M||" ") ? while item := tab(upto(' '))||move(1) do { if find(item,P) then { P ?:= 1(tab(find(item)),move(*item))||tab(0) N ?:= (item := tab(upto(' '))||move(1), tab(0)) } Mp ||:= item } return Mp end
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#E
E
def defaultOrdering(a, b) { return a.op__cmp(b) }   def sort {   to run(table) { return sort(table, 0, false, defaultOrdering) } to run(table, column) { return sort(table, column, false, defaultOrdering) } to run(table, column, reverse) { return sort(table, column, reverse, defaultOrdering) }   to run(table :List[List[String]], column :int, reverse :boolean, ordering) { return table.sort(fn a, b { def ord := ordering(a[column], b[column]) if (reverse) { -ord } else { ord } }) }   }
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#C.23
C#
namespace RosettaCode.OrderTwoNumericalLists { using System; using System.Collections.Generic;   internal static class Program { private static bool IsLessThan(this IEnumerable<int> enumerable, IEnumerable<int> otherEnumerable) { using ( IEnumerator<int> enumerator = enumerable.GetEnumerator(), otherEnumerator = otherEnumerable.GetEnumerator()) { while (true) { if (!otherEnumerator.MoveNext()) { return false; }   if (!enumerator.MoveNext()) { return true; }   if (enumerator.Current == otherEnumerator.Current) { continue; }   return enumerator.Current < otherEnumerator.Current; } } }   private static void Main() { Console.WriteLine( new[] {1, 2, 1, 3, 2}.IsLessThan(new[] {1, 2, 0, 4, 4, 0, 0, 0})); } } }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#TypeScript
TypeScript
// Pascal's triangle   function pascal(n: number): void { // Display the first n rows of Pascal's triangle // if n<=0 then nothing is displayed var ld: number[] = new Array(40); // Old var nw: number[] = new Array(40); // New for (var row = 0; row < n; row++) { nw[0] = 1; for (var i = 1; i <= row; i++) nw[i] = ld[i - 1] + ld[i]; process.stdout.write(" ".repeat((n - row - 1) * 2)); for (var i = 0; i <= row; i++) { if (nw[i] < 100) process.stdout.write(" "); process.stdout.write(nw[i].toString()); if (nw[i] < 10) process.stdout.write(" "); process.stdout.write(" "); } nw[row + 1] = 0; // We do not copy data from nw to ld // but we work with references. var tmp = ld; ld = nw; nw = tmp; console.log(); } }   pascal(13);  
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#J
J
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Java
Java
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#JavaScript
JavaScript
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#EchoLisp
EchoLisp
  (define (ordered? str) (for/and ([i (in-range 1 (string-length str))]) (string-ci<=? (string-ref str (1- i)) (string-ref str i))))   (define (ordre words) (define wl 0) (define s 's) (for/fold (len 0) ((w words)) (set! wl (string-length w)) #:continue (< wl len) #:when (ordered? w) #:continue (and (= len wl) (push s w)) (push (stack s) w) ;; start a new list of length wl wl) (stack->list s))   ;; output (load 'unixdict) (ordre (text-parse unixdict)) → (abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty)   ;; with the dictionaries provided with EchoLisp ;; french → (accentué) ;; ordered, longest, and ... self-reference ;; english → (Adelops alloquy beefily begorry billowy egilops)  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import unicode     func isPalindrome(rseq: seq[Rune]): bool = ## Return true if a sequence of runes is a palindrome. for i in 1..(rseq.len shr 1): if rseq[i - 1] != rseq[^i]: return false result = true     func isPalindrome(str: string; exact = true): bool {.inline.} = ## Return true if a UTF-8 string is a palindrome. ## If "exact" is false, ignore white spaces and ignore case.   if exact: result = str.toRunes.isPalindrome() else: var rseq: seq[Rune] for rune in str.runes: if not rune.isWhiteSpace: rseq.add rune.toLower result = rseq.isPalindrome()     when isMainModule:   proc check(s: string) = var exact, inexact: bool exact = s.isPalindrome() if not exact: inexact = s.isPalindrome(exact = false) let txt = if exact: " is an exact palindrome." elif inexact: " is an inexact palindrome." else: " is not a palindrome." echo '"', s, '"', txt   check "rotor" check "été" check "αννα" check "salà las" check "In girum imus nocte et consumimur igni" check "Esope reste ici et se repose" check "This is a palindrom"
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Kotlin
Kotlin
// version 1.2.31   import java.io.File import java.security.SecureRandom   const val CHARS_PER_LINE = 48 const val CHUNK_SIZE = 6 const val COLS = 8 const val DEMO = true // would normally be set to false   enum class FileType { OTP, ENC, DEC }   fun Char.isAlpha() = this in 'A'..'Z'   fun String.toAlpha() = this.filter { it.isAlpha() }   fun String.isOtpRelated() = endsWith(".1tp") || endsWith(".1tp_cpy") || endsWith(".1tp_enc") || endsWith(".1tp_dec")   fun makePad(nLines: Int): String { val nChars = nLines * CHARS_PER_LINE val sr = SecureRandom() val sb = StringBuilder(nChars) /* generate random upper case letters */ for (i in 0 until nChars) sb.append((sr.nextInt(26) + 65).toChar()) return sb.toString().inChunks(nLines, FileType.OTP) }   fun vigenere(text: String, key: String, encrypt: Boolean = true): String { val sb = StringBuilder(text.length) for ((i, c) in text.withIndex()) { val ci = if (encrypt) (c.toInt() + key[i].toInt() - 130) % 26 else (c.toInt() - key[i].toInt() + 26) % 26 sb.append((ci + 65).toChar()) } val temp = sb.length % CHARS_PER_LINE if (temp > 0) { // pad with random characters so each line is a full one val sr = SecureRandom() for (i in temp until CHARS_PER_LINE) sb.append((sr.nextInt(26) + 65).toChar()) } val ft = if (encrypt) FileType.ENC else FileType.DEC return sb.toString().inChunks(sb.length / CHARS_PER_LINE, ft) }   fun String.inChunks(nLines: Int, ft: FileType): String { val chunks = this.chunked(CHUNK_SIZE) val sb = StringBuilder(this.length + nLines * (COLS + 1)) for (i in 0 until nLines) { val j = i * COLS sb.append(" ${chunks.subList(j, j + COLS).joinToString(" ")}\n") } val s = " file\n" + sb.toString() return when (ft) { FileType.OTP -> "# OTP" + s FileType.ENC -> "# Encrypted" + s FileType.DEC -> "# Decrypted" + s } }   fun menu(): Int { println(""" | |1. Create one time pad file. | |2. Delete one time pad file. | |3. List one time pad files. | |4. Encrypt plain text. | |5. Decrypt cipher text. | |6. Quit program. | """.trimMargin()) var choice: Int? do { print("Your choice (1 to 6) : ") choice = readLine()!!.toIntOrNull() } while (choice == null || choice !in 1..6) return choice }   fun main(args: Array<String>) { mainLoop@ while (true) { val choice = menu() println() when (choice) { 1 -> { // Create OTP println("Note that encrypted lines always contain 48 characters.\n") print("OTP file name to create (without extension) : ") val fileName = readLine()!! + ".1tp" var nLines: Int?   do { print("Number of lines in OTP (max 1000) : ") nLines = readLine()!!.toIntOrNull() } while (nLines == null || nLines !in 1..1000)   val key = makePad(nLines) File(fileName).writeText(key) println("\n'$fileName' has been created in the current directory.") if (DEMO) { // a copy of the OTP file would normally be on a different machine val fileName2 = fileName + "_cpy" // copy for decryption File(fileName2).writeText(key) println("'$fileName2' has been created in the current directory.") println("\nThe contents of these files are :\n") println(key) } }   2 -> { // Delete OTP println("Note that this will also delete ALL associated files.\n") print("OTP file name to delete (without extension) : ") val toDelete1 = readLine()!! + ".1tp" val toDelete2 = toDelete1 + "_cpy" val toDelete3 = toDelete1 + "_enc" val toDelete4 = toDelete1 + "_dec" val allToDelete = listOf(toDelete1, toDelete2, toDelete3, toDelete4) var deleted = 0 println() for (name in allToDelete) { val f = File(name) if (f.exists()) { f.delete() deleted++ println("'$name' has been deleted from the current directory.") } } if (deleted == 0) println("There are no files to delete.") }   3 -> { // List OTPs println("The OTP (and related) files in the current directory are:\n") val otpFiles = File(".").listFiles().filter { it.isFile() && it.name.isOtpRelated() }.map { it.name }.toMutableList() otpFiles.sort() println(otpFiles.joinToString("\n")) }   4 -> { // Encrypt print("OTP file name to use (without extension) : ") val keyFile = readLine()!! + ".1tp" val kf = File(keyFile) if (kf.exists()) { val lines = File(keyFile).readLines().toMutableList() var first = lines.size for (i in 0 until lines.size) { if (lines[i].startsWith(" ")) { first = i break } } if (first == lines.size) { println("\nThat file has no unused lines.") continue@mainLoop } val lines2 = lines.drop(first) // get rid of comments and used lines   println("Text to encrypt :-\n") val text = readLine()!!.toUpperCase().toAlpha() val len = text.length var nLines = len / CHARS_PER_LINE if (len % CHARS_PER_LINE > 0) nLines++   if (lines2.size >= nLines) { val key = lines2.take(nLines).joinToString("").toAlpha() val encrypted = vigenere(text, key) val encFile = keyFile + "_enc" File(encFile).writeText(encrypted) println("\n'$encFile' has been created in the current directory.") for (i in first until first + nLines) { lines[i] = "-" + lines[i].drop(1) } File(keyFile).writeText(lines.joinToString("\n")) if (DEMO) { println("\nThe contents of the encrypted file are :\n") println(encrypted) } } else println("Not enough lines left in that file to do encryption") } else println("\nThat file does not exist.") }   5 -> { // Decrypt print("OTP file name to use (without extension) : ") val keyFile = readLine()!! + ".1tp_cpy" val kf = File(keyFile) if (kf.exists()) { val keyLines = File(keyFile).readLines().toMutableList() var first = keyLines.size for (i in 0 until keyLines.size) { if (keyLines[i].startsWith(" ")) { first = i break } } if (first == keyLines.size) { println("\nThat file has no unused lines.") continue@mainLoop } val keyLines2 = keyLines.drop(first) // get rid of comments and used lines   val encFile = keyFile.dropLast(3) + "enc" val ef = File(encFile) if (ef.exists()) { val encLines = File(encFile).readLines().drop(1) // exclude comment line val nLines = encLines.size if (keyLines2.size >= nLines) { val encrypted = encLines.joinToString("").toAlpha() val key = keyLines2.take(nLines).joinToString("").toAlpha() val decrypted = vigenere(encrypted, key, false) val decFile = keyFile.dropLast(3) + "dec" File(decFile).writeText(decrypted) println("\n'$decFile' has been created in the current directory.") for (i in first until first + nLines) { keyLines[i] = "-" + keyLines[i].drop(1) } File(keyFile).writeText(keyLines.joinToString("\n")) if (DEMO) { println("\nThe contents of the decrypted file are :\n") println(decrypted) } } else println("Not enough lines left in that file to do decryption") } else println("\n'$encFile' is missing.") } else println("\nThat file does not exist.") }   else -> return // Quit } } }
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#PHP
PHP
function ownCalcPass($password, $nonce) { $msr = 0x7FFFFFFF; $m_1 = (int)0xFFFFFFFF; $m_8 = (int)0xFFFFFFF8; $m_16 = (int)0xFFFFFFF0; $m_128 = (int)0xFFFFFF80; $m_16777216 = (int)0xFF000000; $flag = True; $num1 = 0; $num2 = 0;   foreach (str_split($nonce) as $c) { $num1 = $num1 & $m_1; $num2 = $num2 & $m_1; if ($c == '1') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_128; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 6; $num2 = $num2 << 25; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '2') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_16; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 3; $num2 = $num2 << 28; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '3') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_8; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 2; $num2 = $num2 << 29; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '4') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 1; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 30; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '5') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 5; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 26; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '6') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 12; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 19; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '7') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFF00; $num1 = $num1 + (( $num2 & 0xFF ) << 24 ); $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 ); $num2 = $num2 & $m_16777216; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '8') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFFFF; $num1 = $num1 << 16; $numx = $num2 >> 1; $numx = $numx & $msr; $numx = $numx >> 23; $num1 = $num1 + $numx; $num2 = $num2 & 0xFF0000; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '9') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = ~(int)$num2; $flag = False; } else { $num1 = $num2; } $num2 = $num1; } return sprintf('%u', $num1 & $m_1); }  
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: vershoks, arshins, sazhens, versts, meters, centimeters and kilometers. Also see   Old Russian measure of length
#11l
11l
V unit2mult = [‘arshin’ = 0.7112, ‘centimeter’ = 0.01, ‘diuym’ = 0.0254, ‘fut’ = 0.3048, ‘kilometer’ = 1000.0, ‘liniya’ = 0.00254, ‘meter’ = 1.0, ‘milia’ = 7467.6, ‘piad’ = 0.1778, ‘sazhen’ = 2.1336, ‘tochka’ = 0.000254, ‘vershok’ = 0.04445, ‘versta’ = 1066.8]   :start: assert(:argv.len == 3, ‘ERROR. Need two arguments - number then units’) Float value X.try value = Float(:argv[1]) X.catch exit(‘ERROR. First argument must be a (float) number’) V unit = :argv[2] assert(unit C unit2mult, ‘ERROR. Only know the following units: ’unit2mult.keys().join(‘ ’))   print(‘#. #. to:’.format(value, unit)) L(unt, mlt) sorted(unit2mult.items()) print(‘ #10: #.’.format(unt, value * unit2mult[unit] / mlt))
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Clojure
Clojure
(use 'penumbra.opengl) (require '[penumbra.app :as app])   (defn init [state] (app/title! "Triangle") (clear-color 0.3 0.3 0.3 0) (shade-model :smooth) state)   (defn reshape [[x y w h] state] (ortho-view -30 30 -30 30 -30 30) (load-identity) (translate -15 -15) state)   (defn display [[dt time] state] (draw-triangles (color 1 0 0) (vertex 0 0) (color 0 1 0) (vertex 30 0) (color 0 0 1) (vertex 0 30)))   (app/start {:display display, :reshape reshape, :init init} {})
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#Applesoft_BASIC
Applesoft BASIC
10 I = RND(0) : REMRANDOM SEED   20 FOR J = 1 TO 1000000 : REMMAYBE TRY 100 ON A 1MHZ APPLE II 30 N = 10 : GOSUB 100"ONE_OF_N 40 C(C) = C(C) + 1 50 NEXT   60 FOR J = 1 TO 10 70 PRINT J, C(J) 80 NEXT 90 END   100 REMONE_OF_N 110 FOR I = 1 TO N 120 IF INT(RND(1) * I) = 0 THEN C = I 130 NEXT I 140 RETURN
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#Arturo
Arturo
oneOfN: function [n][ result: 0 loop 0..dec n 'x [ if zero? random 0 x -> result: x ] return result ]   oneOfNTest: function [n,trials][ ret: array.of:n 0 if n > 0 [ loop 1..trials 'i [ oon: oneOfN n ret\[oon]: ret\[oon] + 1 ] ] return ret ]   print oneOfNTest 10 1000000
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#Python
Python
from __future__ import division import sys   def pminf(array): x = 1 pmin_list = [] N = len(array) for index in range(N): if array[index] < x: pmin_list.insert(index, array[index]) else: pmin_list.insert(index, x) return pmin_list #end function   def cumminf(array): cummin = [] cumulative_min = array[0] for p in array: if p < cumulative_min: cumulative_min = p cummin.append(cumulative_min) return cummin #end   def cummaxf(array): cummax = [] cumulative_max = array[0] for e in array: if e > cumulative_max: cumulative_max = e cummax.append(cumulative_max) return cummax #end   def order(*args): if len(args) > 1: if args[1].lower() == 'false':# if ($string1 eq $string2) { return sorted(range(len(args[0])), key = lambda k: args[0][k]) elif list(args[1].lower()) == list('true'): return sorted(range(len(args[0])), key = lambda k: args[0][k], reverse = True) else: print "%s isn't a recognized parameter" % args[1] sys.exit() elif len(args) == 1: return sorted(range(len(args[0])), key = lambda k: args[0][k]) #end   def p_adjust(*args): method = "bh" pvalues = args[0] if len(args) > 1: methods = {"bh", "fdr", "by", "holm", "hommel", "bonferroni", "hochberg"} metharg = arg[1].lower() if metharg in methods: method = metharg lp = len(pvalues) n = lp qvalues = []   if method == 'hochberg':#already all lower case o = order(pvalues, 'TRUE') cummin_input = [] for index in range(n): cummin_input.insert(index, (index+1)*pvalues[o[index]]) cummin = cumminf(cummin_input) pmin = pminf(cummin) ro = order(o) qvalues = [pmin[i] for i in ro] elif method == 'bh': o = order(pvalues, 'TRUE') cummin_input = [] for index in range(n): cummin_input.insert(index, (n/(n-index))* pvalues[o[index]]) ro = order(o) cummin = cumminf(cummin_input) pmin = pminf(cummin) qvalues = [pmin[i] for i in ro] elif method == 'by': q = 0.0 o = order(pvalues, 'TRUE') ro = order(o) for index in range(1, n+1): q += 1.0 / index; cummin_input = [] for index in range(n): cummin_input.insert(index, q * (n/(n-index)) * pvalues[o[index]]) cummin = cumminf(cummin_input) pmin = pminf(cummin) qvalues = [pmin[i] for i in ro] elif method == 'bonferroni': for index in range(n): q = pvalues[index] * n if (0 <= q) and (q < 1): qvalues.insert(index, q) elif q >= 1: qvalues.insert(index, 1) else: print '%g won\'t give a Bonferroni adjusted p' % q sys.exit() elif method == 'holm': o = order(pvalues) cummax_input = [] for index in range(n): cummax_input.insert(index, (n - index) * pvalues[o[index]]) ro = order(o) cummax = cummaxf(cummax_input) pmin = pminf(cummax) qvalues = [pmin[i] for i in ro] elif method == 'hommel': i = range(1,n+1) o = order(pvalues) p = [pvalues[index] for index in o] ro = order(o) pa = [] q = [] smin = n*p[0] for index in range(n): temp = n*p[index] / (index + 1) if temp < smin: smin = temp for index in range(n): pa.insert(index, smin) q.insert(index, smin) for j in range(n-1,1,-1): ij = range(1,n-j+2) for x in range(len(ij)): ij[x] -= 1 I2_LENGTH = j - 1 i2 = [] for index in range(I2_LENGTH+1): i2.insert(index, n - j + 2 + index - 1) q1 = j * p[i2[0]] / 2.0 for index in range(1,I2_LENGTH): TEMP_Q1 = j * p[i2[index]] / (2.0 + index) if TEMP_Q1 < q1: q1 = TEMP_Q1 for index in range(n - j + 1): q[ij[index]] = min(j * p[ij[index]], q1) for index in range(I2_LENGTH): q[i2[index]] = q[n-j] for index in range(n): if pa[index] < q[index]: pa[index] = q[index] qvalues = [pa[index] for index in ro] else: print "method %s isn't defined." % method sys.exit() return qvalues   pvalues = [4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03]   correct_answers = {}   correct_answers['bh'] = [6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01, 9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01, 6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01, 9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01, 4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01, 2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01, 1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03, 2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03, 4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03, 2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02]   correct_answers['by'] = [1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01, 7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02, 1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02, 2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02, 1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02]   correct_answers['bonferroni'] = [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02, 9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01]   correct_answers['hochberg'] = [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01]   correct_answers['holm'] = [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02, 8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01]   correct_answers['hommel'] = [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02, 8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01]   for key in correct_answers.keys(): error = 0.0 q = p_adjust(pvalues, key) for i in range(len(q)): error += abs(q[i] - correct_answers[key][i]) print '%s error = %g' % (key.upper(), error)  
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#J
J
disjorder=:3 :0&.;: : clusters=. (</. i.@#) x order=. x i.&~. y need=. #/.~ y from=. ;need (#{.)each (/:~order){clusters to=. ;need {.!._ each order{clusters (from{x) to} x )
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Java
Java
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils;   public class OrderDisjointItems {   public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}};   for (String[] a : MNs) { String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" ")); System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r)); } }   // if input items cannot be null static String[] orderDisjointItems(String[] m, String[] n) { for (String e : n) { int idx = ArrayUtils.indexOf(m, e); if (idx != -1) m[idx] = null; } for (int i = 0, j = 0; i < m.length; i++) { if (m[i] == null) m[i] = n[j++]; } return m; }   // otherwise static String[] orderDisjointItems2(String[] m, String[] n) { BitSet bitSet = new BitSet(m.length); for (String e : n) { int idx = -1; do { idx = ArrayUtils.indexOf(m, e, idx + 1); } while (idx != -1 && bitSet.get(idx)); if (idx != -1) bitSet.set(idx); } for (int i = 0, j = 0; i < m.length; i++) { if (bitSet.get(i)) m[i] = n[j++]; } return m; } }
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Elixir
Elixir
defmodule Optional_parameters do def sort( table, options\\[] ) do options = options ++ [ ordering: :lexicographic, column: 0, reverse: false ] ordering = options[ :ordering ] column = options[ :column ] reverse = options[ :reverse ] sorted = sort( table, ordering, column ) if reverse, do: Enum.reverse( sorted ), else: sorted end   defp sort( table, :lexicographic, column ) do Enum.sort_by( table, &elem( &1, column ) ) end defp sort( table, :numeric, column ) do Enum.sort_by( table, &elem( &1, column ) |> String.to_integer ) end   def task do table = [ { "123", "456", "0789" }, { "456", "0789", "123" }, { "0789", "123", "456" } ] IO.write "sort defaults "; IO.inspect sort( table ) IO.write " & reverse "; IO.inspect sort( table, reverse: true ) IO.write "sort column 2 "; IO.inspect sort( table, column: 2) IO.write " & reverse "; IO.inspect sort( table, column: 2, reverse: true) IO.write "sort numeric "; IO.inspect sort( table, ordering: :numeric) IO.write " & reverse "; IO.inspect sort( table, ordering: :numeric, reverse: true) end end   Optional_parameters.task
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Erlang
Erlang
  -module( optional_parameters ).   -export( [sort/2, task/0] ).   sort( Table, Options ) -> Ordering = proplists:get_value( ordering, Options, lexicographic ), Column = proplists:get_value( column, Options, 1 ), Is_reverse = proplists:get_value( reverse, Options, false ), Sorted = sort( Table, Ordering, Column ), sorted_reverse( Is_reverse, Sorted ).   task() -> io:fwrite( "sort defaults ~p~n", [sort( table(), [])] ), io:fwrite( "reverse ~p~n", [sort( table(), [reverse])] ), io:fwrite( "sort column 3 ~p~n", [sort( table(), [{column, 3}])] ), io:fwrite( "reverse ~p~n", [sort( table(), [{column, 3}, reverse])] ), io:fwrite( "sort numeric ~p~n", [sort( table(), [{ordering, numeric}])] ), io:fwrite( "reverse ~p~n", [sort( table(), [{ordering, numeric}, reverse])] ).       row_numeric( Tuple ) -> erlang:list_to_tuple( [{erlang:list_to_integer(X), X} || X <- erlang:tuple_to_list(Tuple)] ).   row_remove_numeric( Tuple ) -> erlang:list_to_tuple( [Y || {_X, Y} <- erlang:tuple_to_list(Tuple)] ).   sort( Table, lexicographic, Column ) -> lists:keysort( Column, Table ); sort( Table, numeric, Column ) -> Numeric_table = [row_numeric(X) || X <- Table], Sorted_numeric = lists:keysort( Column, Numeric_table ), [row_remove_numeric(X) || X <- Sorted_numeric].   sorted_reverse( true, Sorted ) -> lists:reverse( Sorted ); sorted_reverse( false, Sorted ) -> Sorted.   table() -> [table_row1(), table_row2(), table_row3()].   table_row1() -> {"123", "456", "0789"}. table_row2() -> {"456", "0789", "123"}. table_row3() -> {"0789", "123", "456"}.  
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#C.2B.2B
C++
#include <iostream> #include <vector>   int main() { std::vector<int> a; a.push_back(1); a.push_back(2); a.push_back(1); a.push_back(3); a.push_back(2); std::vector<int> b; b.push_back(1); b.push_back(2); b.push_back(0); b.push_back(4); b.push_back(4); b.push_back(0); b.push_back(0); b.push_back(0);   std::cout << std::boolalpha << (a < b) << std::endl; // prints "false" return 0; }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#uBasic.2F4tH
uBasic/4tH
Input "Number Of Rows: "; N @(1) = 1 Print Tab((N+1)*3);"1"   For R = 2 To N Print Tab((N-R)*3+1); For I = R To 1 Step -1 @(I) = @(I) + @(I-1) Print Using "______";@(i); Next Next   Print End
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#jq
jq
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Julia
Julia
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Kotlin
Kotlin
  As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence. Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}  
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elixir
Elixir
File.read!("unixdict.txt") |> String.split |> Enum.filter(fn word -> String.codepoints(word) |> Enum.sort |> Enum.join == word end) |> Enum.group_by(fn word -> String.length(word) end) |> Enum.max_by(fn {length,_words} -> length end) |> elem(1) |> Enum.sort |> Enum.each(fn word -> IO.puts word end)
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Erlang
Erlang
  -module( ordered_words ).   -export( [is_ordered/1, task/0] ).   is_ordered( Word ) -> lists:sort( Word ) =:= Word.   task() -> ok = find_unimplemented_tasks:init_http(), Ordered_words = [X || X <- words(), is_ordered(X)], Sorted_longest_length_first = lists:reverse( sort_with_length( Ordered_words ) ), [{Max_length, _Word1} | _T] = Sorted_longest_length_first, Longest_length_first = lists:takewhile( fun({Length, _Word2}) -> Length =:= Max_length end, Sorted_longest_length_first ), [X || {_Length, X} <- Longest_length_first].       sort_with_length( Words ) -> Words_with_length_first = [{erlang:length(X), X} || X <- Words], lists:sort( Words_with_length_first ).   words() -> anagrams_deranged:words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ).  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Objeck
Objeck
  bundle Default { class Test { function : Main(args : String[]) ~ Nil { IsPalindrome("aasa")->PrintLine(); IsPalindrome("acbca")->PrintLine(); IsPalindrome("xx")->PrintLine(); }   function : native : IsPalindrome(s : String) ~ Bool { l := s->Size(); for(i := 0; i < l / 2; i += 1;) { if(s->Get(i) <> s->Get(l - i - 1)) { return false; }; };   return true; } } }  
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Nim
Nim
import os, re, sequtils, strformat, strutils import nimcrypto   # One-time pad file signature. const Magic = "#one-time pad"   # Suffix for pad files. const Suffix = ".1tp"   proc log(msg: string) = ## Log a message. stderr.write msg stderr.write '\n'   proc makeKeys(n, size: Positive): seq[string] = ## Generate "n" secure, random keys of "size" bytes.   # We're generating and storing keys in their hexadecimal form to make # one-time pad files a little more human readable and to ensure a key # can not start with a hyphen. var bytes = newSeq[byte](size) for _ in 1..n: if randomBytes(bytes) != size: raise newException(ValueError, "unable to build keys.") result.add bytes.mapIt(it.toHex).join()   proc makePad(name: string; padSize, keySize: Positive): string = ## Create a new one-time pad identified by the given name. ## Args: ## name: unique one-time pad identifier. ## padSize: the number of keys (or pages) in the pad. ## keySize: the number of bytes per key. ## Returns: ## the new one-time pad as a string.   let pad = @[Magic, &"#name={name}", &"#size={padSize}"] & makeKeys(padSize, keySize) result = pad.join("\n")   proc `xor`(message, key: string): string = ## Return "message" XOR-ed with "key". ## ## Args: ## message: plaintext or cyphertext to be encrypted or decrypted. ## key: encryption and decryption key. ## Returns: ## plaintext or cyphertext as a string.   if key.len < message.len: quit("Key size is too short to encrypt/decrypt the message.", QuitFailure) result = newStringOfCap(message.len) var keyIndex = 0 for msgChar in message: result.add chr(ord(msgChar) xor ord(key[keyIndex])) inc keyIndex   proc useKey(pad: var string): string = ## Use the next available key from the given one-time pad. ## ## Args: ## pad: a one-time pad, updated. ## Returns: ## the key.   var matches: array[1, string] let pos = pad.find(re"(?m)(^[A-F0-9]+$)", matches) if pos < 0: quit("Pad is all used up.", QuitFailure)   pad.insert("-", pos) result = matches[0]   proc writePad(path: string; padSize, keySize: Positive) = ## Write a new one-time pad to the given path. ## ## Args: ## path: path to write one-time pad to. ## padSize: the number of keys (or pages) in the pad. ## keySize: the number of bytes per key.   if fileExists(path): quit("Pad " & path & " already exists", QuitFailure) try: path.writeFile(makePad(path.extractFilename(), padSize, keySize)) except IOError: quit("Unable to write file " & path, QuitFailure) log("New one-time pad written to " & path)   proc process(pad, message: string; outfile: File) = ## Encrypt or decrypt "message" using the given pad. ## ## Args: ## pad: path to one-time pad. ## message: plaintext or ciphertext message to encrypt or decrypt. ## outfile: file-like object to write to.   if not fileExists(pad): quit("No such pad: " & pad, QuitFailure) let start = pad.readLines(1) if start.len == 0 or start[0] != Magic: quit(&"file '{pad}' does not look like a one-time pad", QuitFailure)   # Rewrites the entire one-time pad every time var padData = pad.readFile() let key = padData.useKey().parseHexStr() pad.writeFile(padData)   outfile.write(message xor key)     when isMainModule:   import parseopt   proc printUsage() = echo "Usage: ", getAppFilename().lastPathPart, " [-h] [--length LENGTH] [--key-size KEY_SIZE] [-o OUTFILE]" echo " [--encrypt FILE | --decrypt FILE] pad" echo "" echo """One-time pad.   positional arguments: pad Path to one-time pad. If neither --encrypt or --decrypt are given, will create a new pad.   optional arguments: -h, --help show this help message and exit --length LENGTH Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10. --key-size KEY_SIZE Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64. --outfile OUTFILE Write encoded/decoded message to a file. Ignored if --encrypt or --decrypt is not given. Defaults to stdout. --encrypt FILE Encrypt FILE using the next available key from pad. --decrypt FILE Decrypt FILE using the next available key from pad. """   var parser = initOptParser(shortNoVal = {'h'}, longNoval = @["help"]) padPath: string length = 10 outpath = "" encryptPath = "" decryptPath = "" keySize = 64 encrypt = false decrypt = false   for kind, key, val in parser.getopt(): case kind   of cmdShortOption: printUsage() if key != "h": quit("Wrong option: " & key, QuitFailure) elif val.len != 0: quit("Wrong value for option -h", QuitFailure) else: quit(QuitSuccess)   of cmdLongOption: case key   of "help": printUsage() quit(QuitSuccess)   of "length": try: length = parseInt(val) if length < 2: raise newException(ValueError, "") except ValueError: quit("Wrong length: " & val, QuitFailure)   of "encrypt": encryptPath = val encrypt = true   of "decrypt": decryptPath = val decrypt = true   of "outfile": outPath = val   of "key-size": try: keySize = parseInt(val) if length < 2: raise newException(ValueError, "") except ValueError: quit("Wrong key size: " & val, QuitFailure)   else: quit("Invalid option: " & key, QuitFailure)   of cmdArgument: padPath = if key.endsWith(Suffix): key else: key & Suffix   of cmdEnd: discard # Cannot not occur.   if padPath.len == 0: quit("Missing pad file.", QuitFailure)   if encrypt and decrypt: quit("Incompatible options: encrypt and decrypt", QuitFailure)   if encrypt or decrypt:   var outfile: File if outpath.len == 0: outfile = stdout else: try: outfile = outpath.open(fmWrite) except IOError: quit("Unable to open output file.", QuitFailure)   let message = try: if encrypt: encryptPath.readFile() else: decryptPath.readFile() except IOError: quit("Unable to open file to encrypt or decrypt.", QuitFailure)   padPath.process(message, outfile) if outfile != stdout: outfile.close()   else: padPath.writePad(length, keySize)
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Perl
Perl
# 20200814 added Perl programming solution   use strict; use warnings;   use Crypt::OTP; use Bytes::Random::Secure qw( random_bytes );   print "Message  : ", my $message = "show me the monKey", "\n";   my $otp = random_bytes(length $message); print "Ord(OTP)  : ", ( map { ord($_).' ' } (split //, $otp) ) , "\n";   my $cipher = OTP( $otp, $message, 1 ); print "Ord(Cipher) : ", ( map { ord($_).' ' } (split //, $cipher) ) , "\n";   print "Decoded  : ", OTP( $otp, $cipher, 1 ), "\n";
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Python
Python
  def ownCalcPass (password, nonce, test=False) : start = True num1 = 0 num2 = 0 password = int(password) if test: print("password: %08x" % (password)) for c in nonce : if c != "0": if start: num2 = password start = False if test: print("c: %s num1: %08x num2: %08x" % (c, num1, num2)) if c == '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 elif c == '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 elif c == '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 elif c == '4': num1 = num2 << 1 num2 = num2 >> 31 elif c == '5': num1 = num2 << 5 num2 = num2 >> 27 elif c == '6': num1 = num2 << 12 num2 = num2 >> 20 elif c == '7': num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 ) num2 = ( num2 & 0xFF000000 ) >> 8 elif c == '8': num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 ) num2 = (num2 & 0x00FF0000) >> 8 elif c == '9': num1 = ~num2 else : num1 = num2   num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if (c not in "09"): num1 |= num2 if test: print(" num1: %08x num2: %08x" % (num1, num2)) num2 = num1 return num1   def test_passwd_calc(passwd, nonce, expected): res = ownCalcPass(passwd, nonce, False) m = passwd+' '+nonce+' '+str(res)+' '+str(expected) if res == int(expected) : print('PASS '+m) else : print('FAIL '+m)   if __name__ == '__main__': test_passwd_calc('12345','603356072','25280520') test_passwd_calc('12345','410501656','119537670') test_passwd_calc('12345','630292165','4269684735')    
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: vershoks, arshins, sazhens, versts, meters, centimeters and kilometers. Also see   Old Russian measure of length
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE PTR="CARD" DEFINE UNIT_COUNT="10"   PTR ARRAY names(UNIT_COUNT), values(UNIT_COUNT) BYTE count=[0]   PROC Append(CHAR ARRAY name REAL POINTER value) names(count)=name values(count)=value count==+1 RETURN   PROC Init() REAL arshin,centimeter,kilometer,meter, sazhen,vershok,versta   ValR("0.7112",arshin) Append("arshins",arshin) ValR("0.01",centimeter) Append("centimeters",centimeter) ValR("1000",kilometer) Append("kilometers",kilometer) ValR("1",meter) Append("meters",meter) ValR("2.1336",sazhen) Append("sazhens",sazhen) ValR("0.04445",vershok) Append("vershoks",vershok) ValR("1066.8",versta) Append("versts",versta) RETURN   BYTE FUNC GetUnit() BYTE i,res   FOR i=1 TO count DO PrintF("%B-%S",i,names(i-1)) IF i<count THEN Put(32) FI OD PutE() DO PrintF("Get unit (1-%B): ",count) res=InputB() UNTIL res>=1 AND res<=count OD RETURN (res-1)   PROC PrintResult(REAL POINTER value BYTE unit) BYTE i REAL res,tmp   PutE() FOR i=0 TO count-1 DO IF i=unit THEN RealAssign(value,res) ELSE RealMult(value,values(unit),tmp) RealDiv(tmp,values(i),res) FI Print(" ") PrintR(res) PrintF(" %S%E",names(i)) OD PutE() RETURN   PROC Main() BYTE unit REAL value   Put(125) PutE() ;clear screen Init()   DO Print("Get value: ") InputR(value) unit=GetUnit() PrintResult(value,unit) OD RETURN
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: vershoks, arshins, sazhens, versts, meters, centimeters and kilometers. Also see   Old Russian measure of length
#AppleScript
AppleScript
-- General purpose linear measurement converter. on convertLinear(inputNumber, inputUnitRecord, outputUnitRecord) set {inputType, outputType} to {inputUnitRecord's type, outputUnitRecord's type} if (inputType is not outputType) then error "Unit type mismatch: " & inputType & ", " & outputType -- The |offset| values are only relevant to temperature conversions and default to zero. set inputUnit to inputUnitRecord & {|offset|:0} set outputUnit to outputUnitRecord & {|offset|:0}   return (inputNumber - (inputUnit's |offset|)) * (inputUnit's coefficient) / (outputUnit's coefficient) ¬ + (outputUnit's |offset|) end convertLinear   on program(inputNumber, inputUnitName) -- The task description only specifies these seven units, but more can be added if wished. -- The coefficients are the equivalent lengths in metres. set unitRecords to {{|name|:"metre", type:"length", coefficient:1.0}, ¬ {|name|:"centimetre", type:"length", coefficient:0.01}, {|name|:"kilometre", type:"length", coefficient:1000.0}, ¬ {|name|:"vershok", type:"length", coefficient:0.04445}, {|name|:"arshin", type:"length", coefficient:0.7112}, ¬ {|name|:"sazhen", type:"length", coefficient:2.1336}, {|name|:"versta", type:"length", coefficient:1066.8}}   -- Massage the given input unit name if necessary. if (inputUnitName ends with "s") then set inputUnitName to text 1 thru -2 of inputUnitName if (inputUnitName ends with "meter") then set inputUnitName to (text 1 thru -3 of inputUnitName) & "re"   -- Get the record with the input unit name from 'unitRecords'. set inputUnitRecord to missing value repeat with thisRecord in unitRecords if (thisRecord's |name| is inputUnitName) then set inputUnitRecord to thisRecord's contents exit repeat end if end repeat if (inputUnitRecord is missing value) then error "Unrecognised unit name: " & inputUnitName   -- Guess the user's spelling preference from the short-date order configured on their machine. tell (current date) to set {Feb1, its day, its month, its year} to {it, 1, 2, 3333} set USSpelling to (Feb1's short date string's first word as integer is 2)   -- Convert the input number to its equivalents in all the specified units, rounding to eight decimal -- places and getting integer values as AS integers where possible. Pair the results with the unit names. set output to {} repeat with thisRecord in unitRecords set outputNumber to convertLinear(inputNumber, inputUnitRecord, thisRecord) set outputNumber to outputNumber div 1 + ((outputNumber * 100000000 mod 100000000) as integer) / 100000000 if (outputNumber mod 1 is 0) then set outputNumber to outputNumber div 1 set outputUnitName to thisRecord's |name| if ((outputUnitName ends with "metre") and (USSpelling)) then ¬ set outputUnitName to (text 1 thru -3 of outputUnitName) & "er" if (outputNumber is not 1) then set outputUnitName to outputUnitName & "s" set end of output to {outputNumber, outputUnitName} end repeat   return output -- {{number, unit name}, … } end program   on demo() set output to {} set astid to AppleScript's text item delimiters repeat with input in {{1, "kilometre"}, {1, "versta"}} set {inputNumber, inputUnitName} to input set end of output to (inputNumber as text) & space & inputUnitName & " is:" set conversions to program(inputNumber, inputUnitName) set AppleScript's text item delimiters to space repeat with thisConversion in conversions set thisConversion's contents to thisConversion as text end repeat set AppleScript's text item delimiters to "; " set end of output to conversions as text end repeat set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid   return output end demo   return demo()
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Common_Lisp
Common Lisp
(defun draw-triangle (x y &key (z 0) (type 'right)) (case type (right (gl:with-primitive :triangles (gl:color 0 0 1) (gl:vertex x y z) (gl:color 0 1 0) (gl:vertex x (- y 1) z) (gl:color 1 0 0) (gl:vertex (+ x 1) (1- y) z))) (equilateral (gl:with-primitive :triangles (gl:color 0 0 1) (gl:vertex (+ x 0.5) y z) (gl:color 1 0 0) (gl:vertex (- x 0.5) (- y 1) z) (gl:color 0 1 0) (gl:vertex (+ x 1.5) (- y 1) z)))))   (defun draw-update () (gl:clear :color-buffer :depth-buffer :color-buffer-bit) (gl:matrix-mode :modelview) (gl:load-identity)   (gl:color 1.0 1.0 1.0) (gl:translate 0 0 -2)   (draw-triangle -0.5 0.5 :type 'equilateral))   (defun main-loop () (sdl:with-events () (:quit-event () t) (:key-down-event (:key key) (cond ((sdl:key= key :sdl-key-escape) (sdl:push-quit-event)))) (:idle () (draw-update) (sdl:update-display))))   (defun setup-gl (w h) (gl:clear-color 0.5 0.5 0.5 1) (gl:clear-depth 1)   (gl:viewport 0 0 w h)   (gl:depth-func :lequal) (gl:hint :perspective-correction-hint :nicest) (gl:shade-model :smooth) (gl:enable :depth-test :cull-face)   (gl:matrix-mode :projection) (gl:load-identity) (glu:perspective 45 (/ w (max h 1)) 0.1 20)   (gl:matrix-mode :modelview) (gl:load-identity))   (defun triangle (&optional (w 640) (h 480)) (sdl:with-init () (sdl:set-gl-attribute :SDL-GL-DEPTH-SIZE 16) (sdl:window w h :bpp 32 :flags sdl:sdl-opengl :title-caption "Rosettacode.org OpenGL Demo") (setup-gl w h) (setf (sdl:frame-rate) 2) (main-loop)))
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#AutoHotkey
AutoHotkey
one_of_n(n){ ; One based line numbers choice = 1 Loop % n-1 { Random, rnd, 1, % A_Index+1 If rnd = 1 choice := A_Index+1 } return choice } one_of_n_test(n=10, trials=100000){ bins := [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Loop % trials bins[one_of_n(n)] += 1 return bins }   b := one_of_n_test() Loop 10 out .= A_Index ": " b[A_Index] "`n" MsgBox % out
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#R
R
p <- c(4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03)   p.adjust(p, method = 'BH') print("Benjamini-Hochberg") writeLines("\n")   p.adjust(p, method = 'BY') print("Benjamini & Yekutieli") writeLines("\n")   p.adjust(p, method = 'bonferroni') print("Bonferroni") writeLines("\n")   p.adjust(p, method = 'hochberg') print("Hochberg") writeLines("\n");   p.adjust(p, method = 'hommel') writeLines("Hommel\n")
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#JavaScript
JavaScript
(() => { "use strict";   // ------------ ORDER DISJOINT LIST ITEMS ------------   // disjointOrder :: [String] -> [String] -> [String] const disjointOrder = ms => ns => zipWith( a => b => [...a, b] )( segments(ms)(ns) )( ns.concat("") ) .flat();     // segments :: [String] -> [String] -> [String] const segments = ms => ns => { const dct = ms.reduce((a, x) => { const wds = a.words, found = wds.indexOf(x) !== -1;   return { parts: [ ...a.parts, ...(found ? [a.current] : []) ], current: found ? [] : [...a.current, x], words: found ? deleteFirst(x)(wds) : wds }; }, { words: ns, parts: [], current: [] });   return [...dct.parts, dct.current]; };     // ---------------------- TEST ----------------------- const main = () => transpose(transpose([{ M: "the cat sat on the mat", N: "mat cat" }, { M: "the cat sat on the mat", N: "cat mat" }, { M: "A B C A B C A B C", N: "C A C A" }, { M: "A B C A B D A B E", N: "E A D A" }, { M: "A B", N: "B" }, { M: "A B", N: "B A" }, { M: "A B B A", N: "B A" }].map(dct => [ dct.M, dct.N, unwords( disjointOrder( words(dct.M) )( words(dct.N) ) ) ])) .map(col => { const w = maximumBy( comparing(x => x.length) )(col).length;   return col.map(justifyLeft(w)(" ")); })) .map( ([a, b, c]) => `${a} -> ${b} -> ${c}` ) .join("\n");     // ---------------- GENERIC FUNCTIONS ----------------   // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => // The ordering of f(x) and f(y) as a value // drawn from {-1, 0, 1}, representing {LT, EQ, GT}. x => y => { const a = f(x), b = f(y);   return a < b ? -1 : (a > b ? 1 : 0); };     // deleteFirst :: a -> [a] -> [a] const deleteFirst = x => { const go = xs => Boolean(xs.length) ? ( x === xs[0] ? ( xs.slice(1) ) : [xs[0]].concat(go(xs.slice(1))) ) : [];   return go; };     // unwords :: [String] -> String const unwords = xs => // A space-separated string derived // from a list of words. xs.join(" ");     // words :: String -> [String] const words = s => // List of space-delimited sub-strings. s.split(/\s+/u);     // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => xs.map( (x, i) => f(x)(ys[i]) ).slice( 0, Math.min(xs.length, ys.length) );   // ---------------- FORMATTING OUTPUT ----------------   // justifyLeft :: Int -> Char -> String -> String const justifyLeft = n => // The string s, followed by enough padding (with // the character c) to reach the string length n. c => s => n > s.length ? ( s.padEnd(n, c) ) : s;     // maximumBy :: (a -> a -> Ordering) -> [a] -> a const maximumBy = f => xs => Boolean(xs.length) ? ( xs.slice(1).reduce( (a, x) => 0 < f(x)(a) ? ( x ) : a, xs[0] ) ) : undefined;     // transpose :: [[a]] -> [[a]] const transpose = rows => // The columns of a matrix of consistent row length, // transposed into corresponding rows. Boolean(rows.length) ? rows[0].map( (_, i) => rows.flatMap( v => v[i] ) ) : [];     // MAIN --- return main(); })();
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#F.23
F#
type Table(rows:string[][]) = // in-place sorting of rows member x.Sort(?ordering, ?column, ?reverse) = let ordering = defaultArg ordering compare let column = defaultArg column 0 let reverse = defaultArg reverse false   let factor = if reverse then -1 else 1 let comparer (row1:string[]) (row2:string[]) = factor * ordering row1.[column] row2.[column]   Array.sortInPlaceWith comparer rows   member x.Print() = for row in rows do printfn "%A" row   // Example usage let t = new Table([| [|"a"; "b"; "c"|] [|""; "q"; "z"|] [|"can"; "z"; "a"|] |])   printfn "Unsorted"; t.Print()   t.Sort() printfn "Default sort"; t.Print()   t.Sort(column=2) printfn "Sorted by col. 2"; t.Print()   t.Sort(column=1) printfn "Sorted by col. 1"; t.Print()   t.Sort(column=1, reverse=true) printfn "Reverse sorted by col. 1"; t.Print()   t.Sort(ordering=fun s1 s2 -> compare s2.Length s1.Length) printfn "Sorted by decreasing length"; t.Print()
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#clojure
clojure
  (defn lex? [a b] (compare a b))  
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#UNIX_Shell
UNIX Shell
#! /bin/bash pascal() { local -i n=${1:-1} if (( n <= 1 )); then echo 1 else local output=$( $FUNCNAME $((n - 1)) ) set -- $( tail -n 1 <<<"$output" ) # previous row echo "$output" printf "1 " while [[ -n $1 ]]; do printf "%d " $(( $1 + ${2:-0} )) shift done echo fi } pascal "$1"
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Lambdatalk
Lambdatalk
  As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence. Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}  
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#LIL
LIL
expr [...] combines all arguments into a single string and evaluates the mathematical expression in that string. The expression can use the following operators (in the order presented): (a) - parentheses -a - negative sign +a - positive sign ~a - bit inversion  !a - logical negation a * b - multiplication a / b - floating point division a \ b - integer division a % b - modulo a + b - addition a - b - subtraction a << b - bit shifting a >> b a <= b - comparison a >= b a < b a > b a == b - equality comparison a != b a | b - bitwise OR a & b - bitwise AND a || b - logical OR a && b - logical AND
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Lua
Lua
42 :my-var 42 "my-var" define
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Euphoria
Euphoria
include misc.e   type ordered(sequence s) for i = 1 to length(s)-1 do -- assume all items in the sequence are atoms if s[i]>s[i+1] then return 0 end if end for return 1 end type   integer maxlen sequence words object word constant fn = open("unixdict.txt","r") maxlen = -1   while 1 do word = gets(fn) if atom(word) then exit end if word = word[1..$-1] -- truncate new-line if length(word) >= maxlen and ordered(word) then if length(word) > maxlen then maxlen = length(word) words = {} end if words = append(words,word) end if end while   close(fn)   pretty_print(1,words,{2})
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#OCaml
OCaml
let is_palindrome s = let l = String.length s in let rec comp n = n = 0 || (s.[l-n] = s.[n-1] && comp (n-1)) in comp (l / 2)
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Phix
Phix
  """One-time pad using an XOR cipher. Requires Python >=3.6."""   import argparse import itertools import pathlib import re import secrets import sys     # One-time pad file signature. MAGIC = "#one-time pad"     def make_keys(n, size): """Generate ``n`` secure, random keys of ``size`` bytes.""" # We're generating and storing keys in their hexadecimal form to make # one-time pad files a little more human readable and to ensure a key # can not start with a hyphen. return (secrets.token_hex(size) for _ in range(n))     def make_pad(name, pad_size, key_size): """Create a new one-time pad identified by the given name.   Args: name (str): Unique one-time pad identifier. pad_size (int): The number of keys (or pages) in the pad. key_size (int): The number of bytes per key. Returns: The new one-time pad as a string. """ pad = [ MAGIC, f"#name={name}", f"#size={pad_size}", *make_keys(pad_size, key_size), ]   return "\n".join(pad)     def xor(message, key): """Return ``message`` XOR-ed with ``key``.   Args: message (bytes): Plaintext or cyphertext to be encrypted or decrypted. key (bytes): Encryption and decryption key. Returns: Plaintext or cyphertext as a byte string. """ return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))     def use_key(pad): """Use the next available key from the given one-time pad.   Args: pad (str): A one-time pad. Returns: (str, str) A two-tuple of updated pad and key. """ match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE) if not match: error("pad is all used up")   key = match.group() pos = match.start()   return (f"{pad[:pos]}-{pad[pos:]}", key)     def log(msg): """Log a message.""" sys.stderr.write(msg) sys.stderr.write("\n")     def error(msg): """Exit with an error message.""" sys.stderr.write(msg) sys.stderr.write("\n") sys.exit(1)     def write_pad(path, pad_size, key_size): """Write a new one-time pad to the given path.   Args: path (pathlib.Path): Path to write one-time pad to. length (int): Number of keys in the pad. """ if path.exists(): error(f"pad '{path}' already exists")   with path.open("w") as fd: fd.write(make_pad(path.name, pad_size, key_size))   log(f"New one-time pad written to {path}")     def main(pad, message, outfile): """Encrypt or decrypt ``message`` using the given pad.   Args: pad (pathlib.Path): Path to one-time pad. message (bytes): Plaintext or ciphertext message to encrypt or decrypt. outfile: File-like object to write to. """ if not pad.exists(): error(f"no such pad '{pad}'")   with pad.open("r") as fd: if fd.readline().strip() != MAGIC: error(f"file '{pad}' does not look like a one-time pad")   # Rewrites the entire one-time pad every time with pad.open("r+") as fd: updated, key = use_key(fd.read())   fd.seek(0) fd.write(updated)   outfile.write(xor(message, bytes.fromhex(key)))     if __name__ == "__main__": # Command line interface parser = argparse.ArgumentParser(description="One-time pad.")   parser.add_argument( "pad", help=( "Path to one-time pad. If neither --encrypt or --decrypt " "are given, will create a new pad." ), )   parser.add_argument( "--length", type=int, default=10, help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.", )   parser.add_argument( "--key-size", type=int, default=64, help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.", )   parser.add_argument( "-o", "--outfile", type=argparse.FileType("wb"), default=sys.stdout.buffer, help=( "Write encoded/decoded message to a file. Ignored if --encrypt or " "--decrypt is not given. Defaults to stdout." ), )   group = parser.add_mutually_exclusive_group()   group.add_argument( "--encrypt", metavar="FILE", type=argparse.FileType("rb"), help="Encrypt FILE using the next available key from pad.", ) group.add_argument( "--decrypt", metavar="FILE", type=argparse.FileType("rb"), help="Decrypt FILE using the next available key from pad.", )   args = parser.parse_args()   if args.encrypt: message = args.encrypt.read() elif args.decrypt: message = args.decrypt.read() else: message = None   # Sometimes necessary if message came from stdin if isinstance(message, str): message = message.encode()   pad = pathlib.Path(args.pad).with_suffix(".1tp")   if message: main(pad, message, args.outfile) else: write_pad(pad, args.length, args.key_size)  
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Racket
Racket
#lang racket/base (define (32-bit-truncate n) (bitwise-and n #xFFFFFFFF))   (define (own-calc-pass password-string nonce) (define-values (num-1 flag) (for/fold ((num-1 0) (flag #t)) ((c (in-string nonce))) (let* ((num-1 (32-bit-truncate num-1)) (num-2 (if flag (string->number password-string) num-1)))   (define (and-right-left-add mask right left) (values (+ (arithmetic-shift (bitwise-and num-2 mask) (- right)) (arithmetic-shift num-2 left)) #f))   (define (left-right-add left right) (values (+ (arithmetic-shift num-2 left) (arithmetic-shift num-2 (- right))) #f))   (define (stage-7) (values (+ (+ (+ (bitwise-and num-2 #xff00) (arithmetic-shift (bitwise-and num-2 #xff) 24)) (arithmetic-shift (bitwise-and num-2 #xff0000) -16)) (arithmetic-shift (bitwise-and num-2 #xFF000000) -8)) #f))   (define (stage-8) (values (+ (+ (arithmetic-shift (bitwise-and num-2 #xffff) 16) (arithmetic-shift num-2 -24)) (arithmetic-shift (bitwise-and num-2 #xff0000) -8)) #f))   (define (stage-9) (values (bitwise-not num-2) #f))   (case c ([#\1] (and-right-left-add #xFFFFFF80 7 25)) ([#\2] (and-right-left-add #xFFFFFFF0 4 28)) ([#\3] (and-right-left-add #xFFFFFFF8 3 29)) ([#\4] (left-right-add 1 31)) ([#\5] (left-right-add 5 27)) ([#\6] (left-right-add 12 20)) ([#\7] (stage-7)) ([#\8] (stage-8)) ([#\9] (stage-9)) (else (values num-1 flag)))))) (32-bit-truncate num-1))   (module+ test (require rackunit)   (define (own-test-calc-pass passwd nonce expected) (let* ((res (own-calc-pass passwd nonce)) (msg (format "~a ~a ~a ~a" passwd nonce res expected))) (string-append (if (= res expected) "PASS" "FAIL") " " msg)))     (own-test-calc-pass "12345" "603356072" 25280520) (own-test-calc-pass "12345" "410501656" 119537670))
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Raku
Raku
sub own-password (Int $password, Int $nonce) { my int $n1 = 0; my int $n2 = $password; for $nonce.comb { given $_ { when 1 { $n1 = $n2 +& 0xFFFFFF80 +> 7; $n2 +<= 25; } when 2 { $n1 = $n2 +& 0xFFFFFFF0 +> 4; $n2 +<= 28; } when 3 { $n1 = $n2 +& 0xFFFFFFF8 +> 3; $n2 +<= 29; } when 4 { $n1 = $n2 +< 1; $n2 +>= 31; } when 5 { $n1 = $n2 +< 5; $n2 +>= 27; } when 6 { $n1 = $n2 +< 12; $n2 +>= 20; } when 7 { $n1 = $n2 +& 0x0000FF00 +| ($n2 +& 0x000000FF +< 24) +| ($n2 +& 0x00FF0000 +> 16); $n2 = $n2 +& 0xFF000000 +> 8; } when 8 { $n1 = $n2 +& 0x0000FFFF +< 16 +| $n2 +> 24; $n2 = $n2 +& 0x00FF0000 +> 8; } when 9 { $n1 = +^$n2 } default { $n1 = $n2 } } given $_ { when 0 {} when 9 {} default { $n1 = ($n1 +| $n2) +& 0xFFFFFFFF } } $n2 = $n1; } $n1 }   say own-password( 12345, 603356072 ); say own-password( 12345, 410501656 ); say own-password( 12345, 630292165 );
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: vershoks, arshins, sazhens, versts, meters, centimeters and kilometers. Also see   Old Russian measure of length
#AWK
AWK
  # syntax: GAWK -f OLD_RUSSIAN_MEASURE_OF_LENGTH.AWK BEGIN { units = "kilometer meter centimeter tochka liniya diuym vershok piad fut arshin sazhen versta milia" values = "1000.0 1.0 0.01 0.000254 0.00254 0.0254 0.04445 0.1778 0.3048 0.7112 2.1336 1066.8 7467.6" u_leng = split(units,u_arr," ") v_leng = split(values,v_arr," ") if (u_leng != v_leng) { print("error: lengths of units & values are unequal") exit(1) } print("enter length & measure or C/R to exit") } { if ($0 == "") { exit(0) } measure = tolower($2) sub(/s$/,"",measure) for (i=1; i<=u_leng; i++) { if (u_arr[i] == measure) { for (j=1; j<=u_leng; j++) { str = sprintf("%.8f",$1*v_arr[i]/v_arr[j]) sub(/0+$/,"",str) printf("%10s %s\n",u_arr[j],str) } print("") next } } printf("error: invalid measure; choose from: %s\n\n",units) }  
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#D
D
module opengl_sample; // file name + directory import dglut.core, dglut.window, dglut.opengl;   void main() { with (new Canvas) { setName("Triangle"); map;   onResize = (Canvas self) { // A delegate literal that takes a parameter. with (self) glViewport(0, 0, width, height); MatrixMode.Projection.Identity; // For functions without parameters, the () can be omitted. glOrtho(-30, 30, -30, 30, -30, 30); MatrixMode.Modelview; };   onDisplay=(Canvas self) { scope(exit) self.swap; // Scope guards ease exception-safe programming glClearColor(0.3f, 0.3f, 0.3f, 0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity; // A convenience wrapper around glTranslatef. Supports numbers, arrays and vectors. Translate(-15, -15, 0); // This is a delegate literal as well. Triangles is a wrapper around glBegin and glEnd. Triangles = { Color(1f, 0f, 0f); Vertex(0, 0); Color(0f, 1f, 0f); Vertex(30, 0); Color(0f, 0f, 1f); Vertex(0, 30); }; }; } loop; }
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#AWK
AWK
#!/usr/bin/gawk -f # # Usage: # gawk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk # BEGIN { srand(Seed ? Seed : 1); } { if (NR*rand() < 1 ) { line = $0 } } END { print line; }
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#BASIC
BASIC
DECLARE FUNCTION oneofN& (n AS LONG)   DIM L0 AS LONG, c AS LONG DIM chosen(1 TO 10) AS LONG   RANDOMIZE TIMER   FOR L0 = 1 TO 1000000 c = oneofN&(10) chosen(c) = chosen(c) + 1 NEXT   FOR L0 = 1 TO 10 PRINT L0, chosen(L0) NEXT   FUNCTION oneofN& (n AS LONG) 'assumes first line is 1 DIM L1 AS LONG, choice AS LONG FOR L1 = 1 TO n IF INT(RND * L1) = 0 THEN choice = L1 NEXT oneofN& = choice END FUNCTION
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q-values". Task Given one list of p-values, return the p-values correcting for multiple comparisons p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03} There are several methods to do this, see: Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101 Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075 Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733 Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325 Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190 Each method has its own advantages and disadvantages.
#Raku
Raku
########################### Helper subs ###########################   sub adjusted (@p, $type) { "\n$type\n" ~ format adjust( check(@p), $type ) }   sub format ( @p, $cols = 5 ) { my $i = -$cols; my $fmt = "%1.10f"; join "\n", @p.rotor($cols, :partial).map: { sprintf "[%2d] { join ' ', $fmt xx $_ }", $i+=$cols, $_ }; }   sub check ( @p ) { die 'p-values must be in range 0.0 to 1.0' if @p.min < 0 or 1 < @p.max; @p }   multi ratchet ( 'up', @p ) { my $m; @p[$_] min= $m, $m = @p[$_] for ^@p; @p }   multi ratchet ( 'dn', @p ) { my $m; @p[$_] max= $m, $m = @p[$_] for ^@p .reverse; @p }   sub schwartzian ( @p, &transform, :$ratchet ) { my @pa = @p.map( {[$_, $++]} ).sort( -*.[0] ).map: { [transform(.[0]), .[1]] }; @pa[*;0] = ratchet($ratchet, @pa»[0]); @pa.sort( *.[1] )»[0] }   ############# The various p-value correction routines #############   multi adjust( @p, 'Benjamini-Hochberg' ) { @p.&schwartzian: * * @p / (@p - $++) min 1, :ratchet('up') }   multi adjust( @p, 'Benjamini-Yekutieli' ) { my \r = ^@p .map( { 1 / ++$ } ).sum; @p.&schwartzian: * * r * @p / (@p - $++) min 1, :ratchet('up') }   multi adjust( @p, 'Hochberg' ) { my \m = @p.max; @p.&schwartzian: * * ++$ min m, :ratchet('up') }   multi adjust( @p, 'Holm' ) { @p.&schwartzian: * * ++$ min 1, :ratchet('dn') }   multi adjust( @p, 'Šidák' ) { @p.&schwartzian: 1 - (1 - *) ** ++$, :ratchet('dn') }   multi adjust( @p, 'Bonferroni' ) { @p.map: * * @p min 1 }   # Hommel correction can't be easily reduced to a one pass transform multi adjust( @p, 'Hommel' ) { my @s = @p.map( {[$_, $++]} ).sort: *.[0] ; # sorted my \z = +@p; # array si(z)e my @pa = @s»[0].map( * * z / ++$ ).min xx z; # p adjusted my @q; # scratch array for (1 ..^ z).reverse -> $i { my @L = 0 .. z - $i; # lower indices my @U = z - $i ^..^ z; # upper indices my $q = @s[@U]»[0].map( { $_ * $i / (2 + $++) } ).min; @q[@L] = @s[@L]»[0].map: { min $_ * $i, $q, @s[*-1][0] }; @pa = ^z .map: { max @pa[$_], @q[$_] } } @pa[@s[*;1].map( {[$_, $++]} ).sort( *.[0] )»[1]] }   multi adjust ( @p, $unknown ) { note "\nSorry, do not know how to do $unknown correction.\n" ~ "Perhaps you want one of these?:\n" ~ <Benjamini-Hochberg Benjamini-Yekutieli Bonferroni Hochberg Holm Hommel Šidák>.join("\n"); exit }   ########################### The task ###########################   my @p-values = 4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, 3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, 1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03 ;   for < Benjamini-Hochberg Benjamini-Yekutieli Bonferroni Hochberg Holm Hommel Šidák > { say adjusted @p-values, $_ }
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#jq
jq
def disjoint_order(N): # The helper function, indices, ensures that successive occurrences # of a particular value in N are matched by successive occurrences # in the input on the assumption that null is not initially in the input. def indices: . as $in | reduce range(0; N|length) as $i # state: [ array, indices ] ( [$in, []]; (.[0] | index(N[$i])) as $ix | .[0][$ix] = null | .[1] += [$ix]) | .[1];   . as $in | (indices | sort) as $sorted | reduce range(0; N|length) as $i ($in; .[$sorted[$i]] = N[$i] ) ;
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Julia
Julia
  function order_disjoint{T<:AbstractArray}(m::T, n::T) rlen = length(n) rdis = zeros(Int, rlen) for (i, e) in enumerate(n) j = findfirst(m, e) while j in rdis && j != 0 j = findnext(m, e, j+1) end rdis[i] = j end if 0 in rdis throw(DomainError()) end sort!(rdis) p = copy(m) p[rdis] = n return p end  
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Kotlin
Kotlin
// version 1.0.6   const val NULL = "\u0000"   fun orderDisjointList(m: String, n: String): String { val nList = n.split(' ') // first replace the first occurrence of items of 'n' in 'm' with the NULL character // which we can safely assume won't occur in 'm' naturally var p = m for (item in nList) p = p.replaceFirst(item, NULL) // now successively replace the NULLs with items from nList val mList = p.split(NULL) val sb = StringBuilder() for (i in 0 until nList.size) sb.append(mList[i], nList[i]) return sb.append(mList.last()).toString() }   fun main(args: Array<String>) { val m = arrayOf( "the cat sat on the mat", "the cat sat on the mat", "A B C A B C A B C", "A B C A B D A B E", "A B", "A B", "A B B A" ) val n = arrayOf( "mat cat", "cat mat", "C A C A", "E A D A", "B", "B A", "B A" ) for (i in 0 until m.size) println("${m[i].padEnd(22)} -> ${n[i].padEnd(7)} -> ${orderDisjointList(m[i], n[i])}") }
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Factor
Factor
USING: accessors combinators io kernel math.order prettyprint sequences sorting ;   TUPLE: table-sorter data { column initial: 0 } reversed? { ordering initial: [ ] } ;   : <table-sorter> ( -- obj ) table-sorter new ;   : sort-table ( table-sorter -- matrix ) { [ data>> ] [ column>> [ swap nth ] curry ] [ ordering>> compose ] [ reversed?>> [ >=< ] [ <=> ] ? [ bi@ ] prepose curry ] } cleave [ sort ] curry call( x -- x ) ;     ! ===== Now we can use the interface defined above =====   CONSTANT: table { { "a" "b" "c" } { "" "q" "z" } { "can" "z" "a" } }   "Unsorted" print table simple-table.   "Default sort" print <table-sorter> table >>data sort-table simple-table.   "Sorted by col 2" print <table-sorter> table >>data 2 >>column sort-table simple-table.   "Sorted by col 1" print <table-sorter> table >>data 1 >>column sort-table simple-table.   "Reverse sorted by col 1" print <table-sorter> table >>data 1 >>column t >>reversed? sort-table simple-table.   "Sorted by decreasing length" print <table-sorter> table >>data t >>reversed? [ length ] >>ordering sort-table simple-table.
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#Fortran
Fortran
module ExampleOptionalParameter ! use any module needed for the sort function(s) ! and all the interfaces needed to make the code work implicit none contains   subroutine sort_table(table, ordering, column, reverse) type(table_type), intent(inout) :: table integer, optional :: column logical, optional :: reverse optional :: ordering interface integer function ordering(a, b) type(table_element), intent(in) :: a, b end function ordering end interface   integer :: the_column, i logical :: reversing type(table_row) :: rowA, rowB   if ( present(column) ) then if ( column > get_num_of_columns(table) ) then ! raise an error? else the_column = column end if else the_column = 1 ! a default value, de facto end if   reversing = .false. ! default value if ( present(reverse) ) reversing = reverse   do ! loops over the rows to sort... at some point, we need ! comparing an element (cell) of the row, with the element ! in another row; ... let us suppose rowA and rowB are ! the two rows we are considering ea = get_element(rowA, the_column) eb = get_element(rowB, the_column) if ( present(ordering) ) then if ( .not. reversing ) then if ( ordering(ea, eb) > 0 ) then ! swap the rowA with the rowB end if else ! < instead of > if ( ordering(ea, eb) < 0 ) then ! swap the rowA with the rowB end if end if else if ( .not. reversing ) then if ( lexinternal(ea, eb) > 0 ) then ! swap the rowA with the rowB end if else ! < instead of > if ( lexinternal(ea, eb) < 0 ) then ! swap the rowA with the rowB end if end if end if ! ... more of the sorting algo ... ! ... and rows traversing ... (and an exit condition of course!) end do   end subroutine sort_table   end module ExampleOptionalParameter
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#Common_Lisp
Common Lisp
(defun list< (a b) (cond ((not b) nil) ((not a) t) ((= (first a) (first b)) (list< (rest a) (rest b))) (t (< (first a) (first b)))))
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Ursala
Ursala
#import std #import nat   pascal = choose**ziDS+ iota*t+ iota+ successor
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
42 :my-var 42 "my-var" define
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#MATLAB
MATLAB
42 :my-var 42 "my-var" define
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#min
min
42 :my-var 42 "my-var" define
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#F.23
F#
open System open System.IO   let longestOrderedWords() = let isOrdered = Seq.pairwise >> Seq.forall (fun (a,b) -> a <= b)   File.ReadLines("unixdict.txt") |> Seq.filter isOrdered |> Seq.groupBy (fun s -> s.Length) |> Seq.sortBy (fst >> (~-)) |> Seq.head |> snd   longestOrderedWords() |> Seq.iter (printfn "%s")
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Octave
Octave
function v = palindro_r(s) if ( length(s) == 1 ) v = true; return; elseif ( length(s) == 2 ) v = s(1) == s(2); return; endif if ( s(1) == s(length(s)) ) v = palindro_r(s(2:length(s)-1)); else v = false; endif endfunction
http://rosettacode.org/wiki/One-time_pad
One-time pad
Implement a One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. Sub-Tasks Generate the data for a One-time pad (user needs to specify a filename and length) The important part is to get "true random" numbers, e.g. from /dev/random encryption / decryption ( basically the same operation, much like Rot-13 ) For this step, much of Vigenère cipher could be reused, with the key to be read from the file containing the One-time pad. optional: management of One-time pads: list, mark as used, delete, etc. Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: Such files have a file-extension ".1tp" Lines starting with "#" may contain arbitary meta-data (i.e. comments) Lines starting with "-" count as "used" Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE See also one time pad encryption in Python snapfractalpop - One-Time-Pad Command-Line-Utility (C). Crypt-OTP-2.00 on CPAN (Perl)
#Python
Python
  """One-time pad using an XOR cipher. Requires Python >=3.6."""   import argparse import itertools import pathlib import re import secrets import sys     # One-time pad file signature. MAGIC = "#one-time pad"     def make_keys(n, size): """Generate ``n`` secure, random keys of ``size`` bytes.""" # We're generating and storing keys in their hexadecimal form to make # one-time pad files a little more human readable and to ensure a key # can not start with a hyphen. return (secrets.token_hex(size) for _ in range(n))     def make_pad(name, pad_size, key_size): """Create a new one-time pad identified by the given name.   Args: name (str): Unique one-time pad identifier. pad_size (int): The number of keys (or pages) in the pad. key_size (int): The number of bytes per key. Returns: The new one-time pad as a string. """ pad = [ MAGIC, f"#name={name}", f"#size={pad_size}", *make_keys(pad_size, key_size), ]   return "\n".join(pad)     def xor(message, key): """Return ``message`` XOR-ed with ``key``.   Args: message (bytes): Plaintext or cyphertext to be encrypted or decrypted. key (bytes): Encryption and decryption key. Returns: Plaintext or cyphertext as a byte string. """ return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))     def use_key(pad): """Use the next available key from the given one-time pad.   Args: pad (str): A one-time pad. Returns: (str, str) A two-tuple of updated pad and key. """ match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE) if not match: error("pad is all used up")   key = match.group() pos = match.start()   return (f"{pad[:pos]}-{pad[pos:]}", key)     def log(msg): """Log a message.""" sys.stderr.write(msg) sys.stderr.write("\n")     def error(msg): """Exit with an error message.""" sys.stderr.write(msg) sys.stderr.write("\n") sys.exit(1)     def write_pad(path, pad_size, key_size): """Write a new one-time pad to the given path.   Args: path (pathlib.Path): Path to write one-time pad to. length (int): Number of keys in the pad. """ if path.exists(): error(f"pad '{path}' already exists")   with path.open("w") as fd: fd.write(make_pad(path.name, pad_size, key_size))   log(f"New one-time pad written to {path}")     def main(pad, message, outfile): """Encrypt or decrypt ``message`` using the given pad.   Args: pad (pathlib.Path): Path to one-time pad. message (bytes): Plaintext or ciphertext message to encrypt or decrypt. outfile: File-like object to write to. """ if not pad.exists(): error(f"no such pad '{pad}'")   with pad.open("r") as fd: if fd.readline().strip() != MAGIC: error(f"file '{pad}' does not look like a one-time pad")   # Rewrites the entire one-time pad every time with pad.open("r+") as fd: updated, key = use_key(fd.read())   fd.seek(0) fd.write(updated)   outfile.write(xor(message, bytes.fromhex(key)))     if __name__ == "__main__": # Command line interface parser = argparse.ArgumentParser(description="One-time pad.")   parser.add_argument( "pad", help=( "Path to one-time pad. If neither --encrypt or --decrypt " "are given, will create a new pad." ), )   parser.add_argument( "--length", type=int, default=10, help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.", )   parser.add_argument( "--key-size", type=int, default=64, help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.", )   parser.add_argument( "-o", "--outfile", type=argparse.FileType("wb"), default=sys.stdout.buffer, help=( "Write encoded/decoded message to a file. Ignored if --encrypt or " "--decrypt is not given. Defaults to stdout." ), )   group = parser.add_mutually_exclusive_group()   group.add_argument( "--encrypt", metavar="FILE", type=argparse.FileType("rb"), help="Encrypt FILE using the next available key from pad.", ) group.add_argument( "--decrypt", metavar="FILE", type=argparse.FileType("rb"), help="Decrypt FILE using the next available key from pad.", )   args = parser.parse_args()   if args.encrypt: message = args.encrypt.read() elif args.decrypt: message = args.decrypt.read() else: message = None   # Sometimes necessary if message came from stdin if isinstance(message, str): message = message.encode()   pad = pathlib.Path(args.pad).with_suffix(".1tp")   if message: main(pad, message, args.outfile) else: write_pad(pad, args.length, args.key_size)  
http://rosettacode.org/wiki/OpenWebNet_password
OpenWebNet password
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist Note: Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows ← *#*1## → *99*0## ← *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent → *#25280520## ← *#*1##
#Swift
Swift
  func openAuthenticationResponse(_password: String, operations: String) -> String? { var num1 = UInt32(0) var num2 = UInt32(0) var start = true let password = UInt32(_password)! for c in operations { if (c != "0") { if start { num2 = password } start = false } switch c { case "1": num1 = (num2 & 0xffffff80) >> 7 num2 = num2 << 25 case "2": num1 = (num2 & 0xfffffff0) >> 4 num2 = num2 << 28 case "3": num1 = (num2 & 0xfffffff8) >> 3 num2 = num2 << 29 case "4": num1 = num2 << 1 num2 = num2 >> 31 case "5": num1 = num1 << 5 num2 = num2 >> 27 case "6": num1 = num2 << 12 num2 = num2 >> 20 case "7": num1 = (num2 & 0x0000ff00) | ((num2 & 0x000000ff) << 24) | ((num2 & 0x00ff0000) >> 16) num2 = (num2 & 0xff000000) >> 8 case "8": num1 = ((num2 & 0x0000ffff) << 16) | (num2 >> 24) num2 = (num2 & 0x00ff0000) >> 8 case "9": num1 = ~num2 case "0": num1 = num2 default: print("unexpected char \(c)") return nil } if (c != "9") && (c != "0") { num1 |= num2 } num2 = num1 } return String(num1) }