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/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
#Arturo
Arturo
sortTable: function [tbl][ column: "0" reversed?: false unless null? c: <= attr 'column -> column: to :string c unless null? attr 'reverse -> reversed?: true   result: new sort.by: column map tbl 'r [ to :dictionary flatten couple 0..dec size r r ]   if reversed? -> reverse 'result   return map result 'r -> values r ]   printTable: function [tbl, title][ print ["==" title] loop tbl 'row [ print row ] print "" ]   lst: [ ["a", "b", "c"] ["", "q", "z"] ["zap", "zip", "Zot"] ]   printTable sortTable lst "Default sort" printTable sortTable.column:1 lst "Sorting by column=1" printTable sortTable.reverse lst "Sorting, reversed" printTable sortTable.reverse.column:1 lst "Sorting by column=1, reversed"
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.
#ALGOL_W
ALGOL W
begin % compare lists (rows) of integers %  % returns TRUE if there is an element in a that is < the corresponding %  % element in b and all previous elements are equal, FALSE otherwise  %  % the bounds of a and b should aLb :: aUb and bLb :: bUb  % logical procedure iLT ( integer array a ( * )  ; integer value aLb, aUb  ; integer array b ( * )  ; integer value bLb, bUb ) ; begin integer aPos, bPos; logical equal; aPos := aLb; bPos := bLb; equal := true; while aPos <= aUb and bPos <= bUb and equal do begin equal := a( aPos ) = b( bPos ); if equal then begin aPos := aPOs + 1; bPos := bPos + 1 end if_equal end while_more_elements_and_equal ; if not equal then % there is an element in a and b that is not equal % a( aPos ) < b( bPos ) else % all elements are equal or one list is shorter %  % a is < b if a has fewer elements % aPos > aUb and bPos <= bUb end iLT ;  % tests a < b has the expected result % procedure test ( string(5) value aName  ; integer array a ( * )  ; integer value aLb, aUb  ; string(5) value bName  ; integer array b ( * )  ; integer value bLb, bUb  ; logical value expected ) ; begin logical isLt; isLt := iLT( a, aLb, aUb, b, bLb, bUb ); write( aName, if isLt then " < " else " >= ", bName , if isLt = expected then "" else ", NOT as expected" ) end test ;   integer array list1, list3, list4 ( 1 :: 5 ); integer array list2 ( 1 :: 6 ); integer array list5 ( 1 :: 5 ); integer array list6 ( 1 :: 4 ); integer array list7 ( 1 :: 3 ); integer array list8 ( 1 :: 1 ); integer aPos;  % test cases as in the BBC basic sample % aPos := 1; for i := 1, 2, 1, 5, 2 do begin list1( aPos ) := i; aPos := aPos + 1 end; aPos := 1; for i := 1, 2, 1, 5, 2, 2 do begin list2( aPos ) := i; aPos := aPos + 1 end; aPos := 1; for i := 1, 2, 3, 4, 5 do begin list3( aPos ) := i; aPos := aPos + 1 end; aPos := 1; for i := 1, 2, 3, 4, 5 do begin list4( aPos ) := i; aPos := aPos + 1 end; test( "list1", list1, 1, 5, "list2", list2, 1, 6, true ); test( "list2", list2, 1, 6, "list3", list3, 1, 5, true ); test( "list3", list3, 1, 5, "list4", list4, 1, 5, false );  % additional test cases % aPos := 1; for i := 9, 0, 2, 1, 0 do begin list5( aPos ) := i; aPos := aPos + 1 end; aPos := 1; for i := 4, 0, 7, 7 do begin list6( aPos ) := i; aPos := aPos + 1 end; aPos := 1; for i := 4, 0, 7 do begin list7( aPos ) := i; aPos := aPos + 1 end; test( "list5", list5, 1, 5, "list6", list6, 1, 4, false ); test( "list6", list6, 1, 4, "list7", list7, 1, 3, false ); test( "list7", list7, 1, 3, "list8", list8, 1, 0, false ); test( "list8", list8, 1, 0, "list7", list7, 1, 3, true ) 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.
#Aime
Aime
ordl(list a, b) { integer i, l, o;   l = min(~a, ~b); i = 0; while (i < l) { if (a[i] != b[i]) { o = a[i] < b[i]; break; }   i += 1; }   i < l ? o : ~a <= ~b; }   main(void) { o_(ordl(list(1, 2), list(1, 2)), "\n"); o_(ordl(list(1e2, 2), list(1e2, 2, 3)), "\n"); o_(ordl(list(1, 2, 3), list(1, 2)), "\n"); o_(ordl(list(.5, 4), list(.5, 2)), "\n"); o_(ordl(list(1, 4, 2, 3), list(1, 4, 2.1, 3)), "\n");   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
#Scala
Scala
  def tri(row: Int): List[Int] = row match { case 1 => List(1) case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1 }
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Order_by_pair_comparisons use warnings;   sub ask { while( 1 ) { print "Compare $a to $b [<,=,>]: "; <STDIN> =~ /[<=>]/ and return +{qw( < -1 = 0 > 1 )}->{$&}; } }   my @sorted = sort ask qw( violet red green indigo blue yellow orange ); print "sorted: @sorted\n";
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Phix
Phix
integer qn = 0 function ask(string a, b) qn += 1 printf(1,"%d: Is %s < %s (Y/N)?:",{qn,a,b}) integer ch = upper(wait_key()) printf(1,"%s\n",ch) return iff(ch='Y'?-1:1) end function ?custom_sort(ask,split("violet orange red yellow green blue indigo"))
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.
#AWK
AWK
  # Operators are shown in decreasing order of precedence. # A blank line separates groups of operators with equal precedence. # All operators are left associative except: # . assignment operators # . conditional operator # . exponentiation # which are right associative. # # ( ) grouping # # $ field reference # # ++ increment (both prefix and postfix) # -- decrement (both prefix and postfix) # # ^ exponentiation # ** exponentiation (not all awk's) # # + unary plus # - unary minus #  ! logical NOT # # * multiply # / divide #  % modulus # # + add # - subtract # # string concatenation has no explicit operator # # < relational: less than # <= relational: less than or equal to # > relational: greater than # >= relational: greater than or equal to #  != relational: not equal to # == relational: equal to # > redirection: output to file # >> redirection: append output to file # | redirection: pipe # |& redirection: coprocess (not all awk's) # # ~ regular expression: match #  !~ regular expression: negated match # # in array membership # # && logical AND # # || logical OR # #  ?: conditional expression # # = assignment # += addition assignment # -= subtraction assignment # *= multiplication assignment # /= division assignment #  %= modulo assignment # ^= exponentiation assignment # **= exponentiation assignment (not all awk's)  
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.
#BASIC256
BASIC256
3 * 2 + 1
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
#Clojure
Clojure
(defn is-sorted? [coll] (not-any? pos? (map compare coll (next coll))))   (defn take-while-eqcount [coll] (let [n (count (first coll))] (take-while #(== n (count %)) coll)))   (with-open [rdr (clojure.java.io/reader "unixdict.txt")] (->> rdr line-seq (filter is-sorted?) (sort-by count >) take-while-eqcount (clojure.string/join ", ") println))
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
#Mirah
Mirah
def reverse(s:string) StringBuilder.new(s).reverse.toString() end   def palindrome?(s:string) s.equals(reverse(s)) end   puts palindrome?("anna") # ==> true puts palindrome?("Erik") # ==> false puts palindrome?("palindroom-moordnilap") # ==> true puts nil # ==> null
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.
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector>   std::vector<int> seqLen(int start, int end) { std::vector<int> result;   if (start == end) { result.resize(end + 1); std::iota(result.begin(), result.end(), 1); } else if (start < end) { result.resize(end - start + 1); std::iota(result.begin(), result.end(), start); } else { result.resize(start - end + 1); std::iota(result.rbegin(), result.rend(), end); }   return result; }   std::vector<int> order(const std::vector<double>& arr, bool decreasing) { std::vector<int> idx(arr.size()); std::iota(idx.begin(), idx.end(), 0);   std::function<bool(int, int)> cmp; if (decreasing) { cmp = [&arr](int a, int b) { return arr[b] < arr[a]; }; } else { cmp = [&arr](int a, int b) { return arr[a] < arr[b]; }; }   std::sort(idx.begin(), idx.end(), cmp); return idx; }   std::vector<double> cummin(const std::vector<double>& arr) { if (arr.empty()) throw std::runtime_error("cummin requries at least one element"); std::vector<double> output(arr.size()); double cumulativeMin = arr[0]; std::transform(arr.cbegin(), arr.cend(), output.begin(), [&cumulativeMin](double a) { if (a < cumulativeMin) cumulativeMin = a; return cumulativeMin; }); return output; }   std::vector<double> cummax(const std::vector<double>& arr) { if (arr.empty()) throw std::runtime_error("cummax requries at least one element"); std::vector<double> output(arr.size()); double cumulativeMax = arr[0]; std::transform(arr.cbegin(), arr.cend(), output.begin(), [&cumulativeMax](double a) { if (cumulativeMax < a) cumulativeMax = a; return cumulativeMax; }); return output; }   std::vector<double> pminx(const std::vector<double>& arr, double x) { if (arr.empty()) throw std::runtime_error("pmin requries at least one element"); std::vector<double> result(arr.size()); std::transform(arr.cbegin(), arr.cend(), result.begin(), [&x](double a) { if (a < x) return a; return x; }); return result; }   void doubleSay(const std::vector<double>& arr) { printf("[ 1] %.10f", arr[0]); for (size_t i = 1; i < arr.size(); ++i) { printf(" %.10f", arr[i]); if ((i + 1) % 5 == 0) printf("\n[%2d]", i + 1); } }   std::vector<double> pAdjust(const std::vector<double>& pvalues, const std::string& str) { if (pvalues.empty()) throw std::runtime_error("pAdjust requires at least one element"); size_t size = pvalues.size();   int type; if ("bh" == str || "fdr" == str) { type = 0; } else if ("by" == str) { type = 1; } else if ("bonferroni" == str) { type = 2; } else if ("hochberg" == str) { type = 3; } else if ("holm" == str) { type = 4; } else if ("hommel" == str) { type = 5; } else { throw std::runtime_error(str + " doesn't match any accepted FDR types"); }   // Bonferroni method if (2 == type) { std::vector<double> result(size); for (size_t i = 0; i < size; ++i) { double b = pvalues[i] * size; if (b >= 1) { result[i] = 1; } else if (0 <= b && b < 1) { result[i] = b; } else { throw std::runtime_error("a value is outside [0, 1)"); } } return result; } // Holm method else if (4 == type) { auto o = order(pvalues, false); std::vector<double> o2Double(o.begin(), o.end()); std::vector<double> cummaxInput(size); for (size_t i = 0; i < size; ++i) { cummaxInput[i] = (size - i) * pvalues[o[i]]; } auto ro = order(o2Double, false); auto cummaxOutput = cummax(cummaxInput); auto pmin = pminx(cummaxOutput, 1.0); std::vector<double> result(size); std::transform(ro.cbegin(), ro.cend(), result.begin(), [&pmin](int a) { return pmin[a]; }); return result; } // Hommel else if (5 == type) { auto indices = seqLen(size, size); auto o = order(pvalues, false); std::vector<double> p(size); std::transform(o.cbegin(), o.cend(), p.begin(), [&pvalues](int a) { return pvalues[a]; }); std::vector<double> o2Double(o.begin(), o.end()); auto ro = order(o2Double, false); std::vector<double> q(size); std::vector<double> pa(size); std::vector<double> npi(size); for (size_t i = 0; i < size; ++i) { npi[i] = p[i] * size / indices[i]; } double min = *std::min_element(npi.begin(), npi.end()); std::fill(q.begin(), q.end(), min); std::fill(pa.begin(), pa.end(), min); for (int j = size; j >= 2; --j) { auto ij = seqLen(1, size - j + 1); std::transform(ij.cbegin(), ij.cend(), ij.begin(), [](int a) { return a - 1; }); int i2Length = j - 1; std::vector<int> i2(i2Length); for (int i = 0; i < i2Length; ++i) { i2[i] = size - j + 2 + i - 1; } double q1 = j * p[i2[0]] / 2.0; for (int i = 1; i < i2Length; ++i) { double temp_q1 = p[i2[i]] * j / (2.0 + i); if (temp_q1 < q1) q1 = temp_q1; } for (size_t i = 0; i < size - j + 1; ++i) { q[ij[i]] = std::min(p[ij[i]] * j, q1); } for (int i = 0; i < i2Length; ++i) { q[i2[i]] = q[size - j]; } for (size_t i = 0; i < size; ++i) { if (pa[i] < q[i]) { pa[i] = q[i]; } } } std::transform(ro.cbegin(), ro.cend(), q.begin(), [&pa](int a) { return pa[a]; }); return q; }   std::vector<double> ni(size); std::vector<int> o = order(pvalues, true); std::vector<double> od(o.begin(), o.end()); for (size_t i = 0; i < size; ++i) { if (pvalues[i] < 0 || pvalues[i]>1) { throw std::runtime_error("a value is outside [0, 1]"); } ni[i] = (double)size / (size - i); } auto ro = order(od, false); std::vector<double> cumminInput(size); if (0 == type) { // BH method for (size_t i = 0; i < size; ++i) { cumminInput[i] = ni[i] * pvalues[o[i]]; } } else if (1 == type) { // BY method double q = 0; for (size_t i = 1; i < size + 1; ++i) { q += 1.0 / i; } for (size_t i = 0; i < size; ++i) { cumminInput[i] = q * ni[i] * pvalues[o[i]]; } } else if (3 == type) { // Hochberg method for (size_t i = 0; i < size; ++i) { cumminInput[i] = (i + 1) * pvalues[o[i]]; } } auto cumminArray = cummin(cumminInput); auto pmin = pminx(cumminArray, 1.0); std::vector<double> result(size); for (size_t i = 0; i < size; ++i) { result[i] = pmin[ro[i]]; } return result; }   int main() { using namespace std;   vector<double> 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 };   vector<vector<double>> correctAnswers{ // 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 } };   vector<string> types{ "bh", "by", "bonferroni", "hochberg", "holm", "hommel" }; for (size_t type = 0; type < types.size(); ++type) { auto q = pAdjust(pvalues, types[type]); double error = 0.0; for (size_t i = 0; i < pvalues.size(); ++i) { error += abs(q[i] - correctAnswers[type][i]); } doubleSay(q); printf("\ntype = %d = '%s' has a cumulative error of %g\n\n\n", type, types[type].c_str(), error); }   return 0; }
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
#Arturo
Arturo
orderDisjoint: function [m,n][ ms: split.words m ns: split.words n   indexes: new []   loop ns 'item [ idx: index ms item unless null? idx [ 'indexes ++ idx ms\[idx]: "" ] ] sort 'indexes   loop.with:'i indexes 'idx -> ms\[idx]: ns\[i]   return join.with:" " ms ]   process: function [a,b][ print [a "|" b "->" orderDisjoint a b] ]   process "the cat sat on the mat" "mat cat" process "the cat sat on the mat" "cat mat" process "A B C A B C A B C" "C A C A" process "A B C A B D A B E" "E A D A" process "A B" "B" process "A B" "B A" process "A B B A" "B A"
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
#AutoHotkey
AutoHotkey
Data := [ {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"} ]   for Key, Val in Data Output .= Val.M " :: " Val.N " -> " OrderDisjointList(Val.M, Val.N) "`n" MsgBox, % RTrim(Output, "`n")   OrderDisjointList(M, N) { ItemsN := [] Loop, Parse, N, % A_Space ItemsN[A_LoopField] := ItemsN[A_LoopField] ? ItemsN[A_LoopField] + 1 : 1 N := StrSplit(N, A_Space) Loop, Parse, M, % A_Space Result .= (ItemsN[A_LoopField]-- > 0 ? N.Remove(1) : A_LoopField) " " return RTrim(Result) }
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
#AutoHotkey
AutoHotkey
Gosub start ; create and show the gui sort_table("Text", column := 2, reverse := 1) ; lexicographic sort Sleep, 2000 sort_table("Integer", column := 2, reverse := 1) ; numerical sort Return   start: Gui, Add, ListView, r20 w200, 1|2|3 data = ( 1,2,3 b,q,z c,z,z ) Loop, Parse, data, `n { StringSplit, row, A_LoopField, `, LV_Add(row, row1, row2, row3) } LV_ModifyCol(50) ; Auto-size columns Gui, Show Return   ; The function supporting named, defaulted arguments sort_table(ordering = "Text", column = 0, reverse = 0) { If reverse desc = desc LV_ModifyCol(column, "sort" . desc . " " . ordering) }   GuiClose: ExitApp
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.
#AppleScript
AppleScript
-- <= for lists -- compare :: [a] -> [a] -> Bool on compare(xs, ys) if length of xs = 0 then true else if length of ys = 0 then false else set {hx, txs} to uncons(xs) set {hy, tys} to uncons(ys)   if hx = hy then compare(txs, tys) else hx < hy end if end if end if end compare       -- TEST on run   {compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]), ¬ compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2])}   end run     ---------------------------------------------------------------------------   -- GENERIC FUNCTION   -- uncons :: [a] -> Maybe (a, [a]) on uncons(xs) if length of xs > 0 then {item 1 of xs, rest of xs} else missing value end if end uncons
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
#Scheme
Scheme
(define (next-row row) (map + (cons 0 row) (append row '(0))))   (define (triangle row rows) (if (= rows 0) '() (cons row (triangle (next-row row) (- rows 1)))))   (triangle (list 1) 5)  
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Python
Python
def _insort_right(a, x, q): """ Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. """   lo, hi = 0, len(a) while lo < hi: mid = (lo+hi)//2 q += 1 less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q   def order(items): ordered, q = [], 0 for item in items: q = _insort_right(ordered, item, q) return ordered, q   if __name__ == '__main__': items = 'violet red green indigo blue yellow orange'.split() ans, questions = order(items) print('\n' + ' '.join(ans))
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Quackery
Quackery
[ $ "Is " swap join $ " before " join swap join $ "? (y/n) " join input $ "y" = ] is askuser   $ "red orange yellow green blue indigo violet" say "Correct order --> " dup echo$ cr cr nest$ shuffle dup witheach [ echo$ sp ] cr cr sortwith askuser cr witheach [ echo$ sp ] cr
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.
#bc
bc
3 * 2 + 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.
#BCPL
BCPL
3 * 2 + 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.
#BQN
BQN
3 * 2 + 1
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
#CLU
CLU
is_ordered = proc (s: string) returns (bool) last: char := '\000' for c: char in string$chars(s) do if last > c then return(false) end last := c end return(true) end is_ordered   lines = iter (s: stream) yields (string) while true do yield(stream$getl(s)) except when end_of_file: break end end end lines   ordered_words = proc (s: stream) returns (array[string]) words: array[string] max_len: int := 0 for word: string in lines(s) do if is_ordered(word) then len: int := string$size(word) if len > max_len then max_len := len words := array[string]$[] elseif len = max_len then array[string]$addh(words,word) end end end return(words) end ordered_words   start_up = proc () dict: stream := stream$open(file_name$parse("unixdict.txt"), "read") words: array[string] := ordered_words(dict) stream$close(dict)   po: stream := stream$primary_output() for word: string in array[string]$elements(words) do stream$putl(po, word) end end start_up
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
#ML
ML
fun to_locase s = implode ` map (c_downcase) ` explode s   fun only_alpha s = implode ` filter (fn x = c_alphabetic x) ` explode s   fun is_palin ( h1 :: t1, h2 :: t2, n = 0 ) = true | ( h1 :: t1, h2 :: t2, n ) where ( h1 eql h2 ) = is_palin( t1, t2, n - 1) | ( h1 :: t1, h2 :: t2, n ) = false | (str s) = let val es = explode ` to_locase ` only_alpha s; val res = rev es; val k = (len es) div 2 in is_palin (es, res, k) end   fun test_is_palin s = (print "\""; print s; print "\" is a palindrome: "; print ` is_palin s; println "")   fun test (f, arg, res, ok, notok) = if (f arg eql res) then ("'" @ arg @ "' " @ ok) else ("'" @ arg @ "' " @ notok)   ;   println ` test (is_palin, "In girum imus nocte, et consumimur igni", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "Madam, I'm Adam.", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "salàlas", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "radar", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "Lagerregal", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "Ein Neger mit Gazelle zagt im Regen nie.", true, "is a palindrome", "is NOT a palindrome"); println ` test (is_palin, "something wrong", true, "is a palindrome", "is NOT a palindrome");
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##
#11l
11l
F ownCalcPass(password, nonce) UInt32 result V start = 1B L(c) nonce I c != ‘0’ & start result = UInt32(Int(password)) start = 0B S c ‘0’ {} ‘1’ result = rotr(result, 7) ‘2’ result = rotr(result, 4) ‘3’ result = rotr(result, 3) ‘4’ result = rotl(result, 1) ‘5’ result = rotl(result, 5) ‘6’ result = rotl(result, 12) ‘7’ result = (result [&] 0000'FF00) [|] result << 24 [|] (result [&] 00FF'0000) >> 16 [|] (result [&] FF00'0000) >> 8 ‘8’ result = result << 16 [|] result >> 24 [|] (result [&] 00FF'0000) >> 8 ‘9’ result = (-)result E X ValueError(‘non-digit in nonce.’) R result   F test_passwd_calc(passwd, nonce, expected) V res = ownCalcPass(passwd, nonce) V m = passwd‘ ’nonce‘ ’res‘ ’expected I res == expected print(‘PASS ’m) E print(‘FAIL ’m)   test_passwd_calc(‘12345’, ‘603356072’, 25280520) test_passwd_calc(‘12345’, ‘410501656’, 119537670) test_passwd_calc(‘12345’, ‘630292165’, 4269684735)
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.
#D
D
import std.algorithm; import std.conv; import std.math; import std.stdio; import std.string;   int[] seqLen(int start, int end) { int[] result; if (start == end) { result.length = end+1; for (int i; i<result.length; i++) { result[i] = i+1; } } else if (start < end) { result.length = end - start + 1; for (int i; i<result.length; i++) { result[i] = start+i; } } else { result.length = start - end + 1; for (int i; i<result.length; i++) { result[i] = start-i; } } return result; }   int[] order(double[] array, bool decreasing) { int size = array.length; int[] idx; idx.length = size; double[] baseArr; baseArr.length = size; for (int i; i<size; i++) { baseArr[i] = array[i]; idx[i] = i; } if (!decreasing) { alias comp = (a,b) => baseArr[a] < baseArr[b]; idx.sort!comp; } else { alias comp = (a,b) => baseArr[b] < baseArr[a]; idx.sort!comp; } return idx; }   double[] cummin(double[] array) { int size = array.length; if (size < 1) throw new Exception("cummin requires at least one element"); double[] output; output.length = size; auto cumulativeMin = array[0]; foreach (i; 0..size) { if (array[i] < cumulativeMin) cumulativeMin = array[i]; output[i] = cumulativeMin; } return output; }   double[] cummax(double[] array) { auto size = array.length; if (size < 1) throw new Exception("cummax requires at least one element"); double[] output; output.length = size; auto cumulativeMax = array[0]; foreach (i; 0..size) { if (array[i] > cumulativeMax) cumulativeMax = array[i]; output[i] = cumulativeMax; } return output; }   double[] pminx(double[] array, double x) { auto size = array.length; if (size < 1) throw new Exception("pmin requires at least one element"); double[] result; result.length = size; foreach (i; 0..size) { if (array[i] < x) { result[i] = array[i]; } else { result[i] = x; } } return result; }   void doubleSay(double[] array) { writef("[ 1] %e", array[0]); foreach (i; 1..array.length) { writef(" %.10f", array[i]); if ((i+1) % 5 == 0) writef("\n[%2d]", i+1); } writeln; }   auto toArray(T,U)(U[] array) { T[] result; result.length = array.length; foreach(i; 0..array.length) { result[i] = to!T(array[i]); } return result; }   double[] pAdjust(double[] pvalues, string str) { auto size = pvalues.length; if (size < 1) throw new Exception("pAdjust requires at least one element"); int type = str.toLower.predSwitch!"a==b"( "bh", 0, "fdr", 0, "by", 1, "bonferroni", 2, "hochberg", 3, "holm", 4, "hommel", 5, { throw new Exception(text("'",str,"' doesn't match any accepted FDR types")); }() ); if (type == 2) { // Bonferroni method double[] result; result.length = size; foreach (i; 0..size) { auto b = pvalues[i] * size; if (b >= 1) { result[i] = 1; } else if (0 <= b && b < 1) { result[i] = b; } else { throw new Exception(text(b," is outside [0, 1)")); } } return result; } else if (type == 4) { // Holm method auto o = order(pvalues, false); auto o2Double = toArray!(double,int)(o); double[] cummaxInput; cummaxInput.length = size; foreach (i; 0..size) { cummaxInput[i] = (size-i) * pvalues[o[i]]; } auto ro = order(o2Double, false); auto cummaxOutput = cummax(cummaxInput); auto pmin = pminx(cummaxOutput, 1.0); double[] result; result.length = size; foreach (i; 0..size) { result[i] = pmin[ro[i]]; } return result; } else if (type == 5) { auto indices = seqLen(size, size); auto o = order(pvalues, false); double[] p; p.length = size; foreach (i; 0..size) { p[i] = pvalues[o[i]]; } auto o2Double = toArray!double(o); auto ro = order(o2Double, false); double[] q; q.length = size; double[] pa; pa.length = size; double[] npi; npi.length = size; foreach (i; 0..size) { npi[i] = p[i] * size / indices[i]; } auto min_ = reduce!min(npi); q[] = min_; pa[] = min_; foreach_reverse (j; 2..size) { auto ij = seqLen(1, size - j + 1); foreach (i; 0..size-j+1) { ij[i]--; } auto i2Length = j-1; int[] i2; i2.length = i2Length; foreach(i; 0..i2Length) { i2[i] = size-j+2+i-1; } auto pi2Length = i2Length; double q1 = j*p[i2[0]] / 2.0; foreach (i; 1..pi2Length) { auto temp_q1 = p[i2[i]] * j / (2.0 + i); if (temp_q1 < q1) q1 = temp_q1; } foreach (i; 0..size-j+1) { q[ij[i]] = min(p[ij[i]] * j, q1); } foreach(i; 0..i2Length) { q[i2[i]] = q[size-j]; } foreach(i; 0..size) if (pa[i] < q[i]) pa[i] = q[i]; } foreach (index; 0..size) { q[index] = pa[ro[index]]; } return q; }   double[] ni; ni.length = size; auto o = order(pvalues, true); auto oDouble = toArray!double(o); foreach (index; 0..size) { if (pvalues[index] < 0 || pvalues[index] > 1) { throw new Exception(text("array[", index, "] = ", pvalues[index], " is outside [0, 1]")); } ni[index] = cast(double) size / (size - index); } auto ro = order(oDouble, false); double[] cumminInput; cumminInput.length = size; if (type == 0) { // BH method foreach (index; 0..size) { cumminInput[index] = ni[index] * pvalues[o[index]]; } } else if (type == 1) { // BY method double q = 0; foreach (index; 1..size+1) q += 1.0 / index; foreach (index; 0..size) { cumminInput[index] = q * ni[index] * pvalues[o[index]]; } } else if (type == 3) { // Hochberg method foreach (index; 0..size) { cumminInput[index] = (index + 1) * pvalues[o[index]]; } } auto cumminArray =cummin(cumminInput); auto pmin = pminx(cumminArray, 1.0); double[] result; result.length = size; foreach (i; 0..size) { result[i] = pmin[ro[i]]; } return result; }   void main() { double[] 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 ];   double[][] correctAnswers = [ [ // 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 ] ]; auto types = ["bh", "by", "bonferroni", "hochberg", "holm", "hommel"]; foreach (type; 0..types.length) { auto q = pAdjust(pvalues, types[type]); double error = 0.0; foreach (i; 0..pvalues.length) { error += abs(q[i] - correctAnswers[type][i]); } doubleSay(q); writefln("\ntype %d = '%s' has a cumulative error of %g", type, types[type], 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
#Bracmat
Bracmat
( ( odli = M N NN item A Z R .  !arg:(?M.?N) & :?NN & whl ' ( !N:%?item ?N & (  !M:?A !item ?Z & !A (.) !Z:?M & !NN !item:?NN | ) ) & :?R & whl ' ( !M:?A (.) ?M & !NN:%?item ?NN & !R !A !item:?R ) & !R !M ) & (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)  : ?tests & whl ' ( !tests:(?M.?N) ?tests & put$("Data M:" !M) & put$("\tOrder N:" !N) & out$(\t odli$(!M.!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
#C.2B.2B
C++
  #include <iostream> #include <vector> #include <algorithm> #include <string>   template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; }   template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) { std::vector<T*> M_p(std::size(M)); for (auto i = 0; i < std::size(M_p); ++i) { M_p[i] = &M[i]; } for (auto e : N) { auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool { if (c != nullptr) { if (*c == e) return true; } return false; }); if (i != std::end(M_p)) { *i = nullptr; } } for (auto i = 0; i < std::size(N); ++i) { auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool { return c == nullptr; }); if (j != std::end(M_p)) { *j = &M[std::distance(std::begin(M_p), j)]; **j = N[i]; } } return M; }   int main() { std::vector<std::vector<std::vector<std::string>>> l = { { { "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" } } }; for (const auto& e : l) { std::cout << "M: "; print(e[0]); std::cout << ", N: "; print(e[1]); std::cout << ", M': "; auto res = orderDisjointArrayItems<std::string>(e[0], e[1]); print(res); std::cout << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
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
#BASIC
BASIC
100 DEF PROC sort_table REF t$(), ordering, col, reverse 110 DEFAULT ordering=0, col=1, reverse=0 120 REM implementation of sort not shown 190 END PROC
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program orderlist.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult1: .asciz "List1 < List2 \n" @ message result szMessResult2: .asciz "List1 => List2 \n" @ message result szCarriageReturn: .asciz "\n"   iTabList1: .int 1,2,3,4,5 .equ NBELEMENTS1, (. - iTabList1) /4 iTabList2: .int 1,2,1,5,2,2 .equ NBELEMENTS2, (. - iTabList2) /4 iTabList3: .int 1,2,3,4,5 .equ NBELEMENTS3, (. - iTabList3) /4 iTabList4: .int 1,2,3,4,5,6 .equ NBELEMENTS4, (. - iTabList4) /4 /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdriTabList1 mov r1,#NBELEMENTS1 ldr r2,iAdriTabList2 mov r3,#NBELEMENTS2 bl listeOrder cmp r0,#0 @ false ? beq 1f @ yes ldr r0,iAdrszMessResult1 @ list 1 < list 2 bl affichageMess @ display message b 2f 1: ldr r0,iAdrszMessResult2 bl affichageMess @ display message   2: ldr r0,iAdriTabList1 mov r1,#NBELEMENTS1 ldr r2,iAdriTabList3 mov r3,#NBELEMENTS3 bl listeOrder cmp r0,#0 @ false ? beq 3f @ yes ldr r0,iAdrszMessResult1 @ list 1 < list 2 bl affichageMess @ display message b 4f 3: ldr r0,iAdrszMessResult2 bl affichageMess @ display message 4: ldr r0,iAdriTabList1 mov r1,#NBELEMENTS1 ldr r2,iAdriTabList4 mov r3,#NBELEMENTS4 bl listeOrder cmp r0,#0 @ false ? beq 5f @ yes ldr r0,iAdrszMessResult1 @ list 1 < list 2 bl affichageMess @ display message b 6f 5: ldr r0,iAdrszMessResult2 bl affichageMess @ display message 6: 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdriTabList1: .int iTabList1 iAdriTabList2: .int iTabList2 iAdriTabList3: .int iTabList3 iAdriTabList4: .int iTabList4 iAdrszMessResult1: .int szMessResult1 iAdrszMessResult2: .int szMessResult2 iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of list 1 */ /* r1 contains list 1 size */ /* r2 contains the address of list 2 */ /* r3 contains list 2 size */ /* r0 returns 1 if list1 < list2 */ /* r0 returns 0 else */ listeOrder: push {r1-r7,lr} @ save registres cmp r1,#0 @ list 1 size = zero ? moveq r0,#-1 @ yes -> error beq 100f cmp r3,#0 @ list 2 size = zero ? moveq r0,#-2 @ yes -> error beq 100f mov r4,#0 @ index list 1 mov r5,#0 @ index list 2 1: ldr r6,[r0,r4,lsl #2] @ load list 1 element ldr r7,[r2,r5,lsl #2] @ load list 2 element cmp r6,r7 @ compar movgt r0,#0 @ list 1 > list 2 ? bgt 100f beq 2f @ list 1 = list 2 add r4,#1 @ increment index 1 cmp r4,r1 @ end list ? movge r0,#1 @ yes -> ok list 1 < list 2 bge 100f b 1b @ else loop 2: add r4,#1 @ increment index 1 cmp r4,r1 @ end list ? bge 3f @ yes -> verif size add r5,#1 @ else increment index 2 cmp r5,r3 @ end list 2 ? movge r0,#0 @ yes -> list 2 < list 1 bge 100f b 1b @ else loop 3: cmp r1,r3 @ compar size movge r0,#0 @ list 2 < list 1 movlt r0,#1 @ list 1 < list 2 100: pop {r1-r7,lr} @ restaur registers bx lr @ return /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur registers */ bx lr @ return  
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: numRows is 0; var array integer: values is [] (0, 1); var integer: row is 0; var integer: index is 0; begin write("Number of rows: "); readln(numRows); writeln("1" lpad succ(numRows) * 3); for row range 2 to numRows do write("" lpad (numRows - row) * 3); values &:= [] 0; for index range succ(row) downto 2 do values[index] +:= values[pred(index)]; write(" " <& values[index] lpad 5); end for; writeln; end for; end func;
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Raku
Raku
my $ask_count = 0; sub by_asking ( $a, $b ) { $ask_count++; constant $fmt = '%2d. Is %-6s [ less than | greater than | equal to ] %-6s? ( < = > ) '; constant %o = '<' => Order::Less, '=' => Order::Same, '>' => Order::More;   loop { my $input = prompt sprintf $fmt, $ask_count, $a, $b; return $_ with %o{ $input.trim }; say "Invalid input '$input'"; } }   my @colors = <violet red green indigo blue yellow orange>; my @sorted = @colors.sort: &by_asking; say (:@sorted);   die if @sorted».substr(0,1).join ne 'roygbiv'; my $expected_ask_count = @colors.elems * log(@colors.elems); warn "Too many questions? ({:$ask_count} > {:$expected_ask_count})" if $ask_count > $expected_ask_count;
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#REXX
REXX
/*REXX pgm orders some items based on (correct) answers from a carbon─based life form. */ colors= 'violet red green indigo blue yellow orange' q= 0; #= 0; $= do j=1 for words(colors); q= inSort( word(colors, j), q) end /*j*/ /*poise questions the CBLF about order.*/ say do i=1 for #; say ' query' right(i, length(#) )":"  !.i end /*i*/ /* [↑] show the list of queries to CBLF*/ say say 'final ordering: ' $ exit 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ getAns: #= # + 1; _= copies('─', 8); y_n= ' Answer y/n' do try=0 until ansU='Y' | ansU='N' if try>0 then say _ '(***error***) incorrect answer.' ask= _ ' is ' center(x,6) " less than " center(word($, mid+1),6) '?' say ask y_n; parse pull ans 1 ansU; ansU= space(ans); upper ansU end /*until*/;  !.#= ask ' ' ans; return /*──────────────────────────────────────────────────────────────────────────────────────*/ inSort: parse arg x, q; hi= words($); lo= 0 do q=q-1 while lo<hi; mid= (lo+hi) % 2 call getAns; if ansU=='Y' then hi= mid else lo= mid + 1 end /*q*/ $= subword($, 1, lo) x subword($, lo+1); return q
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.
#Bracmat
Bracmat
SAMPLES>write 18 / 2 * 3 + 7 34 SAMPLES>write 18 / (2 * 3) + 7 10
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.
#C
C
SAMPLES>write 18 / 2 * 3 + 7 34 SAMPLES>write 18 / (2 * 3) + 7 10
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.
#C.2B.2B
C++
SAMPLES>write 18 / 2 * 3 + 7 34 SAMPLES>write 18 / (2 * 3) + 7 10
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ABC-WORDS.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT DICT ASSIGN TO DISK ORGANIZATION LINE SEQUENTIAL.   DATA DIVISION. FILE SECTION. FD DICT LABEL RECORD STANDARD VALUE OF FILE-ID IS "unixdict.txt". 01 ENTRY. 03 WORD PIC X(32). 03 LETTERS PIC X OCCURS 32 TIMES, REDEFINES WORD.   WORKING-STORAGE SECTION. 01 LEN PIC 99. 01 MAXLEN PIC 99 VALUE 0. 01 I PIC 99. 01 OK-FLAG PIC X. 88 OK VALUE '*'.   PROCEDURE DIVISION. BEGIN. OPEN INPUT DICT.   FIND-LONGEST-WORD. READ DICT, AT END CLOSE DICT, GO TO PRINT-LONGEST-WORDS. PERFORM CHECK-WORD. GO TO FIND-LONGEST-WORD.   PRINT-LONGEST-WORDS. ALTER VALID-WORD TO PROCEED TO SHOW-WORD. OPEN INPUT DICT.   READ-WORDS. READ DICT, AT END CLOSE DICT, STOP RUN. PERFORM CHECK-WORD. GO TO READ-WORDS.   CHECK-WORD. MOVE ZERO TO LEN. INSPECT WORD TALLYING LEN FOR CHARACTERS BEFORE INITIAL SPACE. MOVE '*' TO OK-FLAG. PERFORM CHECK-CHAR-PAIR VARYING I FROM 2 BY 1 UNTIL NOT OK OR I IS GREATER THAN LEN. IF OK, PERFORM DO-WORD.   CHECK-CHAR-PAIR. IF LETTERS(I - 1) IS GREATER THAN LETTERS(I), MOVE SPACE TO OK-FLAG.   DO-WORD SECTION. VALID-WORD. GO TO CHECK-LENGTH. CHECK-LENGTH. IF LEN IS GREATER THAN MAXLEN, MOVE LEN TO MAXLEN. GO TO DONE. SHOW-WORD. IF LEN IS EQUAL TO MAXLEN, DISPLAY WORD. DONE. EXIT.
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
#MMIX
MMIX
argc IS $0 argv IS $1   LOC Data_Segment DataSeg GREG @   LOC @+1000 ItsPalStr IS @-Data_Segment BYTE "It's palindrome",10,0 LOC @+(8-@)&7 NoPalStr IS @-Data_Segment BYTE "It is not palindrome",10,0   LOC #100 GREG @ % input: $255 points to where the string to be checked is % returns $255 0 if not palindrome, not zero otherwise % trashs: $0,$1,$2,$3 % return address $4 DetectPalindrome LOC @ ADDU $1,$255,0 % $1 = $255 2H LDB $0,$1,0 % get byte at $1 BZ $0,1F % if zero, end (length) INCL $1,1 % $1++ JMP 2B % loop 1H SUBU $1,$1,1 % ptr last char of string ADDU $0,DataSeg,0 % $0 to data seg. 3H CMP $3,$1,$255 % is $0 == $255? BZ $3,4F % then jump LDB $3,$1,0 % otherwise get the byte STB $3,$0,0 % and copy it INCL $0,1 % $0++ SUB $1,$1,1 % $1-- JMP 3B 4H LDB $3,$1,0 STB $3,$0,0 % copy the last byte % now let us compare reversed string and straight string XOR $0,$0,$0 % index ADDU $1,DataSeg,0 6H LDB $2,$1,$0 % pick char from rev str LDB $3,$255,$0 % pick char from straight str BZ $3,PaliOk % finished as palindrome CMP $2,$2,$3 % == ? BNZ $2,5F % if not, exit INCL $0,1 % $0++ JMP 6B 5H XOR $255,$255,$255 GO $4,$4,0 % return false PaliOk NEG $255,0,1 GO $4,$4,0 % return true % The Main for testing the function % run from the command line % $ mmix ./palindrome.mmo ingirumimusnocteetconsumimurigni Main CMP argc,argc,2 % argc > 2? BN argc,3F % no -> not enough arg ADDU $1,$1,8 % argv+1 LDOU $255,$1,0 % argv[1] GO $4,DetectPalindrome BZ $255,2F % if not palindrome, jmp SETL $0,ItsPalStr % pal string ADDU $255,DataSeg,$0 JMP 1F 2H SETL $0,NoPalStr % no pal string ADDU $255,DataSeg,$0 1H TRAP 0,Fputs,StdOut % print 3H XOR $255,$255,$255 TRAP 0,Halt,0 % exit(0)
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##
#D
D
import std.stdio, std.string, std.conv, std.ascii, std.algorithm;   ulong ownCalcPass(in ulong password, in string nonce) pure nothrow @safe @nogc in { assert(nonce.representation.all!isDigit); } body { enum ulong m_1 = 0x_FFFF_FFFF_UL; enum ulong m_8 = 0x_FFFF_FFF8_UL; enum ulong m_16 = 0x_FFFF_FFF0_UL; enum ulong m_128 = 0x_FFFF_FF80_UL; enum ulong m_16777216 = 0X_FF00_0000_UL;   auto flag = true; ulong num1 = 0, num2 = 0;   foreach (immutable char c; nonce) { num1 &= m_1; num2 &= m_1;   switch (c) { case '0': num1 = num2; break; case '1': if (flag) num2 = password; flag = false; num1 = num2 & m_128; num1 = num1 >> 7; num2 = num2 << 25; num1 = num1 + num2; break; case '2': if (flag) num2 = password; flag = false; num1 = num2 & m_16; num1 = num1 >> 4; num2 = num2 << 28; num1 = num1 + num2; break; case '3': if (flag) num2 = password; flag = false; num1 = num2 & m_8; num1 = num1 >> 3; num2 = num2 << 29; num1 = num1 + num2; break; case '4': if (flag) num2 = password; flag = false; num1 = num2 << 1; num2 = num2 >> 31; num1 = num1 + num2; break; case '5': if (flag) num2 = password; flag = false; num1 = num2 << 5; num2 = num2 >> 27; num1 = num1 + num2; break; case '6': if (flag) num2 = password; flag = false; num1 = num2 << 12; num2 = num2 >> 20; num1 = num1 + num2; break; case '7': if (flag) num2 = password; flag = false; num1 = num2 & 0xFF00UL; num1 = num1 + ((num2 & 0xFFUL) << 24); num1 = num1 + ((num2 & 0xFF0000UL) >> 16); num2 = (num2 & m_16777216) >> 8; num1 = num1 + num2; break; case '8': if (flag) num2 = password; flag = false; num1 = num2 & 0xFFFFUL; num1 = num1 << 16; num1 = num1 + (num2 >> 24); num2 = num2 & 0xFF0000UL; num2 = num2 >> 8; num1 = num1 + num2; break; case '9': if (flag) num2 = password; flag = false; num1 = ~num2; break; default: // Impossible if contracts are active. assert(0, "Non-digit in nonce"); }   num2 = num1; }   return num1 & m_1; }   void ownTestCalcPass(in string sPassword, in string nonce, in ulong expected) in { assert(sPassword.representation.all!isDigit); assert(nonce.representation.all!isDigit); } body { immutable password = sPassword.to!ulong; immutable res = ownCalcPass(password, nonce); immutable m = format("%d %s %d %d", password, nonce, res, expected); writeln((res == expected) ? "PASS " : "FAIL ", m); }   void main() { ownTestCalcPass("12345", "603356072", 25280520UL); ownTestCalcPass("12345", "410501656", 119537670UL); }
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.
#Go
Go
package main   import ( "fmt" "log" "math" "os" "sort" "strconv" "strings" )   type pvalues = []float64   type iv1 struct { index int value float64 } type iv2 struct{ index, value int }   type direction int   const ( up direction = iota down )   // Test also for 'Unknown' correction type. var ctypes = []string{ "Benjamini-Hochberg", "Benjamini-Yekutieli", "Bonferroni", "Hochberg", "Holm", "Hommel", "Šidák", "Unknown", }   func minimum(p pvalues) float64 { m := p[0] for i := 1; i < len(p); i++ { if p[i] < m { m = p[i] } } return m }   func maximum(p pvalues) float64 { m := p[0] for i := 1; i < len(p); i++ { if p[i] > m { m = p[i] } } return m }   func adjusted(p pvalues, ctype string) (string, error) { err := check(p) if err != nil { return "", err } temp := pformat(adjust(p, ctype), 5) return fmt.Sprintf("\n%s\n%s", ctype, temp), nil }   func pformat(p pvalues, cols int) string { var lines []string for i := 0; i < len(p); i += cols { fchunk := p[i : i+cols] schunk := make([]string, cols) for j := 0; j < cols; j++ { schunk[j] = strconv.FormatFloat(fchunk[j], 'f', 10, 64) } lines = append(lines, fmt.Sprintf("[%2d]  %s", i, strings.Join(schunk, " "))) } return strings.Join(lines, "\n") }   func check(p []float64) error { cond := len(p) > 0 && minimum(p) >= 0 && maximum(p) <= 1 if !cond { return fmt.Errorf("p-values must be in range 0.0 to 1.0") } return nil }   func ratchet(p pvalues, dir direction) { size := len(p) m := p[0] if dir == up { for i := 1; i < size; i++ { if p[i] > m { p[i] = m } m = p[i] } } else { for i := 1; i < size; i++ { if p[i] < m { p[i] = m } m = p[i] } } for i := 0; i < size; i++ { if p[i] > 1.0 { p[i] = 1.0 } } }   func schwartzian(p pvalues, mult pvalues, dir direction) pvalues { size := len(p) order := make([]int, size) iv1s := make([]iv1, size) for i := 0; i < size; i++ { iv1s[i] = iv1{i, p[i]} } if dir == up { sort.Slice(iv1s, func(i, j int) bool { return iv1s[i].value > iv1s[j].value }) } else { sort.Slice(iv1s, func(i, j int) bool { return iv1s[i].value < iv1s[j].value }) } for i := 0; i < size; i++ { order[i] = iv1s[i].index } pa := make(pvalues, size) for i := 0; i < size; i++ { pa[i] = mult[i] * p[order[i]] } ratchet(pa, dir) order2 := make([]int, size) iv2s := make([]iv2, size) for i := 0; i < size; i++ { iv2s[i] = iv2{i, order[i]} } sort.Slice(iv2s, func(i, j int) bool { return iv2s[i].value < iv2s[j].value }) for i := 0; i < size; i++ { order2[i] = iv2s[i].index } pa2 := make(pvalues, size) for i := 0; i < size; i++ { pa2[i] = pa[order2[i]] } return pa2 }   func adjust(p pvalues, ctype string) pvalues { size := len(p) if size == 0 { return p } fsize := float64(size) switch ctype { case "Benjamini-Hochberg": mult := make(pvalues, size) for i := 0; i < size; i++ { mult[i] = fsize / float64(size-i) } return schwartzian(p, mult, up) case "Benjamini-Yekutieli": q := 0.0 for i := 1; i <= size; i++ { q += 1.0 / float64(i) } mult := make(pvalues, size) for i := 0; i < size; i++ { mult[i] = q * fsize / (fsize - float64(i)) } return schwartzian(p, mult, up) case "Bonferroni": p2 := make(pvalues, size) for i := 0; i < size; i++ { p2[i] = math.Min(p[i]*fsize, 1.0) } return p2 case "Hochberg": mult := make(pvalues, size) for i := 0; i < size; i++ { mult[i] = float64(i) + 1 } return schwartzian(p, mult, up) case "Holm": mult := make(pvalues, size) for i := 0; i < size; i++ { mult[i] = fsize - float64(i) } return schwartzian(p, mult, down) case "Hommel": order := make([]int, size) iv1s := make([]iv1, size) for i := 0; i < size; i++ { iv1s[i] = iv1{i, p[i]} } sort.Slice(iv1s, func(i, j int) bool { return iv1s[i].value < iv1s[j].value }) for i := 0; i < size; i++ { order[i] = iv1s[i].index } s := make(pvalues, size) for i := 0; i < size; i++ { s[i] = p[order[i]] } m := make(pvalues, size) for i := 0; i < size; i++ { m[i] = s[i] * fsize / (float64(i) + 1) } min := minimum(m) q := make(pvalues, size) for i := 0; i < size; i++ { q[i] = min } pa := make(pvalues, size) for i := 0; i < size; i++ { pa[i] = min } for j := size - 1; j >= 2; j-- { lower := make([]int, size-j+1) // lower indices for i := 0; i < len(lower); i++ { lower[i] = i } upper := make([]int, j-1) // upper indices for i := 0; i < len(upper); i++ { upper[i] = size - j + 1 + i } qmin := float64(j) * s[upper[0]] / 2.0 for i := 1; i < len(upper); i++ { temp := s[upper[i]] * float64(j) / (2.0 + float64(i)) if temp < qmin { qmin = temp } } for i := 0; i < len(lower); i++ { q[lower[i]] = math.Min(s[lower[i]]*float64(j), qmin) } for i := 0; i < len(upper); i++ { q[upper[i]] = q[size-j] } for i := 0; i < size; i++ { if pa[i] < q[i] { pa[i] = q[i] } } } order2 := make([]int, size) iv2s := make([]iv2, size) for i := 0; i < size; i++ { iv2s[i] = iv2{i, order[i]} } sort.Slice(iv2s, func(i, j int) bool { return iv2s[i].value < iv2s[j].value }) for i := 0; i < size; i++ { order2[i] = iv2s[i].index } pa2 := make(pvalues, size) for i := 0; i < size; i++ { pa2[i] = pa[order2[i]] } return pa2 case "Šidák": p2 := make(pvalues, size) for i := 0; i < size; i++ { p2[i] = 1.0 - math.Pow(1.0-float64(p[i]), fsize) } return p2 default: fmt.Printf("\nSorry, do not know how to do '%s' correction.\n", ctype) fmt.Println("Perhaps you want one of these?:") temp := make([]string, len(ctypes)-1) for i := 0; i < len(temp); i++ { temp[i] = fmt.Sprintf("  %s", ctypes[i]) } fmt.Println(strings.Join(temp, "\n")) os.Exit(1) } return p }   func main() { p := 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, } for _, ctype := range ctypes { s, err := adjusted(p, ctype) if err != nil { log.Fatal(err) } fmt.Println(s) } }
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
#Common_Lisp
Common Lisp
(defun order-disjoint (data order) (let ((order-b (make-hash-table :test 'equal))) (loop :for n :in order :do (incf (gethash n order-b 0))) (loop :for m :in data :collect (cond ((< 0 (gethash m order-b 0)) (decf (gethash m order-b)) (pop order)) (t 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
#BBC_BASIC
BBC BASIC
DIM table$(100,100) PROCsort_default(table$()) PROCsort_options(table$(), TRUE, 1, FALSE) END   DEF PROCsort_options(table$(), ordering%, column%, reverse%) DEF PROCsort_default(table$()) : LOCAL ordering%, column%, reverse% REM The sort goes here, controlled by the options REM Zero/FALSE values for the options shall select the defaults ENDPROC
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.
#Arturo
Arturo
compareLists: function [a,b][ loop 0..min @[size a, size b] 'i [ if a\[i] < b\[i] -> return true if a\[i] > b\[i] -> return false ] return less? size a size b ]   alias.infix '<=> 'compareLists   do [ print [1 2 1 3 2] <=> [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
#Sidef
Sidef
func pascal(rows) { var row = [1] { | n| say row.join(' ') row = [1, {|i| row[i] + row[i+1] }.map(0 .. n-2)..., 1] } << 1..rows }   pascal(10)
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Ruby
Ruby
items = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"] count = 0 sortedItems = [] items.each {|item| puts "Inserting '#{item}' into #{sortedItems}" spotToInsert = sortedItems.bsearch_index{|x| count += 1 print "(#{count}) Is #{item} < #{x}? " gets.start_with?('y') } || sortedItems.length # if insertion point is at the end, bsearch_index returns nil sortedItems.insert(spotToInsert, item) } p sortedItems
http://rosettacode.org/wiki/Order_by_pair_comparisons
Order by pair comparisons
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 Assume we have a set of items that can be sorted into an order by the user. The user is presented with pairs of items from the set in no order, the user states which item is less than, equal to, or greater than the other (with respect to their relative positions if fully ordered). Write a function that given items that the user can order, asks the user to give the result of comparing two items at a time and uses the comparison results to eventually return the items in order. Try and minimise the comparisons the user is asked for. Show on this page, the function ordering the colours of the rainbow: violet red green indigo blue yellow orange The correct ordering being: red orange yellow green blue indigo violet Note: Asking for/receiving user comparisons is a part of the task. Code inputs should not assume an ordering. The seven colours can form twenty-one different pairs. A routine that does not ask the user "too many" comparison questions should be used.
#Wren
Wren
import "/ioutil" for Input import "/fmt" for Fmt   // Inserts item x in list a, and keeps it sorted assuming a is already sorted. // If x is already in a, inserts it to the right of the rightmost x. var insortRight = Fn.new{ |a, x, q| var lo = 0 var hi = a.count while (lo < hi) { var mid = ((lo + hi)/2).floor q = q + 1 var prompt = Fmt.swrite("$2d: Is $6s less than $6s ? y/n: ", q, x, a[mid]) var less = Input.option(prompt, "yn") == "y" if (less) { hi = mid } else { lo = mid + 1 } } a.insert(lo, x) return q }   var order = Fn.new { |items| var ordered = [] var q = 0 for (item in items) { q = insortRight.call(ordered, item, q) } return ordered }   var items = "violet red green indigo blue yellow orange".split(" ") var ordered = order.call(items) System.print("\nThe colors of the rainbow, in sorted order, are:") System.print(ordered)
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.
#Cach.C3.A9_ObjectScript
Caché ObjectScript
SAMPLES>write 18 / 2 * 3 + 7 34 SAMPLES>write 18 / (2 * 3) + 7 10
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.
#Clojure
Clojure
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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.
#COBOL
COBOL
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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
#CoffeeScript
CoffeeScript
  ordered_word = (word) -> for i in [0...word.length - 1] return false unless word[i] <= word[i+1] true   show_longest_ordered_words = (candidates, dict_file_name) -> words = [''] for word in candidates continue if word.length < words[0].length if ordered_word word words = [] if word.length > words[0].length words.push word return if words[0] == '' # we came up empty console.log "Longest Ordered Words (source=#{dict_file_name}):" for word in words console.log word   dict_file_name = 'unixdict.txt' file_content = require('fs').readFileSync dict_file_name dict_words = file_content.toString().split '\n' show_longest_ordered_words dict_words, dict_file_name  
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
#Modula-2
Modula-2
MODULE Palindrome; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   PROCEDURE IsPalindrome(str : ARRAY OF CHAR) : BOOLEAN; VAR i,m : INTEGER; VAR buf : ARRAY[0..63] OF CHAR; BEGIN i := 0; m := HIGH(str) - 1; WHILE i<m DO IF str[i] # str[m-i] THEN RETURN FALSE END; INC(i) END; RETURN TRUE END IsPalindrome;   PROCEDURE Print(str : ARRAY OF CHAR); VAR buf : ARRAY[0..63] OF CHAR; BEGIN FormatString("%s: %b\n", buf, str, IsPalindrome(str)); WriteString(buf) END Print;   BEGIN Print(""); Print("z"); Print("aha"); Print("sees"); Print("oofoe"); Print("deified"); Print("Deified"); Print("amanaplanacanalpanama"); Print("ingirumimusnocteetconsumimurigni");   ReadChar END Palindrome.
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##
#Delphi
Delphi
  program OpenWebNet_password;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function ownCalcPass(password, nonce: string): Cardinal; begin var start := True; var num1 := 0; var num2 := num1; var i := password.ToInteger(); var pwd := i;   for var c in nonce do begin if c <> '0' then begin if start then num2 := pwd; start := False; end;   case c of '1': begin num1 := (num2 and $FFFFFF80) shr 7; num2 := num2 shl 25; end; '2': begin num1 := (num2 and $FFFFFFF0) shr 4; num2 := num2 shl 28; end; '3': begin num1 := (num2 and $FFFFFFF8) shr 3; num2 := num2 shl 29; end; '4': begin num1 := num2 shl 1; num2 := num2 shr 31; end; '5': begin num1 := num2 shl 5; num2 := num2 shr 27; end; '6': begin num1 := num2 shl 12; num2 := num2 shr 20; end; '7': begin var num3 := num2 and $0000FF00; var num4 := ((num2 and $000000FF) shl 24) or ((num2 and $00FF0000) shr 16); num1 := num3 or num4; num2 := (num2 and $FF000000) shr 8; end; '8': begin ; num1 := (num2 and $0000FFFF) shl 16 or (num2 shr 24); num2 := (num2 and $00FF0000) shr 8; end; '9': begin num1 := not num2; end; else num1 := num2; end;   num1 := num1 and $FFFFFFFF; num2 := num2 and $FFFFFFFF; if (c <> '0') and (c <> '9') then num1 := num1 or num2; num2 := num1; end; Result := num1; end;   function TestPasswordCalc(Password, nonce: string; expected: Cardinal): Integer; begin var res := ownCalcPass(Password, nonce); var m := format('%s  %s  %-10u  %-10u', [Password, nonce, res, expected]); if res = expected then writeln('PASS ' + m) else writeln('FAIL ' + m); end;   begin testPasswordCalc('12345', '603356072', 25280520); testPasswordCalc('12345', '410501656', 119537670); testPasswordCalc('12345', '630292165', 4269684735); readln; end.
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.
#Ada
Ada
with Lumen.Window; with Lumen.Events; with Lumen.Events.Animate; with GL; with GLU;   procedure OpenGL is   The_Window : Lumen.Window.Handle;   Program_Exit : Exception;   -- simply exit this program procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin raise Program_Exit; end;   -- Resize the scene procedure Resize_Scene (Width, Height : in Natural) is use GL; use GLU; begin -- reset current viewport glViewport (0, 0, GLsizei (Width), GLsizei (Height));   -- select projection matrix and reset it glMatrixMode (GL_PROJECTION); glLoadIdentity;   -- calculate aspect ratio gluPerspective (45.0, GLdouble (Width) / GLdouble (Height), 0.1, 100.0);   -- select modelview matrix and reset it glMatrixMode (GL_MODELVIEW); glLoadIdentity; end Resize_Scene;   procedure Init_GL is use GL; use GLU; begin -- smooth shading glShadeModel (GL_SMOOTH);   -- black background glClearColor (0.0, 0.0, 0.0, 0.0);   -- depth buffer setup glClearDepth (1.0); -- enable depth testing glEnable (GL_DEPTH_TEST); -- type of depth test glDepthFunc (GL_LEQUAL);   glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); end Init_GL;   -- Resize and Initialize the GL window procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is Height : Natural := Event.Resize_Data.Height; Width  : Natural := Event.Resize_Data.Width; begin -- prevent div by zero if Height = 0 then Height := 1; end if;   Resize_Scene (Width, Height); end;   procedure Draw is use GL; begin -- clear screen and depth buffer glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- reset current modelview matrix glLoadIdentity;   -- draw triangle glBegin (GL_TRIANGLES); glColor3f (1.0, 0.0, 0.0); glVertex3f ( 0.0, 1.0, 0.0); glColor3f (0.0, 1.0, 0.0); glVertex3f (-1.0, -1.0, 0.0); glColor3f (0.0, 0.0, 1.0); glVertex3f ( 1.0, -1.0, 0.0); glEnd; end Draw;   procedure Frame_Handler (Frame_Delta : in Duration) is begin Draw; Lumen.Window.Swap (The_Window); end Frame_Handler;   begin   Lumen.Window.Create (Win => The_Window, Name => "OpenGL Demo", Width => 640, Height => 480, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False));   Resize_Scene (640, 480); Init_GL;   Lumen.Events.Animate.Select_Events (Win => The_Window, FPS => Lumen.Events.Animate.Flat_Out, Frame => Frame_Handler'Unrestricted_Access, Calls => (Lumen.Events.Resized => Resize_Handler'Unrestricted_Access, Lumen.Events.Close_Window => Quit_Handler'Unrestricted_Access, others => Lumen.Events.No_Callback));   exception when Program_Exit => null; -- normal termination end OpenGL;
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.
#AutoHotkey
AutoHotkey
ahk := comobjactive("ahkdemo.ahk") ahk.hello("hello world") py := ComObjActive("python.server") py.write("hello") return
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.
#Java
Java
import java.util.Arrays; import java.util.Comparator;   public class PValueCorrection { private static int[] seqLen(int start, int end) { int[] result; if (start == end) { result = new int[end + 1]; for (int i = 0; i < result.length; ++i) { result[i] = i + 1; } } else if (start < end) { result = new int[end - start + 1]; for (int i = 0; i < result.length; ++i) { result[i] = start + i; } } else { result = new int[start - end + 1]; for (int i = 0; i < result.length; ++i) { result[i] = start - i; } } return result; }   private static int[] order(double[] array, boolean decreasing) { int size = array.length; int[] idx = new int[size]; double[] baseArr = new double[size]; for (int i = 0; i < size; ++i) { baseArr[i] = array[i]; idx[i] = i; }   Comparator<Integer> cmp; if (!decreasing) { cmp = Comparator.comparingDouble(a -> baseArr[a]); } else { cmp = (a, b) -> Double.compare(baseArr[b], baseArr[a]); }   return Arrays.stream(idx) .boxed() .sorted(cmp) .mapToInt(a -> a) .toArray(); }   private static double[] cummin(double[] array) { if (array.length < 1) throw new IllegalArgumentException("cummin requires at least one element"); double[] output = new double[array.length]; double cumulativeMin = array[0]; for (int i = 0; i < array.length; ++i) { if (array[i] < cumulativeMin) cumulativeMin = array[i]; output[i] = cumulativeMin; } return output; }   private static double[] cummax(double[] array) { if (array.length < 1) throw new IllegalArgumentException("cummax requires at least one element"); double[] output = new double[array.length]; double cumulativeMax = array[0]; for (int i = 0; i < array.length; ++i) { if (array[i] > cumulativeMax) cumulativeMax = array[i]; output[i] = cumulativeMax; } return output; }   private static double[] pminx(double[] array, double x) { if (array.length < 1) throw new IllegalArgumentException("pmin requires at least one element"); double[] result = new double[array.length]; for (int i = 0; i < array.length; ++i) { if (array[i] < x) { result[i] = array[i]; } else { result[i] = x; } } return result; }   private static void doubleSay(double[] array) { System.out.printf("[ 1] %e", array[0]); for (int i = 1; i < array.length; ++i) { System.out.printf(" %.10f", array[i]); if ((i + 1) % 5 == 0) System.out.printf("\n[%2d]", i + 1); } System.out.println(); }   private static double[] intToDouble(int[] array) { double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i]; } return result; }   private static double doubleArrayMin(double[] array) { if (array.length < 1) throw new IllegalArgumentException("pAdjust requires at least one element"); return Arrays.stream(array).min().orElse(Double.NaN); }   private static double[] pAdjust(double[] pvalues, String str) { int size = pvalues.length; if (size < 1) throw new IllegalArgumentException("pAdjust requires at least one element"); int type; switch (str.toLowerCase()) { case "bh": case "fdr": type = 0; break; case "by": type = 1; break; case "bonferroni": type = 2; break; case "hochberg": type = 3; break; case "holm": type = 4; break; case "hommel": type = 5; break; default: throw new IllegalArgumentException(str + " doesn't match any accepted FDR types"); }   if (type == 2) { // Bonferroni method double[] result = new double[size]; for (int i = 0; i < size; ++i) { double b = pvalues[i] * size; if (b >= 1) { result[i] = 1; } else if (0 <= b && b < 1) { result[i] = b; } else { throw new RuntimeException("" + b + " is outside [0, 1)"); } } return result; } else if (type == 4) { // Holm method int[] o = order(pvalues, false); double[] o2Double = intToDouble(o); double[] cummaxInput = new double[size]; for (int i = 0; i < size; ++i) { cummaxInput[i] = (size - i) * pvalues[o[i]]; } int[] ro = order(o2Double, false); double[] cummaxOutput = cummax(cummaxInput); double[] pmin = pminx(cummaxOutput, 1.0); double[] result = new double[size]; for (int i = 0; i < size; ++i) { result[i] = pmin[ro[i]]; } return result; } else if (type == 5) { int[] indices = seqLen(size, size); int[] o = order(pvalues, false); double[] p = new double[size]; for (int i = 0; i < size; ++i) { p[i] = pvalues[o[i]]; } double[] o2Double = intToDouble(o); int[] ro = order(o2Double, false); double[] q = new double[size]; double[] pa = new double[size]; double[] npi = new double[size]; for (int i = 0; i < size; ++i) { npi[i] = p[i] * size / indices[i]; } double min = doubleArrayMin(npi); Arrays.fill(q, min); Arrays.fill(pa, min); for (int j = size; j >= 2; --j) { int[] ij = seqLen(1, size - j + 1); for (int i = 0; i < size - j + 1; ++i) { ij[i]--; } int i2Length = j - 1; int[] i2 = new int[i2Length]; for (int i = 0; i < i2Length; ++i) { i2[i] = size - j + 2 + i - 1; } double q1 = j * p[i2[0]] / 2.0; for (int i = 1; i < i2Length; ++i) { double temp_q1 = p[i2[i]] * j / (2.0 + i); if (temp_q1 < q1) q1 = temp_q1; } for (int i = 0; i < size - j + 1; ++i) { q[ij[i]] = Math.min(p[ij[i]] * j, q1); } for (int i = 0; i < i2Length; ++i) { q[i2[i]] = q[size - j]; } for (int i = 0; i < size; ++i) { if (pa[i] < q[i]) { pa[i] = q[i]; } } } for (int i = 0; i < size; ++i) { q[i] = pa[ro[i]]; } return q; }   double[] ni = new double[size]; int[] o = order(pvalues, true); double[] oDouble = intToDouble(o); for (int i = 0; i < size; ++i) { if (pvalues[i] < 0 || pvalues[i] > 1) { throw new RuntimeException("array[" + i + "] = " + pvalues[i] + " is outside [0, 1]"); } ni[i] = (double) size / (size - i); } int[] ro = order(oDouble, false); double[] cumminInput = new double[size]; if (type == 0) { // BH method for (int i = 0; i < size; ++i) { cumminInput[i] = ni[i] * pvalues[o[i]]; } } else if (type == 1) { // BY method double q = 0; for (int i = 1; i < size + 1; ++i) { q += 1.0 / i; } for (int i = 0; i < size; ++i) { cumminInput[i] = q * ni[i] * pvalues[o[i]]; } } else if (type == 3) { // Hochberg method for (int i = 0; i < size; ++i) { cumminInput[i] = (i + 1) * pvalues[o[i]]; } } double[] cumminArray = cummin(cumminInput); double[] pmin = pminx(cumminArray, 1.0); double[] result = new double[size]; for (int i = 0; i < size; ++i) { result[i] = pmin[ro[i]]; } return result; }   public static void main(String[] args) { double[] pvalues = new double[]{ 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 };   double[][] correctAnswers = new double[][]{ new double[]{ // 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 }, new double[]{ // 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 }, new double[]{ // 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 }, new double[]{ // 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 }, new double[]{ // 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 }, new double[]{ // 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 } };   String[] types = new String[]{"bh", "by", "bonferroni", "hochberg", "holm", "hommel"}; for (int type = 0; type < types.length; ++type) { double[] q = pAdjust(pvalues, types[type]); double error = 0.0; for (int i = 0; i < pvalues.length; ++i) { error += Math.abs(q[i] - correctAnswers[type][i]); } doubleSay(q); System.out.printf("\ntype %d = '%s' has a cumulative error of %g\n", type, types[type], 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
#D
D
import std.stdio, std.string, std.algorithm, std.array, std.range, std.conv;   T[] orderDisjointArrayItems(T)(in T[] data, in T[] items) pure /*nothrow*/ @safe { int[] itemIndices; foreach (item; items.dup.sort().uniq) { immutable int itemCount = items.count(item); assert(data.count(item) >= itemCount, text("More of ", item, " than in data")); auto lastIndex = [-1]; foreach (immutable _; 0 .. itemCount) { immutable start = lastIndex.back + 1; lastIndex ~= data[start .. $].countUntil(item) + start; } itemIndices ~= lastIndex.dropOne; }   itemIndices.sort(); auto result = data.dup; foreach (index, item; zip(itemIndices, items)) result[index] = item; return result; }   void main() { immutable problems = "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 | A | A A B | A B B A | A B A B A B | A B A B A B | B A B A A B C C B A | A C A C A B C C B A | C A C A" .splitLines.map!(r => r.split("|")).array;   foreach (immutable p; problems) { immutable a = p[0].split; immutable b = p[1].split; writefln("%s | %s -> %-(%s %)", p[0].strip, p[1].strip, orderDisjointArrayItems(a, b)); } }
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
#Bracmat
Bracmat
( ( sortTable = table ordering column reverse .  !arg  : ( ?table . ( ? (ordering.?ordering) ? | ?&lexicographic:?ordering )  : ( ? (column.?column) ? | ?&1:?column )  : ( ? (reverse.?reverse) ? | ?&no:?reverse ) ) & (...) ) & (12.Claes.left) (11.Otto.right) (8.Frederikke.middle)  : ?table & sortTable$(!table.(column.2) (reverse.yes)) );
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
#C
C
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h>   typedef const char * String; typedef struct sTable { String * *rows; int n_rows,n_cols; } *Table;   typedef int (*CompareFctn)(String a, String b);   struct { CompareFctn compare; int column; int reversed; } sortSpec;   int CmprRows( const void *aa, const void *bb) { String *rA = *(String *const *)aa; String *rB = *(String *const *)bb; int sortCol = sortSpec.column;   String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol]; return sortSpec.compare( left, right ); }   /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * tbl parameter is a table of rows of strings * argSpec is a string containing zero or more of the letters o,c,r * if o is present - the corresponding optional argument is a function which * determines the ordering of the strings. * if c is present - the corresponding optional argument is an integer that * specifies the column to sort on. * if r is present - the corresponding optional argument is either * true(nonzero) or false(zero) and if true, the sort will b in reverse order * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int sortTable(Table tbl, const char* argSpec,... ) { va_list vl; const char *p; int c; sortSpec.compare = &strcmp; sortSpec.column = 0; sortSpec.reversed = 0;   va_start(vl, argSpec); if (argSpec) for (p=argSpec; *p; p++) { switch (*p) { case 'o': sortSpec.compare = va_arg(vl,CompareFctn); break; case 'c': c = va_arg(vl,int); if ( 0<=c && c<tbl->n_cols) sortSpec.column = c; break; case 'r': sortSpec.reversed = (0!=va_arg(vl,int)); break; } } va_end(vl); qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; }   void printTable( Table tbl, FILE *fout, const char *colFmts[]) { int row, col;   for (row=0; row<tbl->n_rows; row++) { fprintf(fout, " "); for(col=0; col<tbl->n_cols; col++) { fprintf(fout, colFmts[col], tbl->rows[row][col]); } fprintf(fout, "\n"); } fprintf(fout, "\n"); }   int ord(char v) { return v-'0'; }   /* an alternative comparison function */ int cmprStrgs(String s1, String s2) { const char *p1 = s1; const char *p2 = s2; const char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++; } if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); }   int main() { const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"}; String r1[] = { "a101", "red", "Java" }; String r2[] = { "ab40", "gren", "Smalltalk" }; String r3[] = { "ab9", "blue", "Fortran" }; String r4[] = { "ab09", "ylow", "Python" }; String r5[] = { "ab1a", "blak", "Factor" }; String r6[] = { "ab1b", "brwn", "C Sharp" }; String r7[] = { "Ab1b", "pink", "Ruby" }; String r8[] = { "ab1", "orng", "Scheme" };   String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 }; struct sTable table; table.rows = rows; table.n_rows = 8; table.n_cols = 3;   sortTable(&table, ""); printf("sort on col 0, ascending\n"); printTable(&table, stdout, colFmts);   sortTable(&table, "ro", 1, &cmprStrgs); printf("sort on col 0, reverse.special\n"); printTable(&table, stdout, colFmts);   sortTable(&table, "c", 1); printf("sort on col 1, ascending\n"); printTable(&table, stdout, colFmts);   sortTable(&table, "cr", 2, 1); printf("sort on col 2, reverse\n"); printTable(&table, stdout, colFmts); return 0; }
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.
#AutoHotkey
AutoHotkey
List1 := [1,2,1,3,2] List2 := [1,2,0,4,4,0,0,0] MsgBox % order(List1, List2)   order(L1, L2){ return L1.MaxIndex() < L2.MaxIndex() }
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
#Stata
Stata
function pascal1(n) { return(comb(J(1,n,0::n-1),J(n,1,0..n-1))) }   function pascal2(n) { a = I(n) a[.,1] = J(n,1,1) for (i=3; i<=n; i++) { a[i,2..i-1] = a[i-1,2..i-1]+a[i-1,1..i-2] } return(a) }   function pascal3(n) { a = J(n,n,0) for (i=1; i<n; i++) { a[i+1,i] = i } s = p = I(n) k = 1 for (i=0; i<n; i++) { p = p*a/k++ s = s+p } return(s) }
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.
#Common_Lisp
Common Lisp
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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.
#D
D
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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.
#Delphi
Delphi
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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
#Common_Lisp
Common Lisp
(defun orderedp (word) (reduce (lambda (prev curr) (when (char> prev curr) (return-from orderedp nil)) curr) word) t)   (defun longest-ordered-words (filename) (let ((result nil)) (with-open-file (s filename) (loop with greatest-length = 0 for word = (read-line s nil) until (null word) do (let ((length (length word))) (when (and (>= length greatest-length) (orderedp word)) (when (> length greatest-length) (setf greatest-length length result nil)) (push word result))))) (nreverse result)))   CL-USER> (longest-ordered-words "unixdict.txt") ("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")  
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
#Modula-3
Modula-3
MODULE Palindrome;   IMPORT Text;   PROCEDURE isPalindrome(string: TEXT): BOOLEAN = VAR len := Text.Length(string); BEGIN FOR i := 0 TO len DIV 2 - 1 DO IF Text.GetChar(string, i) # Text.GetChar(string, (len - i - 1)) THEN RETURN FALSE; END; END; RETURN TRUE; END isPalindrome; END Palindrome.
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##
#Go
Go
package main   import ( "fmt" "strconv" )   func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } 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 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 }   num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 }   func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s  %s  %-10d  %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } }   func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
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.
#AutoHotkey
AutoHotkey
hOpenGL32 := DllCall("LoadLibrary", "Str", "opengl32") Gui, +LastFound +Resize hDC := DllCall("GetDC", "uInt", WinExist())   VarSetCapacity(pfd, 40, 0) NumPut(40, pfd, 0, "uShort") NumPut(1, pfd, 2, "uShort") NumPut(37, pfd, 4, "uInt") NumPut(24, pfd, 9, "uChar") NumPut(16, pfd, 23, "uChar") DllCall("SetPixelFormat", "uInt", hDC, "uInt", DllCall("ChoosePixelFormat", "uInt", hDC, "uInt", &pfd), "uInt", &pfd)   hRC := DllCall("opengl32\wglCreateContext", "uInt", hDC) DllCall("opengl32\wglMakeCurrent", "uInt", hDC, "uInt", hRC) Gui, Show, w640 h480, Triangle OnExit, ExitSub SetTimer, Paint, 50 return     Paint: DllCall("opengl32\glClearColor", "Float", 0.3, "Float", 0.3, "Float", 0.3, "Float", 0) DllCall("opengl32\glClear", "uInt", 0x4100) ;GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT   DllCall("opengl32\glShadeModel", "uInt", 0x1D01) ;GL_SMOOTH   DllCall("opengl32\glLoadIdentity") DllCall("opengl32\glTranslatef", "Float", -15, "Float", -15, "Float", 0)   DllCall("opengl32\glBegin", "uInt", 0x0004) ;GL_TRIANGLES DllCall("opengl32\glColor3f", "Float", 1, "Float", 0, "Float", 0) DllCall("opengl32\glVertex2f", "Float", 0, "Float", 0) DllCall("opengl32\glColor3f", "Float", 0, "Float", 1, "Float", 0) DllCall("opengl32\glVertex2f", "Float", 30, "Float", 0) DllCall("opengl32\glColor3f", "Float", 0, "Float", 0, "Float", 1) DllCall("opengl32\glVertex2f", "Float", 0, "Float", 30) DllCall("opengl32\glEnd")   DllCall("SwapBuffers", "uInt", hDC) return     GuiSize: DllCall("opengl32\glViewport", "Int", 0, "Int", 0, "Int", A_GuiWidth, "Int", A_GuiHeight) DllCall("opengl32\glMatrixMode", "uInt", 0x1701) ;GL_PROJECTION DllCall("opengl32\glLoadIdentity") DllCall("opengl32\glOrtho", "Double", -30, "Double", 30, "Double", -30, "Double", 30, "Double", -30, "Double", 30) DllCall("opengl32\glMatrixMode", "uInt", 0x1700) ;GL_MODELVIEW return     GuiClose: ExitApp     ExitSub: DllCall("opengl32\wglMakeCurrent", "uInt", 0, "uInt", 0) DllCall("opengl32\wglDeleteContext", "uInt", hRC) DllCall("ReleaseDC", "uInt", hDC) DllCall("FreeLibrary", "uInt", hOpenGL32) ExitApp
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.
#Go
Go
package main   import ( "time" ole "github.com/go-ole/go-ole" "github.com/go-ole/go-ole/oleutil" )   func main() { ole.CoInitialize(0) unknown, _ := oleutil.CreateObject("Word.Application") word, _ := unknown.QueryInterface(ole.IID_IDispatch) oleutil.PutProperty(word, "Visible", true) documents := oleutil.MustGetProperty(word, "Documents").ToIDispatch() document := oleutil.MustCallMethod(documents, "Add").ToIDispatch() content := oleutil.MustGetProperty(document, "Content").ToIDispatch() paragraphs := oleutil.MustGetProperty(content, "Paragraphs").ToIDispatch() paragraph := oleutil.MustCallMethod(paragraphs, "Add").ToIDispatch() rnge := oleutil.MustGetProperty(paragraph, "Range").ToIDispatch() oleutil.PutProperty(rnge, "Text", "This is a Rosetta Code test document.")   time.Sleep(10 * time.Second)   oleutil.PutProperty(document, "Saved", true) oleutil.CallMethod(document, "Close", false) oleutil.CallMethod(word, "Quit") word.Release()   ole.CoUninitialize() }
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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckAutomation { ExitNow=false Declare WithEvents Alfa "WORD.APPLICATION" \\ minimize console Title "Minimized- Waiting", 0 Wait 300 Print "ok" With Alfa, "Visible", True Function ALFA_QUIT { Print "Why you close Word?" ExitNow=True } M=0 Every 20 { If ExitNow then exit M++ If M>500 then exit } Try { Method Alfa, "QUIT" } Declare Alfa Nothing if ExitNow then { Print format$("Finish {0:2} sec", M/1000) } Else { Print "Close Word manually" } \\ show again console Title "ok" } CheckAutomation  
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.
#Phix
Phix
#!/usr/bin/env python # -*- coding: utf-8 -*- import win32com.client from win32com.server.util import wrap, unwrap from win32com.server.dispatcher import DefaultDebugDispatcher from ctypes import * import commands import pythoncom import winerror from win32com.server.exception import Exception   clsid = "{55C2F76F-5136-4614-A397-12214CC011E5}" iid = pythoncom.MakeIID(clsid) appid = "python.server"   class VeryPermissive: def __init__(self): self.data = [] self.handle = 0 self.dobjects = {} def __del__(self): pythoncom.RevokeActiveObject(self.handle) def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: return getattr(self,name)(*args) if wFlags & pythoncom.DISPATCH_PROPERTYGET: try: # to avoid problems with byref param handling, tuple results are converted to lists. ret = self.__dict__[name] if type(ret)==type(()): ret = list(ret) return ret except KeyError: # Probably a method request. raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF): setattr(self, name, args[0]) return raise Exception(scode=winerror.E_INVALIDARG, desc="invalid wFlags") def write(self, x): print x return 0 import win32com.server.util, win32com.server.policy child = VeryPermissive() ob = win32com.server.util.wrap(child, usePolicy=win32com.server.policy.DynamicPolicy) try: handle = pythoncom.RegisterActiveObject(ob, iid, 0) except pythoncom.com_error, details: print "Warning - could not register the object in the ROT:", details handle = None child.handle = handle   ahk = win32com.client.Dispatch("ahkdemo.ahk") ahk.aRegisterIDs(clsid, appid) # autohotkey.exe ahkside.ahk # python /c/Python26/Scripts/ipython.py -wthread -i pythonside.py # must use -wthread otherwise calling com client hangs
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.
#Julia
Julia
using MultipleTesting, IterTools, Printf   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]   function printpvalues(v) for chunk in partition(v, 10) println(join((@sprintf("%4.7f", p) for p in chunk), ", ")) end end   println("Original p-values:") printpvalues(p) for corr in (Bonferroni(), BenjaminiHochberg(), BenjaminiYekutieli(), Holm(), Hochberg(), Hommel()) println("\n", corr) printpvalues(adjust(p, corr)) 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
#EchoLisp
EchoLisp
  (lib 'list) ;; for list-delete   (define dataM '((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)))   (define orderM '((mat cat) (cat mat) (C A C A) (E A D A) (B) (B A) (B A)))   (define (order-disjoint M N) (define R (append N null)) ;; tmp copy of N : delete w when used (for/list [(w M)] (if (not (member w R)) w ;; output as is (begin0 (first N) ;; replacer (set! N (rest N)) (set! R (list-delete R w))))))      
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
#C.2B.2B
C++
#include <vector> #include <algorithm> #include <string>   // helper comparator that is passed to std::sort() template <class T> struct sort_table_functor { typedef bool (*CompFun)(const T &, const T &); const CompFun ordering; const int column; const bool reverse; sort_table_functor(CompFun o, int c, bool r) : ordering(o), column(c), reverse(r) { } bool operator()(const std::vector<T> &x, const std::vector<T> &y) const { const T &a = x[column], &b = y[column]; return reverse ? ordering(b, a) : ordering(a, b); } };   // natural-order less-than comparator template <class T> bool myLess(const T &x, const T &y) { return x < y; }   // this is the function we call, which takes optional parameters template <class T> void sort_table(std::vector<std::vector<T> > &table, int column = 0, bool reverse = false, bool (*ordering)(const T &, const T &) = myLess) { std::sort(table.begin(), table.end(), sort_table_functor<T>(ordering, column, reverse)); }   #include <iostream>   // helper function to print our 3x3 matrix template <class T> void print_matrix(std::vector<std::vector<T> > &data) { for () { for (int j = 0; j < 3; j++) std::cout << data[i][j] << "\t"; std::cout << std::endl; } }   // order in descending length bool desc_len_comparator(const std::string &x, const std::string &y) { return x.length() > y.length(); }   int main() {   std::string data_array[3][3] = { {"a", "b", "c"}, {"", "q", "z"}, {"zap", "zip", "Zot"} };   std::vector<std::vector<std::string> > data_orig; for (int i = 0; i < 3; i++) { std::vector<std::string> row; for (int j = 0; j < 3; j++) row.push_back(data_array[i][j]); data_orig.push_back(row); } print_matrix(data_orig);   std::vector<std::vector<std::string> > data = data_orig; sort_table(data); print_matrix(data);   data = data_orig; sort_table(data, 2); print_matrix(data);   data = data_orig; sort_table(data, 1); print_matrix(data);   data = data_orig; sort_table(data, 1, true); print_matrix(data);   data = data_orig; sort_table(data, 0, false, desc_len_comparator); print_matrix(data);   return 0; }
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.
#AWK
AWK
  # syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK BEGIN { split("1,2,1,5,2",list1,",") split("1,2,1,5,2,2",list2,",") split("1,2,3,4,5",list3,",") split("1,2,3,4,5",list4,",") x = compare_array(list1,list2) ? "<" : ">=" ; printf("list1%slist2\n",x) x = compare_array(list2,list3) ? "<" : ">=" ; printf("list2%slist3\n",x) x = compare_array(list3,list4) ? "<" : ">=" ; printf("list3%slist4\n",x) exit(0) } function compare_array(arr1,arr2, ans,i) { ans = 0 for (i=1; i<=length(arr1); i++) { if (arr1[i] != arr2[i]) { ans = 1 break } } if (length(arr1) != length(arr2)) { ans = 1 } return(ans) }  
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
#Swift
Swift
func pascal(n:Int)->[Int]{ if n==1{ let a=[1] print(a) return a } else{ var a=pascal(n:n-1) var temp=a for i in 0..<a.count{ if i+1==a.count{ temp.append(1) break } temp[i+1] = a[i]+a[i+1] } a=temp print(a) return a } } let waste = pascal(n:10)  
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.
#Eiffel
Eiffel
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
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.
#Erlang
Erlang
(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.
#F.23
F#
(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
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh"; include "file.coh";   var filename: [uint8] := "unixdict.txt";   # Call a subroutine for every line in a file interface LineCb(line: [uint8]); sub ForEachLine(fcb: [FCB], fn: LineCb) is var linebuf: uint8[256]; var bufptr := &linebuf[0];   var len := FCBExt(fcb); # get length of file FCBSeek(fcb, 0); # start at beginning of file   while len > 0 loop var ch := FCBGetChar(fcb); if ch == '\n' then # end of line, terminate string [bufptr] := 0; fn(&linebuf[0]); bufptr := &linebuf[0]; else # add char to buffer [bufptr] := ch; bufptr := @next bufptr; end if; len := len - 1; end loop;   # If the file doesn't cleanly end on a line terminator, # also call for last incomplete line if ch != '\n' then [bufptr] := 0; fn(&linebuf[0]); end if; end sub;   # Check if the letters in a word appear in alphabetical order sub isOrdered(word: [uint8]): (r: uint8) is var cr := [word]; word := @next word; loop var cl := cr; cr := [word]; word := @next word; if cr < 32 then r := 1; return; elseif (cl | 32) > (cr | 32) then r := 0; return; end if; end loop; end sub;   # Find maximum length of ordered words var maxLen: uint8 := 0; sub MaxOrderedLength implements LineCb is var len := StrLen(line) as uint8; if maxLen < len and isOrdered(line) != 0 then maxLen := len; end if; end sub;   # Print all ordered words matching maximum length sub PrintMaxLenWord implements LineCb is if maxLen == StrLen(line) as uint8 and isOrdered(line) != 0 then print(line); print_nl(); end if; end sub;   var fcb: FCB; if FCBOpenIn(&fcb, filename) != 0 then print("cannot open unixdict.txt\n"); ExitWithError(); end if;   ForEachLine(&fcb, MaxOrderedLength); ForEachLine(&fcb, PrintMaxLenWord);   var foo := FCBClose(&fcb);
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
#Nanoquery
Nanoquery
def is_palindrome(s) temp = "" for char in s if "abcdefghikjklmnopqrstuvwxyz" .contains. lower(char) temp += lower(char) end end   return list(temp) = list(temp).reverse() end
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)
#Go
Go
package main   import ( "bufio" "crypto/rand" "fmt" "io/ioutil" "log" "math/big" "os" "strconv" "strings" "unicode" )   const ( charsPerLine = 48 chunkSize = 6 cols = 8 demo = true // would normally be set to false )   type fileType int   const ( otp fileType = iota enc dec )   var scnr = bufio.NewScanner(os.Stdin)   func check(err error) { if err != nil { log.Fatal(err) } }   func toAlpha(s string) string { var filtered []rune for _, r := range s { if unicode.IsUpper(r) { filtered = append(filtered, r) } } return string(filtered) }   func isOtpRelated(s string) bool { return strings.HasSuffix(s, ".1tp") || strings.HasSuffix(s, "1tp_cpy") || strings.HasSuffix(s, ".1tp_enc") || strings.HasSuffix(s, "1tp_dec") }   func makePad(nLines int) string { nChars := nLines * charsPerLine bytes := make([]byte, nChars) /* generate random upper case letters */ max := big.NewInt(26) for i := 0; i < nChars; i++ { n, err := rand.Int(rand.Reader, max) check(err) bytes[i] = byte(65 + n.Uint64()) } return inChunks(string(bytes), nLines, otp) }   func vigenere(text, key string, encrypt bool) string { bytes := make([]byte, len(text)) var ci byte for i, c := range text { if encrypt { ci = (byte(c) + key[i] - 130) % 26 } else { ci = (byte(c) + 26 - key[i]) % 26 } bytes[i] = ci + 65 } temp := len(bytes) % charsPerLine if temp > 0 { // pad with random characters so each line is a full one max := big.NewInt(26) for i := temp; i < charsPerLine; i++ { n, err := rand.Int(rand.Reader, max) check(err) bytes = append(bytes, byte(65+n.Uint64())) } } ft := enc if !encrypt { ft = dec } return inChunks(string(bytes), len(bytes)/charsPerLine, ft) }   func inChunks(s string, nLines int, ft fileType) string { nChunks := len(s) / chunkSize remainder := len(s) % chunkSize chunks := make([]string, nChunks) for i := 0; i < nChunks; i++ { chunks[i] = s[i*chunkSize : (i+1)*chunkSize] } if remainder > 0 { chunks = append(chunks, s[nChunks*chunkSize:]) } var sb strings.Builder for i := 0; i < nLines; i++ { j := i * cols sb.WriteString(" " + strings.Join(chunks[j:j+cols], " ") + "\n") } ss := " file\n" + sb.String() switch ft { case otp: return "# OTP" + ss case enc: return "# Encrypted" + ss default: // case dec: return "# Decrypted" + ss } }   func menu() int { fmt.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. `) choice := 0 for choice < 1 || choice > 6 { fmt.Print("Your choice (1 to 6) : ") scnr.Scan() choice, _ = strconv.Atoi(scnr.Text()) check(scnr.Err()) } return choice }   func main() { for { choice := menu() fmt.Println() switch choice { case 1: // Create OTP fmt.Println("Note that encrypted lines always contain 48 characters.\n") fmt.Print("OTP file name to create (without extension) : ") scnr.Scan() fileName := scnr.Text() + ".1tp" nLines := 0 for nLines < 1 || nLines > 1000 { fmt.Print("Number of lines in OTP (max 1000) : ") scnr.Scan() nLines, _ = strconv.Atoi(scnr.Text()) } check(scnr.Err()) key := makePad(nLines) file, err := os.Create(fileName) check(err) _, err = file.WriteString(key) check(err) file.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", fileName) if demo { // a copy of the OTP file would normally be on a different machine fileName2 := fileName + "_cpy" // copy for decryption file, err := os.Create(fileName2) check(err) _, err = file.WriteString(key) check(err) file.Close() fmt.Printf("'%s' has been created in the current directory.\n", fileName2) fmt.Println("\nThe contents of these files are :\n") fmt.Println(key) } case 2: // Delete OTP fmt.Println("Note that this will also delete ALL associated files.\n") fmt.Print("OTP file name to delete (without extension) : ") scnr.Scan() toDelete1 := scnr.Text() + ".1tp" check(scnr.Err()) toDelete2 := toDelete1 + "_cpy" toDelete3 := toDelete1 + "_enc" toDelete4 := toDelete1 + "_dec" allToDelete := []string{toDelete1, toDelete2, toDelete3, toDelete4} deleted := 0 fmt.Println() for _, name := range allToDelete { if _, err := os.Stat(name); !os.IsNotExist(err) { err = os.Remove(name) check(err) deleted++ fmt.Printf("'%s' has been deleted from the current directory.\n", name) } } if deleted == 0 { fmt.Println("There are no files to delete.") } case 3: // List OTPs fmt.Println("The OTP (and related) files in the current directory are:\n") files, err := ioutil.ReadDir(".") // already sorted by file name check(err) for _, fi := range files { name := fi.Name() if !fi.IsDir() && isOtpRelated(name) { fmt.Println(name) } } case 4: // Encrypt fmt.Print("OTP file name to use (without extension) : ") scnr.Scan() keyFile := scnr.Text() + ".1tp" if _, err := os.Stat(keyFile); !os.IsNotExist(err) { file, err := os.Open(keyFile) check(err) bytes, err := ioutil.ReadAll(file) check(err) file.Close() lines := strings.Split(string(bytes), "\n") le := len(lines) first := le for i := 0; i < le; i++ { if strings.HasPrefix(lines[i], " ") { first = i break } } if first == le { fmt.Println("\nThat file has no unused lines.") continue } lines2 := lines[first:] // get rid of comments and used lines   fmt.Println("Text to encrypt :-\n") scnr.Scan() text := toAlpha(strings.ToUpper(scnr.Text())) check(scnr.Err()) tl := len(text) nLines := tl / charsPerLine if tl%charsPerLine > 0 { nLines++ } if len(lines2) >= nLines { key := toAlpha(strings.Join(lines2[0:nLines], "")) encrypted := vigenere(text, key, true) encFile := keyFile + "_enc" file2, err := os.Create(encFile) check(err) _, err = file2.WriteString(encrypted) check(err) file2.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", encFile) for i := first; i < first+nLines; i++ { lines[i] = "-" + lines[i][1:] } file3, err := os.Create(keyFile) check(err) _, err = file3.WriteString(strings.Join(lines, "\n")) check(err) file3.Close() if demo { fmt.Println("\nThe contents of the encrypted file are :\n") fmt.Println(encrypted) } } else { fmt.Println("Not enough lines left in that file to do encryption.") } } else { fmt.Println("\nThat file does not exist.") } case 5: // Decrypt fmt.Print("OTP file name to use (without extension) : ") scnr.Scan() keyFile := scnr.Text() + ".1tp_cpy" check(scnr.Err()) if _, err := os.Stat(keyFile); !os.IsNotExist(err) { file, err := os.Open(keyFile) check(err) bytes, err := ioutil.ReadAll(file) check(err) file.Close() keyLines := strings.Split(string(bytes), "\n") le := len(keyLines) first := le for i := 0; i < le; i++ { if strings.HasPrefix(keyLines[i], " ") { first = i break } } if first == le { fmt.Println("\nThat file has no unused lines.") continue } keyLines2 := keyLines[first:] // get rid of comments and used lines   encFile := keyFile[0:len(keyFile)-3] + "enc" if _, err := os.Stat(encFile); !os.IsNotExist(err) { file2, err := os.Open(encFile) check(err) bytes, err := ioutil.ReadAll(file2) check(err) file2.Close() encLines := strings.Split(string(bytes), "\n")[1:] // exclude comment line nLines := len(encLines) if len(keyLines2) >= nLines { encrypted := toAlpha(strings.Join(encLines, "")) key := toAlpha(strings.Join(keyLines2[0:nLines], "")) decrypted := vigenere(encrypted, key, false) decFile := keyFile[0:len(keyFile)-3] + "dec" file3, err := os.Create(decFile) check(err) _, err = file3.WriteString(decrypted) check(err) file3.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", decFile) for i := first; i < first+nLines; i++ { keyLines[i] = "-" + keyLines[i][1:] } file4, err := os.Create(keyFile) check(err) _, err = file4.WriteString(strings.Join(keyLines, "\n")) check(err) file4.Close() if demo { fmt.Println("\nThe contents of the decrypted file are :\n") fmt.Println(decrypted) } } } else { fmt.Println("Not enough lines left in that file to do decryption.") } } else { fmt.Println("\nThat file does not exist.") } case 6: // Quit program return } } }
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##
#JavaScript
JavaScript
  function calcPass (pass, nonce) { var flag = true; var num1 = 0x0; var num2 = 0x0; var password = parseInt(pass, 10);   for (var c in nonce) { c = nonce[c]; if (c!='0') { if (flag) num2 = password; flag = false; } switch (c) { case '1': num1 = num2 & 0xFFFFFF80; num1 = num1 >>> 7; num2 = num2 << 25; num1 = num1 + num2; break; case '2': num1 = num2 & 0xFFFFFFF0; num1 = num1 >>> 4; num2 = num2 << 28; num1 = num1 + num2; break; case '3': num1 = num2 & 0xFFFFFFF8; num1 = num1 >>> 3; num2 = num2 << 29; num1 = num1 + num2; break; case '4': num1 = num2 << 1; num2 = num2 >>> 31; num1 = num1 + num2; break; case '5': num1 = num2 << 5; num2 = num2 >>> 27; num1 = num1 + num2; break; case '6': num1 = num2 << 12; num2 = num2 >>> 20; num1 = num1 + num2; break; case '7': num1 = num2 & 0x0000FF00; num1 = num1 + (( num2 & 0x000000FF ) << 24 ); num1 = num1 + (( num2 & 0x00FF0000 ) >>> 16 ); num2 = ( num2 & 0xFF000000 ) >>> 8; num1 = num1 + num2; break; case '8': num1 = num2 & 0x0000FFFF; num1 = num1 << 16; num1 = num1 + ( num2 >>> 24 ); num2 = num2 & 0x00FF0000; num2 = num2 >>> 8; num1 = num1 + num2; break; case '9': num1 = ~num2; break; case '0': num1 = num2; break; } num2 = num1; } return (num1 >>> 0).toString(); }   exports.calcPass = calcPass;   console.log ('openpass initialization'); function testCalcPass (pass, nonce, expected) { var res = calcPass (pass, nonce); var m = pass + ' ' + nonce + ' ' + res + ' ' + expected; if (res == parseInt(expected, 10)) console.log ('PASS '+m); else console.log ('FAIL '+m); }   testCalcPass ('12345', '603356072', '25280520'); testCalcPass ('12345', '410501656', '119537670'); testCalcPass ('12345', '630292165', '4269684735'); testCalcPass ('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.
#BaCon
BaCon
PRAGMA INCLUDE <GL/gl.h> <GL/freeglut.h> PRAGMA LDFLAGS GL glut   OPTION PARSE FALSE   SUB Triangle   glViewport(0, 0, 640, 480) glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)   glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT)   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()   glutSwapBuffers()   END SUB   glutInit(&argc, argv) glutInitWindowSize(640, 480) glutCreateWindow("Triangle")   glutDisplayFunc(Triangle) glutMainLoop()
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.
#Python
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import win32com.client from win32com.server.util import wrap, unwrap from win32com.server.dispatcher import DefaultDebugDispatcher from ctypes import * import commands import pythoncom import winerror from win32com.server.exception import Exception   clsid = "{55C2F76F-5136-4614-A397-12214CC011E5}" iid = pythoncom.MakeIID(clsid) appid = "python.server"   class VeryPermissive: def __init__(self): self.data = [] self.handle = 0 self.dobjects = {} def __del__(self): pythoncom.RevokeActiveObject(self.handle) def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_METHOD: return getattr(self,name)(*args) if wFlags & pythoncom.DISPATCH_PROPERTYGET: try: # to avoid problems with byref param handling, tuple results are converted to lists. ret = self.__dict__[name] if type(ret)==type(()): ret = list(ret) return ret except KeyError: # Probably a method request. raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF): setattr(self, name, args[0]) return raise Exception(scode=winerror.E_INVALIDARG, desc="invalid wFlags") def write(self, x): print x return 0 import win32com.server.util, win32com.server.policy child = VeryPermissive() ob = win32com.server.util.wrap(child, usePolicy=win32com.server.policy.DynamicPolicy) try: handle = pythoncom.RegisterActiveObject(ob, iid, 0) except pythoncom.com_error, details: print "Warning - could not register the object in the ROT:", details handle = None child.handle = handle   ahk = win32com.client.Dispatch("ahkdemo.ahk") ahk.aRegisterIDs(clsid, appid) # autohotkey.exe ahkside.ahk # python /c/Python26/Scripts/ipython.py -wthread -i pythonside.py # must use -wthread otherwise calling com client hangs
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.
#Kotlin
Kotlin
// version 1.1.51   import java.util.Arrays   typealias IAE = IllegalArgumentException   fun seqLen(start: Int, end: Int) = when { start == end -> IntArray(end + 1) { it + 1 } start < end -> IntArray(end - start + 1) { start + it } else -> IntArray(start - end + 1) { start - it } }   var baseArr: DoubleArray? = null   fun compareIncrease(a: Int, b: Int): Int = baseArr!![b].compareTo(baseArr!![a])   fun compareDecrease(a: Int, b: Int): Int = baseArr!![a].compareTo(baseArr!![b])   fun order(array: DoubleArray, decreasing: Boolean): IntArray { val size = array.size var idx = IntArray(size) { it } baseArr = array.copyOf() if (!decreasing) { idx = Arrays.stream(idx) .boxed() .sorted { a, b -> compareDecrease(a, b) } .mapToInt { it } .toArray() } else { idx = Arrays.stream(idx) .boxed() .sorted { a, b -> compareIncrease(a, b) } .mapToInt { it } .toArray() } baseArr = null return idx }   fun cummin(array: DoubleArray): DoubleArray { val size = array.size if (size < 1) throw IAE("cummin requires at least one element") val output = DoubleArray(size) var cumulativeMin = array[0] for (i in 0 until size) { if (array[i] < cumulativeMin) cumulativeMin = array[i] output[i] = cumulativeMin } return output }   fun cummax(array: DoubleArray): DoubleArray { val size = array.size if (size < 1) throw IAE("cummax requires at least one element") val output = DoubleArray(size) var cumulativeMax = array[0] for (i in 0 until size) { if (array[i] > cumulativeMax) cumulativeMax = array[i] output[i] = cumulativeMax } return output }   fun pminx(array: DoubleArray, x: Double): DoubleArray { val size = array.size if (size < 1) throw IAE("pmin requires at least one element") return DoubleArray(size) { if (array[it] < x) array[it] else x } }   fun doubleSay(array: DoubleArray) { print("[ 1] %e".format(array[0])) for (i in 1 until array.size) { print(" %.10f".format(array[i])) if ((i + 1) % 5 == 0) print("\n[%2d]".format(i + 1)) } println() }   fun intToDouble(array: IntArray) = DoubleArray(array.size) { array[it].toDouble() }   fun doubleArrayMin(array: DoubleArray) = if (array.size < 1) throw IAE("pAdjust requires at least one element") else array.min()!!   fun pAdjust(pvalues: DoubleArray, str: String): DoubleArray { val size = pvalues.size if (size < 1) throw IAE("pAdjust requires at least one element") val type = when(str.toLowerCase()) { "bh", "fdr" -> 0 "by" -> 1 "bonferroni" -> 2 "hochberg" -> 3 "holm" -> 4 "hommel" -> 5 else -> throw IAE("'$str' doesn't match any accepted FDR types") } if (type == 2) { // Bonferroni method return DoubleArray(size) { val b = pvalues[it] * size when { b >= 1 -> 1.0 0 <= b && b < 1 -> b else -> throw RuntimeException("$b is outside [0, 1)") } } } else if (type == 4) { // Holm method val o = order(pvalues, false) val o2Double = intToDouble(o) val cummaxInput = DoubleArray(size) { (size - it) * pvalues[o[it]] } val ro = order(o2Double, false) val cummaxOutput = cummax(cummaxInput) val pmin = pminx(cummaxOutput, 1.0) return DoubleArray(size) { pmin[ro[it]] } } else if (type == 5) { // Hommel method val indices = seqLen(size, size) val o = order(pvalues, false) val p = DoubleArray(size) { pvalues[o[it]] } val o2Double = intToDouble(o) val ro = order(o2Double, false) val q = DoubleArray(size) val pa = DoubleArray(size) val npi = DoubleArray(size) { p[it] * size / indices[it] } val min = doubleArrayMin(npi) q.fill(min) pa.fill(min) for (j in size - 1 downTo 2) { val ij = seqLen(1, size - j + 1) for (i in 0 until size - j + 1) ij[i]-- val i2Length = j - 1 val i2 = IntArray(i2Length) { size - j + 2 + it - 1 } val pi2Length = i2Length var q1 = j * p[i2[0]] / 2.0 for (i in 1 until pi2Length) { val temp_q1 = p[i2[i]] * j / (2.0 + i) if(temp_q1 < q1) q1 = temp_q1 } for (i in 0 until size - j + 1) { q[ij[i]] = minOf(p[ij[i]] * j, q1) } for (i in 0 until i2Length) q[i2[i]] = q[size - j] for (i in 0 until size) if (pa[i] < q[i]) pa[i] = q[i] } for (index in 0 until size) q[index] = pa[ro[index]] return q } val ni = DoubleArray(size) val o = order(pvalues, true) val oDouble = intToDouble(o) for (index in 0 until size) { if (pvalues[index] !in 0.0 .. 1.0) { throw RuntimeException("array[$index] = ${pvalues[index]} is outside [0, 1]") } ni[index] = size.toDouble() / (size - index) } val ro = order(oDouble, false) val cumminInput = DoubleArray(size) if (type == 0) { // BH method for (index in 0 until size) { cumminInput[index] = ni[index] * pvalues[o[index]] } } else if (type == 1) { // BY method var q = 0.0 for (index in 1 until size + 1) q += 1.0 / index for (index in 0 until size) { cumminInput[index] = q * ni[index] * pvalues[o[index]] } } else if (type == 3) { // Hochberg method for (index in 0 until size) { cumminInput[index] = (index + 1) * pvalues[o[index]] } } val cumminArray = cummin(cumminInput) val pmin = pminx(cumminArray, 1.0) return DoubleArray(size) { pmin[ro[it]] } }   fun main(args: Array<String>) { val pvalues = doubleArrayOf( 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 )   val correctAnswers = listOf( doubleArrayOf( // 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 ), doubleArrayOf( // 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 ), doubleArrayOf( // 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 ), doubleArrayOf( // 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 ), doubleArrayOf( // 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 ), doubleArrayOf( // 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 ) ) val types = listOf("bh", "by", "bonferroni", "hochberg", "holm", "hommel") val f = "\ntype %d = '%s' has cumulative error of %g" for (type in 0 until types.size) { val q = pAdjust(pvalues, types[type]) var error = 0.0 for (i in 0 until pvalues.size) { error += Math.abs(q[i] - correctAnswers[type][i]) } doubleSay(q) println(f.format(type, types[type], 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
#Elixir
Elixir
defmodule Order do def disjoint(m,n) do IO.write "#{Enum.join(m," ")} | #{Enum.join(n," ")} -> " Enum.chunk(n,2) |> Enum.reduce({m,0}, fn [x,y],{m,from} -> md = Enum.drop(m, from) if x > y and x in md and y in md do if Enum.find_index(md,&(&1==x)) > Enum.find_index(md,&(&1==y)) do new_from = max(Enum.find_index(m,&(&1==x)), Enum.find_index(m,&(&1==y))) + 1 m = swap(m,from,x,y) from = new_from end end {m,from} end) |> elem(0) |> Enum.join(" ") |> IO.puts end   defp swap(m,from,x,y) do ix = Enum.find_index(m,&(&1==x)) + from iy = Enum.find_index(m,&(&1==y)) + from vx = Enum.at(m,ix) vy = Enum.at(m,iy) m |> List.replace_at(ix,vy) |> List.replace_at(iy,vx) end end   [ {"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"} ] |> Enum.each(fn {m,n} -> Order.disjoint(String.split(m),String.split(n)) 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
#Factor
Factor
qw{ the cat sat on the mat } qw{ mat cat } make-slots
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
#Clojure
Clojure
(defn sort [table & {:keys [ordering column reverse?]  :or {ordering :lex, column 1}}] (println table ordering column reverse?))   (sort [1 8 3] :reverse? true) [1 8 3] :lex 1 true
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.
#BASIC256
BASIC256
  arraybase 1 dim list1(5): dim list2(6): dim list3(5): dim list4(5) list1 = {1, 2, 1, 5, 2} list2 = {1, 2, 1, 5, 2, 2} list3 = {1, 2, 3, 4, 5} list4 = {1, 2, 3, 4, 5}   if Orden(list1[], list2[]) then print "list1 < list2" else print "list 1>= list2" if Orden(list2[], list3[]) then print "list2 < list3" else print "list2 >= list3" if Orden(list3[], list4[]) then print "list3 < list4" else print "list3 >= list4" end   function Orden(listA[], listB[]) i = 0 l1 = listA[?] l2 = listB[?] while (listA[i] = listB[i]) and i < l1 and i < l2 i = i + 1 end while if listA[?] < listB[?] then return True if listA[?] > listB[?] then return False return l1 < l2 end function  
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.
#BBC_BASIC
BBC BASIC
DIM list1(4) : list1() = 1, 2, 1, 5, 2 DIM list2(5) : list2() = 1, 2, 1, 5, 2, 2 DIM list3(4) : list3() = 1, 2, 3, 4, 5 DIM list4(4) : list4() = 1, 2, 3, 4, 5   IF FNorder(list1(), list2()) PRINT "list1<list2" ELSE PRINT "list1>=list2" IF FNorder(list2(), list3()) PRINT "list2<list3" ELSE PRINT "list2>=list3" IF FNorder(list3(), list4()) PRINT "list3<list4" ELSE PRINT "list3>=list4" END   DEF FNorder(list1(), list2()) LOCAL i%, l1%, l2% l1% = DIM(list1(),1) : l2% = DIM(list2(),1) WHILE list1(i%) = list2(i%) AND i% < l1% AND i% < l2% i% += 1 ENDWHILE IF list1(i%) < list2(i%) THEN = TRUE IF list1(i%) > list2(i%) THEN = FALSE = l1% < l2%
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
#Tcl
Tcl
proc pascal_iterative n { if {$n < 1} {error "undefined behaviour for n < 1"} set row [list 1] lappend rows $row set i 1 while {[incr i] <= $n} { set prev $row set row [list 1] for {set j 1} {$j < [llength $prev]} {incr j} { lappend row [expr {[lindex $prev [expr {$j - 1}]] + [lindex $prev $j]}] } lappend row 1 lappend rows $row } return $rows }   puts [join [pascal_iterative 6] \n]
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.
#Factor
Factor
(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.
#Forth
Forth
(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.
#Fortran
Fortran
(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
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.string;   string[] result; size_t maxLen;   foreach (string word; "unixdict.txt".File.lines) { word = word.chomp; immutable len = word.walkLength; if (len < maxLen || !word.isSorted) continue; if (len > maxLen) { result = [word]; maxLen = len; } else result ~= word; }   writefln("%-(%s\n%)", result); }
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
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Utility.NString; //contains methods Explode() and Implode() which convert string -> list[char] and back   module Palindrome { IsPalindrome( text : string) : bool { Implode(Explode(text).Reverse()) == text; }   Main() : void { WriteLine("radar is a palindrome: {0}", IsPalindrome("radar")); } }
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)
#Haskell
Haskell
-- To compile into an executable: -- ghc -main-is OneTimePad OneTimePad.hs -- To run: -- ./OneTimePad --help   module OneTimePad (main) where   import Control.Monad import Data.Char import Data.Function (on) import qualified Data.Text as T import qualified Data.Text.IO as TI import Data.Time import System.Console.GetOpt import System.Environment import System.Exit import System.IO   -- Command-line options parsing data Options = Options { optCommand :: String , optInput :: IO T.Text , optOutput :: T.Text -> IO () , optPad :: (IO T.Text, T.Text -> IO ()) , optLines :: Int }   startOptions :: Options startOptions = Options { optCommand = "decrypt" , optInput = TI.getContents , optOutput = TI.putStr , optPad = (TI.getContents, TI.putStr) , optLines = 0 }   options :: [ OptDescr (Options -> IO Options) ] options = [ Option "e" ["encrypt"] (NoArg (\opt -> return opt { optCommand = "encrypt" })) "Encrypt file" , Option "d" ["decrypt"] (NoArg (\opt -> return opt { optCommand = "decrypt" })) "Decrypt file (default)" , Option "g" ["generate"] (NoArg (\opt -> return opt { optCommand = "generate" })) "Generate a one-time pad" , Option "i" ["input"] (ReqArg (\arg opt -> return opt { optInput = TI.readFile arg }) "FILE") "Input file (for decryption and encryption)" , Option "o" ["output"] (ReqArg (\arg opt -> return opt { optOutput = TI.writeFile arg }) "FILE") "Output file (for generation, decryption, and encryption)" , Option "p" ["pad"] (ReqArg (\arg opt -> return opt { optPad = (TI.readFile arg, TI.writeFile arg) }) "FILE") "One-time pad to use (for decryption and encryption)" , Option "l" ["lines"] (ReqArg (\arg opt -> return opt { optLines = read arg :: Int }) "LINES") "New one-time pad's length (in lines of 48 characters) (for generation)" , Option "V" ["version"] (NoArg (\_ -> do hPutStrLn stderr "Version 0.01" exitWith ExitSuccess)) "Print version" , Option "h" ["help"] (NoArg (\_ -> do prg <- getProgName putStrLn "usage: OneTimePad [-h] [-V] [--lines LINES] [-i FILE] [-o FILE] [-p FILE] [--encrypt | --decrypt | --generate]" hPutStrLn stderr (usageInfo prg options) exitWith ExitSuccess)) "Show this help message and exit" ]   main :: IO () main = do args <- getArgs let (actions, nonOptions, errors) = getOpt RequireOrder options args opts <- Prelude.foldl (>>=) (return startOptions) actions let Options { optCommand = command , optInput = input , optOutput = output , optPad = (inPad, outPad) , optLines = linecnt } = opts   case command of "generate" -> generate linecnt output "encrypt" -> do inputContents <- clean <$> input padContents <- inPad output $ format $ encrypt inputContents $ unformat $ T.concat $ dropWhile (\t -> T.head t == '-' || T.head t == '#') $ T.lines padContents "decrypt" -> do inputContents <- unformat <$> input padContents <- inPad output $ decrypt inputContents $ unformat $ T.concat $ dropWhile (\t -> T.head t == '-' || T.head t == '#') $ T.lines padContents let discardLines = ceiling $ ((/) `on` fromIntegral) (T.length inputContents) 48 outPad $ discard discardLines $ T.lines padContents   {- | Discard used pad lines. Is only called at decryption to enable using the same pad file for both encryption and decryption. -} discard :: Int -> [T.Text] -> T.Text discard 0 ts = T.unlines ts discard x (t:ts) = if (T.head t == '-' || T.head t == '#') then T.unlines [t, (discard x ts)] else T.unlines [(T.append (T.pack "- ") t), (discard (x-1) ts)]   {- | Clean the text from symbols that cannot be encrypted. -} clean :: T.Text -> T.Text clean = T.map toUpper . T.filter (\c -> let oc = ord c in oc >= 65 && oc <= 122 && (not $ oc >=91 && oc <= 96))   {- | Format text (usually encrypted text) for pretty-printing it in a similar way to the example from Wikipedia (see Rosetta Code page for this task) -} format :: T.Text -> T.Text format = T.unlines . map (T.intercalate (T.pack " ") . T.chunksOf 6) . T.chunksOf 48   {- | Unformat encrypted text, getting rid of characters that are irrelevant for decryption. -} unformat :: T.Text -> T.Text unformat = T.filter (\c -> c/='\n' && c/=' ')   {- | Generate a one-time pad and write it to file (specified as second parameter). Note: this only works on operating systems that have the "/dev/random" file. -} generate :: Int -> (T.Text -> IO ()) -> IO () generate lines output = do withBinaryFile "/dev/random" ReadMode (\handle -> do contents <- replicateM (48 * lines) $ hGetChar handle time <- getCurrentTime output $ T.unlines [ T.pack $ "# OTP pad, generated by https://github.com/kssytsrk/one-time-pad on " ++ show time , format $ T.pack $ map (chr . (65 +) . flip mod 26 . ord) contents ])   -- Helper function for encryption/decryption. crypt :: (Int -> Int -> Int) -> T.Text -> T.Text -> T.Text crypt f = T.zipWith ((chr .) . f `on` ord)   -- Encrypt first parameter's contents, using the second parameter as a key. encrypt :: T.Text -> T.Text -> T.Text encrypt = crypt ((((+65) . flip mod 26 . subtract 130) .) . (+))   -- Decrypt first parameter's contents, using the second parameter as a key. decrypt :: T.Text -> T.Text -> T.Text decrypt = crypt ((((+65) . flip mod 26) .) . (-))
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##
#Julia
Julia
function calcpass(passwd, nonce::String) startflag = true n1 = 0 n2 = 0 password = parse(Int, passwd) dact = Dict( '1' => () -> begin n1 = (n2 & 0xffffff80) >> 7; n2 <<= 25 end, '2' => () -> begin n1 = (n2 & 0xfffffff0) >> 4; n2 <<= 28 end, '3' => () -> begin n1 = (n2 & 0xfffffff8) >> 3; n2 <<= 29 end, '4' => () -> begin n1 = n2 << 1; n2 >>= 31 end, '5' => () -> begin n1 = n2 << 5; n2 >>= 27 end, '6' => () -> begin n1 = n2 << 12; n2 >>= 20 end, '7' => () -> begin n1 = (n2 & 0x0000ff00) | ((n2 & 0x000000ff) << 24) | ((n2 & 0x00ff0000) >> 16); n2 = (n2 & 0xff000000) >> 8 end, '8' => () -> begin n1 = ((n2 & 0x0000ffff) << 16) | (n2 >> 24); n2 = (n2 & 0x00ff0000) >> 8 end, '9' => () -> begin n1 = ~n2 end)   for c in nonce if !haskey(dact, c) n1 = n2 else if startflag n2 = password end startflag = false dact[c]() n1 &= 0xffffffff n2 &= 0xffffffff if c != '9' n1 |= n2 end end n2 = n1 end n1 end   function testcalcpass() tdata = [["12345", "603356072", "25280520"], ["12345", "410501656", "119537670"], ["12345", "630292165", "4269684735"], ["12345", "523781130", "537331200"]] for td in tdata pf = calcpass(td[1], td[2]) == parse(Int, td[3]) ? "Passes test." : "Fails test." println("Calculating pass for [$(td[1]), $(td[2])] = $(td[3]): $pf") end end   testcalcpass()  
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##
#Kotlin
Kotlin
// version 1.1.51   fun ownCalcPass(password: Long, nonce: String): Long { val m1 = 0xFFFF_FFFFL val m8 = 0xFFFF_FFF8L val m16 = 0xFFFF_FFF0L val m128 = 0xFFFF_FF80L val m16777216 = 0xFF00_0000L   var flag = true var num1 = 0L var num2 = 0L   for (c in nonce) { num2 = num2 and m1   when (c) { '1' -> { if (flag) num2 = password flag = false num1 = num2 and m128 num1 = num1 ushr 7 num2 = num2 shl 25 num1 = num1 + num2 }   '2' -> { if (flag) num2 = password flag = false num1 = num2 and m16 num1 = num1 ushr 4 num2 = num2 shl 28 num1 = num1 + num2 }   '3' -> { if (flag) num2 = password flag = false num1 = num2 and m8 num1 = num1 ushr 3 num2 = num2 shl 29 num1 = num1 + num2 }   '4' -> { if (flag) num2 = password flag = false num1 = num2 shl 1 num2 = num2 ushr 31 num1 = num1 + num2 }   '5' -> { if (flag) num2 = password flag = false num1 = num2 shl 5 num2 = num2 ushr 27 num1 = num1 + num2 }   '6' -> { if (flag) num2 = password flag = false num1 = num2 shl 12 num2 = num2 ushr 20 num1 = num1 + num2 }   '7' -> { if (flag) num2 = password flag = false num1 = num2 and 0xFF00L num1 = num1 + ((num2 and 0xFFL) shl 24) num1 = num1 + ((num2 and 0xFF0000L) ushr 16) num2 = (num2 and m16777216) ushr 8 num1 = num1 + num2 }   '8' -> { if (flag) num2 = password flag = false num1 = num2 and 0xFFFFL num1 = num1 shl 16 num1 = num1 + (num2 ushr 24) num2 = num2 and 0xFF0000L num2 = num2 ushr 8 num1 = num1 + num2 }   '9' -> { if (flag) num2 = password flag = false num1 = num2.inv() }   else -> num1 = num2 } num2 = num1 } return num1 and m1 }   fun ownTestCalcPass(passwd: String, nonce: String, expected: Long) { val res = ownCalcPass(passwd.toLong(), nonce) val m = "$passwd $nonce $res $expected" println(if (res == expected) "PASS $m" else "FAIL $m") }   fun main(args: Array<String>) { ownTestCalcPass("12345", "603356072", 25280520) ownTestCalcPass("12345", "410501656", 119537670) }
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.
#BBC_BASIC
BBC BASIC
*FLOAT64   SYS "LoadLibrary", "OPENGL32.DLL" TO opengl% SYS "GetProcAddress", opengl%, "wglCreateContext" TO `wglCreateContext` SYS "GetProcAddress", opengl%, "wglDeleteContext" TO `wglDeleteContext` SYS "GetProcAddress", opengl%, "wglMakeCurrent" TO `wglMakeCurrent` SYS "GetProcAddress", opengl%, "glMatrixMode" TO `glMatrixMode` SYS "GetProcAddress", opengl%, "glClear" TO `glClear` SYS "GetProcAddress", opengl%, "glBegin" TO `glBegin` SYS "GetProcAddress", opengl%, "glColor3dv" TO `glColor3dv` SYS "GetProcAddress", opengl%, "glVertex2dv" TO `glVertex2dv` SYS "GetProcAddress", opengl%, "glEnd" TO `glEnd`   MODE 8   PFD_MAIN_PLANE = 0 PFD_TYPE_RGBA = 0 PFD_DOUBLEBUFFER = 1 PFD_DRAW_TO_WINDOW = 4 PFD_SUPPORT_OPENGL = &20   GL_MODELVIEW = &1700 GL_TRIANGLES = 4 GL_DEPTH_BUFFER_BIT = &00000100 GL_COLOR_BUFFER_BIT = &00004000   ON CLOSE PROCcleanup : QUIT ON ERROR PROCcleanup : SYS "MessageBox", @hwnd%, REPORT$, 0, 48 : QUIT   DIM GLcolor{r#, g#, b#}, GLvertex{x#, y#} DIM pfd{nSize{l&,h&}, nVersion{l&,h&}, dwFlags%, iPixelType&, cColorBits&, \ \ cRedBits&, cRedShift&, cGreenBits&, cGreenShift&, cBlueBits&, cBlueShift&, \ \ cAlphaBits&, cAlphaShift&, cAccumBits&, cAccumRedBits&, cAccumGreenBits&, \ \ cAccumBlueBits&, cAccumAlphaBits&, cDepthBits&, cStencilBits&, cAuxBuffers&, \ \ iLayerType&, bReserved&, dwLayerMask%, dwVisibleMask%, dwDamageMask%}   pfd.nSize.l& = DIM(pfd{}) pfd.nVersion.l& = 1 pfd.dwFlags% = PFD_DRAW_TO_WINDOW OR PFD_SUPPORT_OPENGL OR PFD_DOUBLEBUFFER pfd.dwLayerMask% = PFD_MAIN_PLANE pfd.iPixelType& = PFD_TYPE_RGBA pfd.cColorBits& = 24 pfd.cDepthBits& = 16   SYS "GetDC", @hwnd% TO ghDC%   SYS "ChoosePixelFormat", ghDC%, pfd{} TO pixelformat% IF pixelformat% = 0 ERROR 100, "ChoosePixelFormat failed"   SYS "SetPixelFormat", ghDC%, pixelformat%, pfd{} TO res% IF res% = 0 ERROR 100, "SetPixelFormat failed"   SYS `wglCreateContext`, ghDC% TO ghRC% SYS `wglMakeCurrent`, ghDC%, ghRC% SYS `glMatrixMode`, GL_MODELVIEW   REPEAT WAIT 2 SYS `glClear`, GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT SYS `glBegin`, GL_TRIANGLES GLcolor.r# = 1.0 : GLcolor.g# = 0.0 : GLcolor.b# = 0.0 SYS `glColor3dv`, GLcolor{} GLvertex.x# = 0.0 : GLvertex.y# = 0.8 SYS `glVertex2dv`, GLvertex{} GLcolor.r# = 0.0 : GLcolor.g# = 1.0 : GLcolor.b# = 0.0 SYS `glColor3dv`, GLcolor{} GLvertex.x# = 0.8 : GLvertex.y# = -0.8 SYS `glVertex2dv`, GLvertex{} GLcolor.r# = 0.0 : GLcolor.g# = 0.0 : GLcolor.b# = 1.0 SYS `glColor3dv`, GLcolor{} GLvertex.x# = -0.8 : GLvertex.y# = -0.8 SYS `glVertex2dv`, GLvertex{} SYS `glEnd` SYS "SwapBuffers", ghDC% UNTIL FALSE END   DEF PROCcleanup ON ERROR OFF ghRC% += 0 : IF ghRC% SYS `wglDeleteContext`, ghRC%  : ghRC% = 0 ghDC% += 0 : IF ghDC% SYS "ReleaseDC", @hwnd%, ghDC% : ghDC% = 0 ENDPROC
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
#11l
11l
F one_of_n(lines) V choice = 0 L(line) lines I random:(0..L.index) == 0 choice = line R choice   F one_of_n_test(n = 10, trials = 1000000) V bins = [0] * n I n != 0 L 1..trials bins[one_of_n(0 .< n)]++ R bins   print(one_of_n_test())