Dataset Viewer
Auto-converted to Parquet Duplicate
task_url
large_stringlengths
31
69
task_name
large_stringlengths
3
41
task_description
large_stringlengths
39
5.64k
language_url
large_stringlengths
2
33
language_name
large_stringlengths
1
30
code
large_stringlengths
26
20.9k
loc
large_stringclasses
1 value
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
#Clean
Clean
import StdEnv   Start :: *World -> { {Real} } Start world # (console, world) = stdio world (_, dim1, console) = freadi console (_, dim2, console) = freadi console = createArray dim1 (createArray dim2 1.0)
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Prolog
Prolog
range_expand :- L = '-6,-3--1,3-5,7-11,14,15,17-20', writeln(L), atom_chars(L, LA), extract_Range(LA, R), maplist(study_Range, R, LR), pack_Range(LX, LR), writeln(LX).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % extract_Range(?In, ?Out) % In  : '-6,-3--1,3-5,7-11,14,15,17-20' % Out : [-6], [-3--1], [3-5],[7-11], [14],[15], [17-20] % extract_Range([], []).   extract_Range(X , [Range | Y1]) :- get_Range(X, U-U, Range, X1), extract_Range(X1, Y1).   get_Range([], Range-[], Range, []). get_Range([','|B], Range-[], Range, B) :- !.   get_Range([A | B], EC, Range, R) :- append_dl(EC, [A | U]-U, NEC), get_Range(B, NEC, Range, R).     append_dl(X-Y, Y-Z, X-Z).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % study Range(?In, ?Out) % In  : [-6] % Out : [-6,-6] % % In  : [-3--1] % Out : [-3, -1] % study_Range(Range1, [Deb, Deb]) :- catch(number_chars(Deb, Range1), Deb, false).   study_Range(Range1, [Deb, Fin]) :- append(A, ['-'|B], Range1), A \= [], number_chars(Deb, A), number_chars(Fin, B).   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % :- use_module(library(clpfd)). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Pack Range(?In, ?Out) % In  : -6, % Out : [-6] % % In  : -3, -2,-1 % Out : [-3,-1] % pack_Range([],[]).   pack_Range([X|Rest],[[X | V]|Packed]):- run(X,Rest, [X|V], RRest), pack_Range(RRest,Packed).     run(Fin,[Other|RRest], [Deb, Fin],[Other|RRest]):- Fin #\= Deb, Fin #\= Deb + 1, Other #\= Fin+1.   run(Fin,[],[_Var, Fin],[]).   run(Var,[Var1|LRest],[Deb, Fin], RRest):- Fin #\= Deb, Fin #\= Deb + 1, Var1 #= Var + 1, run(Var1,LRest,[Deb, Fin], RRest).   run(Val,[Other|RRest], [Val, Val],[Other|RRest]).
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#ABAP
ABAP
report z_sum_a_b. data: lv_output type i. selection-screen begin of block input. parameters: p_first type i, p_second type i. selection-screen end of block input.   at selection-screen output. %_p_first_%_app_%-text = 'First Number: '. %_p_second_%_app_%-text = 'Second Number: '.   start-of-selection. lv_output = p_first + p_second. write : / lv_output.
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#OCaml
OCaml
let rec aux acc paths = if List.mem [] paths then (List.rev acc) else let heads = List.map List.hd paths in let item = List.hd heads in let all_the_same = List.for_all ((=) item) (List.tl heads) in if all_the_same then aux (item::acc) (List.map List.tl paths) else (List.rev acc)   let common_prefix sep = function | [] -> invalid_arg "common_prefix" | dirs -> let paths = List.map (Str.split (Str.regexp_string sep)) dirs in let res = aux [] paths in (sep ^ (String.concat sep res))   let () = let dirs = [ "/home/user1/tmp/coverage/test"; "/home/user1/tmp/covert/operator"; "/home/user1/tmp/coven/members"; ] in print_endline (common_prefix "/" dirs); ;;
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediately repeated   character is any character that is   immediately   followed by an identical character (or characters).   Another word choice could've been   duplicated character,   but that might have ruled out   (to some readers)   triplicated characters   ···   or more. {This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   PL/I   BIF:   collapse.} Examples In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   t,   e, and   l   are repeated characters,   indicated by underscores (above),   even though they (those characters) appear elsewhere in the character string. So, after collapsing the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate   repeated   characters and   collapse   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   original string and its length   the resultant string and its length   the above strings should be "bracketed" with   <<<   and   >>>   (to delineate blanks)   «««Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here»»» Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except the 1st string: string number ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ 5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ 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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Collapse(s As String) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Enumerable.Range(1, s.Length - 1).Where(Function(i) s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray) End Function   Sub Main() Dim input() = { "", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", ControlChars.Quote + "If I were two-faced, would I be wearing this one?" + ControlChars.Quote + " --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " } For Each s In input Console.WriteLine($"old: {s.Length} «««{s}»»»") Dim c = Collapse(s) Console.WriteLine($"new: {c.Length} «««{c}»»»") Next End Sub   End Module
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Python
Python
next = str(int('123') + 1)
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Nemerle
Nemerle
System.Console.Write(System.DateTime.Now);
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or opening a new window with this URL is not part of the task. Additionally, it is permissible to serve the provided page as a plain text file (there is no requirement to serve properly formatted HTML here). The browser will generally do the right thing with simple text like this.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "listener.s7i";   const proc: main is func local var listener: aListener is listener.value; var file: sock is STD_NULL; begin aListener := openInetListener(8080); listen(aListener, 10); while TRUE do sock := accept(aListener); write(sock, "HTTP/1.1 200 OK\r\n\ \Content-Type: text/html; charset=UTF-8\r\n\ \\r\n\ \<html><body>Hello, world!</body></html>\n"); close(sock); end while; end func;
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   BYTE FUNC IsZero(REAL POINTER a) CHAR ARRAY s(10)   StrR(a,s) IF s(0)=1 AND s(1)='0 THEN RETURN (1) FI RETURN (0)   CARD FUNC MyMod(CARD a,b) REAL ar,br,dr CARD d,m   IF a>32767 THEN  ;Built-in DIV and MOD  ;do not work properly  ;for numbers greater than 32767 IntToReal(a,ar) IntToReal(b,br) RealDiv(ar,br,dr) d=RealToInt(dr) m=a-d*b ELSE m=a MOD b FI RETURN (m)   BYTE FUNC IsPrime(CARD a) CARD i   IF a<=1 THEN RETURN (0) FI   i=2 WHILE i*i<=a DO IF MyMod(a,i)=0 THEN RETURN (0) FI i==+1 OD RETURN (1)   BYTE FUNC AllDigitsArePrime(CARD a) BYTE i CHAR ARRAY s CHAR c   StrC(a,s) FOR i=1 TO s(0) DO c=s(i) IF c#'2 AND c#'3 AND c#'5 AND c#'7 THEN RETURN (0) FI OD RETURN (1)   PROC Main() BYTE count CARD a   Put(125) PutE() ;clear screen PrintE("Sequence from 1st to 25th:") count=0 a=1 DO IF AllDigitsArePrime(a)=1 AND IsPrime(a)=1 THEN count==+1 IF count<=25 THEN PrintC(a) Put(32) ELSEIF count=100 THEN PrintF("%E%E100th: %U%E",a) EXIT FI FI a==+1 OD RETURN
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. Task Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#Clojure
Clojure
(ns cyclelengths (:gen-class))   (defn factorial [n] " n! " (apply *' (range 1 (inc n)))) ; Use *' (vs. *) to allow arbitrary length arithmetic   (defn pow [n i] " n^i" (apply *' (repeat i n)))   (defn analytical [n] " Analytical Computation " (->>(range 1 (inc n)) (map #(/ (factorial n) (pow n %) (factorial (- n %)))) ;calc n %)) (reduce + 0)))   ;; Number of random times to test each n (def TIMES 1000000)   (defn single-test-cycle-length [n] " Single random test of cycle length " (loop [count 0 bits 0 x 1] (if (zero? (bit-and x bits)) (recur (inc count) (bit-or bits x) (bit-shift-left 1 (rand-int n))) count)))   (defn avg-cycle-length [n times] " Average results of single tests of cycle lengths " (/ (reduce + (for [i (range times)] (single-test-cycle-length n))) times))   ;; Show Results (println "\tAvg\t\tExp\t\tDiff") (doseq [q (range 1 21) :let [anal (double (analytical q)) avg (double (avg-cycle-length q TIMES)) diff (Math/abs (* 100 (- 1 (/ avg anal))))]] (println (format "%3d\t%.4f\t%.4f\t%.2f%%" q avg anal diff)))  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing every k {\displaystyle k} -th prisoner and killing him. As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. > For example, if there are n = 5 {\displaystyle n=5} prisoners and k = 2 {\displaystyle k=2} , the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2. Task Given any   n , k > 0 {\displaystyle n,k>0} ,   find out which prisoner will be the final survivor. In one such incident, there were 41 prisoners and every 3rd prisoner was being killed   ( k = 3 {\displaystyle k=3} ). Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale. Which number was he? Extra The captors may be especially kind and let m {\displaystyle m} survivors free, and Josephus might just have   m − 1 {\displaystyle m-1}   friends to save. Provide a way to calculate which prisoner is at any given position on the killing sequence. Notes You can always play the executioner and follow the procedure exactly as described, walking around the circle, counting (and cutting off) heads along the way. This would yield the complete killing sequence and answer the above questions, with a complexity of probably O ( k n ) {\displaystyle O(kn)} . However, individually it takes no more than O ( m ) {\displaystyle O(m)} to find out which prisoner is the m {\displaystyle m} -th to die. If it's more convenient, you can number prisoners from   1 {\displaystyle 1} to n {\displaystyle n}   instead.   If you choose to do so, please state it clearly. An alternative description has the people committing assisted suicide instead of being executed, and the last person simply walks away. These details are not relevant, at least not mathematically.
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do io.put_string ("Survivor is prisoner: " + execute (12, 4).out) end   execute (n, k: INTEGER): INTEGER -- Survivor of 'n' prisoners, when every 'k'th is executed. require n_positive: n > 0 k_positive: k > 0 n_larger: n > k local killidx: INTEGER prisoners: LINKED_LIST [INTEGER] do create prisoners.make across 0 |..| (n - 1) as c loop prisoners.extend (c.item) end io.put_string ("Prisoners are executed in the order:%N") killidx := 1 from until prisoners.count <= 1 loop killidx := killidx + k - 1 from until killidx <= prisoners.count loop killidx := killidx - prisoners.count end io.put_string (prisoners.at (killidx).out + "%N") prisoners.go_i_th (killidx) prisoners.remove end Result := prisoners.at (1) ensure Result_in_range: Result >= 0 and Result < n end   end  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Groovy
Groovy
def commaQuibbling = { it.size() < 2 ? "{${it.join(', ')}}" : "{${it[0..-2].join(', ')} and ${it[-1]}}" }
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#PicoLisp
PicoLisp
  LEAVE The LEAVE statement terminates execution of a loop. Execution resumes at the next statement after the loop. ITERATE The ITERATE statement causes the next iteration of the loop to commence. Any statements between ITERATE and the end of the loop are not executed. STOP Terminates execution of either a task or the entire program. SIGNAL FINISH Terminates execution of a program in a nice way. SIGNAL statement SIGNAL <condition> raises the named condition. The condition may be one of the hardware or software conditions such as OVERFLOW, UNDERFLOW, ZERODIVIDE, SUBSCRIPTRANGE, STRINGRANGE, etc, or a user-defined condition. CALL The CALL statement causes control to transfer to the named subroutine. SELECT The SELECT statement permits the execution of just one of a list of statements (or groups of statements). It is sort of like a computed GOTO. GO TO The GO TO statement causes control to be transferred to the named statement. It can also be used to transfer control to any one of an array of labelled statements. (This form is superseded by SELECT, above.) [GO TO can also be spelled as GOTO].  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
mystring = InputString["give me a string please"]; myinteger = Input["give me an integer please"];
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Swift
Swift
public enum IntegrationType : CaseIterable { case rectangularLeft case rectangularRight case rectangularMidpoint case trapezium case simpson }   public func integrate( from: Double, to: Double, n: Int, using: IntegrationType = .simpson, f: (Double) -> Double ) -> Double { let integrationFunc: (Double, Double, Int, (Double) -> Double) -> Double   switch using { case .rectangularLeft: integrationFunc = integrateRectL case .rectangularRight: integrationFunc = integrateRectR case .rectangularMidpoint: integrationFunc = integrateRectMid case .trapezium: integrationFunc = integrateTrapezium case .simpson: integrationFunc = integrateSimpson }   return integrationFunc(from, to, n, f) }   private func integrateRectL(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x) x += h }   return h * sum }   private func integrateRectR(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x + h) x += h }   return h * sum }   private func integrateRectMid(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x + h / 2.0) x += h }   return h * sum }   private func integrateTrapezium(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var sum = f(from) + f(to)   for i in 1..<n { sum += 2 * f(from + Double(i) * h) }   return h * sum / 2 }   private func integrateSimpson(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var sum1 = 0.0 var sum2 = 0.0   for i in 0..<n { sum1 += f(from + h * Double(i) + h / 2.0) }   for i in 1..<n { sum2 += f(from + h * Double(i)) }   return h / 6.0 * (f(from) + f(to) + 4.0 * sum1 + 2.0 * sum2) }   let types = IntegrationType.allCases   print("f(x) = x^3:", types.map({ integrate(from: 0, to: 1, n: 100, using: $0, f: { pow($0, 3) }) })) print("f(x) = 1 / x:", types.map({ integrate(from: 1, to: 100, n: 1000, using: $0, f: { 1 / $0 }) })) print("f(x) = x, 0 -> 5_000:", types.map({ integrate(from: 0, to: 5_000, n: 5_000_000, using: $0, f: { $0 }) })) print("f(x) = x, 0 -> 6_000:", types.map({ integrate(from: 0, to: 6_000, n: 6_000_000, using: $0, f: { $0 }) }))
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 Task Create a program or script invocation to find all the events with magnitude greater than 6 Assuming an appropriate name e.g. "data.txt" for the file: Either: Show how your program is invoked to process a data file of that name. Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
#Phixmonti
Phixmonti
argument tail nip len dup if get nip else drop drop "data.txt" endif   dup "r" fopen dup 0 < if drop "Could not open '" print print "' for reading" print -1 quit endif nip   true while dup fgets dup 0 < if drop false else dup split 3 get tonum 6 > if drop print else drop drop endif true endif endwhile fclose
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Io
Io
mums := list(2,4,3,1,2) sorted := nums sort # returns a new sorted array. 'nums' is unchanged nums sortInPlace # sort 'nums' "in-place"
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Water_collected_between_towers
Water collected between towers
Task In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ██ 9 ██ 8 ██ 8 ██ 7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██ 6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██ 5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████ 4 ██ ██ ████████ 4 ██≈≈██≈≈████████ 3 ██████ ████████ 3 ██████≈≈████████ 2 ████████████████ ██ 2 ████████████████≈≈██ 1 ████████████████████ 1 ████████████████████ In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele Water collected between towers on Stack Overflow, from which the example above is taken) An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
#Groovy
Groovy
  Integer waterBetweenTowers(List<Integer> towers) { // iterate over the vertical axis. There the amount of water each row can hold is // the number of empty spots, minus the empty spots at the beginning and end return (1..towers.max()).collect { height -> // create a string representing the row, '#' for tower material and ' ' for air // use .trim() to remove spaces at beginning and end and then count remaining spaces towers.collect({ it >= height ? "#" : " " }).join("").trim().count(" ") }.sum() }   tasks = [ [1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6] ]   tasks.each { println "$it => total water: ${waterBetweenTowers it}" }  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Get two integers from the user. Then,   display a message if the first integer is:   less than,   equal to,   or   greater than the second integer. Test the condition   for each case separately,   so that   all three comparison operators are used   in the code. Related task   String comparison
#Common_Lisp
Common Lisp
(let ((a (read *standard-input*)) (b (read *standard-input*))) (cond ((not (numberp a)) (format t "~A is not a number." a)) ((not (numberp b)) (format t "~A is not a number." b)) ((< a b) (format t "~A is less than ~A." a b)) ((> a b) (format t "~A is greater than ~A." a b)) ((= a b) (format t "~A is equal to ~A." a b)) (t (format t "Cannot determine relevance between ~A and ~B!" a b)))))
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 Task If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: Poke the necessary opcodes into a memory location. Provide a means to pass two values to the machine code. Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
#Common_Lisp
Common Lisp
;;Note that by using the 'CFFI' library, one can apply this procedure portably in any lisp implementation; ;; in this code however I chose to demonstrate only the implementation-dependent programs.   ;;CCL ;; Allocate a memory pointer and poke the opcode into it (defparameter ptr (ccl::malloc 9))   (loop for i in '(139 68 36 4 3 68 36 8 195) for j from 0 do (setf (ccl::%get-unsigned-byte ptr j) i))   ;; Execute with the required arguments and return the result as an unsigned-byte (ccl::ff-call ptr :UNSIGNED-BYTE 7 :UNSIGNED-BYTE 12 :UNSIGNED-BYTE)   ;; Output = 19   ;; Free the pointer (ccl::free ptr)   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;SBCL (defparameter mmap (list 139 68 36 4 3 68 36 8 195))   (defparameter pointer (sb-alien:make-alien sb-alien:unsigned-char (length mmap)))   (defparameter callp (loop for byte in mmap for i from 0 do (setf (sb-alien:deref pointer i) byte) finally (return (sb-alien:cast pointer (function integer integer integer)))))   (sb-alien:alien-funcall callp 7 12)   (loop for i from 0 below 18 collect (sb-alien:deref ptr i))   (sb-alien:free-alien pointer)   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;CLISP (defparameter mmap (list 139 68 36 4 3 68 36 8 195))   (defparameter POINTER (FFI:FOREIGN-ADDRESS (FFI:FOREIGN-ALLOCATE 'FFI:UINT8 :COUNT 9)))   (loop for i in mmap for j from 0 do (FUNCALL #'(SETF FFI:MEMORY-AS) i POINTER 'FFI:INT j))   (FUNCALL (FFI:FOREIGN-FUNCTION POINTER (LOAD-TIME-VALUE (FFI:PARSE-C-TYPE '(FFI:C-FUNCTION (:ARGUMENTS 'FFI:INT 'FFI:INT) (:RETURN-TYPE FFI:INT) (:LANGUAGE :STDC))))) 7 12)   (FFI:FOREIGN-FREE POINTER)  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, not 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. 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
#SNOBOL4
SNOBOL4
  output = "Byte length: " size(trim(input)) end  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Lambdatalk
Lambdatalk
  {def A {A.new {S.map {lambda {:x} {* :x :x}} {S.serie 0 10} }}}   {A.get 3 {A}} // equivalent to A[3] -> 9 {A.get 4 {A}} -> 16  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#Haskell
Haskell
import Data.List.Ordered   powers :: Int -> [Int] powers m = map (^ m) [0..]   squares :: [Int] squares = powers 2   cubes :: [Int] cubes = powers 3   foo :: [Int] foo = filter (not . has cubes) squares   main :: IO () main = print $ take 10 $ drop 20 foo
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functions within the syntax of the language. They should return either a list or an iterator (something that returns successive members of a collection, in order). The syntax has parts corresponding to that of set-builder notation. Task Write a list comprehension that builds the list of all Pythagorean triples with elements between   1   and   n. If the language has multiple ways for expressing such a construct (for example, direct list comprehensions and generators), write one example for each.
#Ruby
Ruby
n = 20   # select Pythagorean triplets r = ((1..n).flat_map { |x| (x..n).flat_map { |y| (y..n).flat_map { |z| [[x, y, z]].keep_if { x * x + y * y == z * z }}}})   p r # print the array _r_
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pennies   15 pennies Task How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents). Optional Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000? (Note:   the answer is larger than   232). References an algorithm from the book Structure and Interpretation of Computer Programs. an article in the algorithmist. Change-making problem on Wikipedia.
#Clojure
Clojure
(def denomination-kind [1 5 10 25])   (defn- cc [amount denominations] (cond (= amount 0) 1 (or (< amount 0) (empty? denominations)) 0 :else (+ (cc amount (rest denominations)) (cc (- amount (first denominations)) denominations))))   (defn count-change "Calculates the number of times you can give change with the given denominations." [amount denominations] (cc amount denominations))   (count-change 15 denomination-kind) ; = 6
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. If the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point, whether in the   Basic Multilingual Plane   or above it. The program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elixir
Elixir
s = "abcdefgh" String.slice(s, 2, 3) #=> "cde" String.slice(s, 1..3) #=> "bcd" String.slice(s, -3, 2) #=> "fg" String.slice(s, 3..-1) #=> "defgh"   # UTF-8 s = "αβγδεζηθ" String.slice(s, 2, 3) #=> "γδε" String.slice(s, 1..3) #=> "βγδ" String.slice(s, -3, 2) #=> "ζη" String.slice(s, 3..-1) #=> "δεζηθ"
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\displaystyle \pi } . If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π / 4 {\displaystyle \pi /4} . So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π / 4 {\displaystyle \pi /4} . Task Write a function to run a simulation like this, with a variable number of random points to select. Also, show the results of a few different sample sizes. For software where the number π {\displaystyle \pi } is not built-in, we give π {\displaystyle \pi } as a number of digits: 3.141592653589793238462643383280
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;   procedure Test_Monte_Carlo is Dice : Generator;   function Pi (Throws : Positive) return Float is Inside : Natural := 0; begin for Throw in 1..Throws loop if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then Inside := Inside + 1; end if; end loop; return 4.0 * Float (Inside) / Float (Throws); end Pi; begin Put_Line (" 10_000:" & Float'Image (Pi ( 10_000))); Put_Line (" 100_000:" & Float'Image (Pi ( 100_000))); Put_Line (" 1_000_000:" & Float'Image (Pi ( 1_000_000))); Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000))); Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000))); end Test_Monte_Carlo;
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care must be taken to avoid concurrently overwriting the same record from another job. Task Given a two record sample for a mythical "passwd" file: Write these records out in the typical system format. Ideally these records will have named fields of various types. Close the file, then reopen the file for append. Append a new record to the file and close the file again. Take appropriate care to avoid concurrently overwrites from another job. Open the file and demonstrate the new record has indeed written to the end. Source record field types and contents. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string jsmith x 1001 1000 Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org /home/jsmith /bin/bash jdoe x 1002 1000 Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org /home/jdoe /bin/bash Record to be appended. account password UID GID fullname,office,extension,homephone,email directory shell string string int int struct(string,string,string,string,string) string string xyz x 1003 1000 X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org /home/xyz /bin/bash Resulting file format: should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example. Expected output: Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash Finally: Provide a summary of the language's "append record" capabilities in a table. eg. Append Capabilities. Data Representation IO Library Append Possible Automatic Append Multi-tasking Safe In core On disk C struct CSV text file glibc/stdio ☑ ☑ ☑ (Not all, eg NFS) Alternatively: If the language's appends can not guarantee its writes will always append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.
#zkl
zkl
var [const] gnames=T("fullname","office","extension","homephone","email"), pnames=T("account","password","uid","gid","gecos","directory","shell");   class Gecos{ var fullname, office, extension, homephone, email; fcn init(str){ gnames.zipWith(setVar,vm.arglist) } fcn toString { gnames.apply(setVar).concat(",") } } class Passwd{ var account,password,uid,gid,gecos,directory,shell; fcn init(str){ pnames.zipWith(setVar,vm.arglist) } fcn toString { pnames.apply(setVar).concat(":") } }
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all Permutations/Derangements of 1 to n starting with 2. The third row is all Permutations/Derangements of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all Permutations/Derangements of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: displaying the four reduced Latin Squares of order 4. for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
#J
J
  redlat=: {{ perms=: (A.&i.~ !)~ y sqs=. i.1 1,y for_j.}.i.y do. p=. (j={."1 perms)#perms sel=.-.+./"1 p +./@:="1/"2 sqs sqs=.(#~ 1-0*/ .="1{:"2),/sqs,"2 1 sel#"2 p end. }}  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Ol
Ol
  (define (timestamp) (syscall 201 "%c"))   (fork-server 'chat-room (lambda () (let this ((visitors #empty)) (let* ((envelope (wait-mail)) (sender msg envelope)) (case msg (['join who name] (let ((visitors (put visitors who name))) (for-each (lambda (who) (print-to (car who) name " joined to as")) (ff->alist visitors)) (this visitors))) (['talk message] (for-each (lambda (who) (print-to (car who) (cdr who) ": " message)) (ff->alist visitors)) (this visitors)) (['part who] (for-each (lambda (who) (print-to (car who) (visitors (car who) "unknown") " leaved")) (ff->alist visitors)) (let ((visitors (del visitors who))) (this visitors))))))))     (define (on-accept name fd) (lambda () (print "# " (timestamp) "> we got new visitor: " name) (mail 'chat-room ['join fd name])   (let*((ss1 ms1 (clock))) (let loop ((str #null) (stream (force (port->bytestream fd)))) (cond ((null? stream) #false) ((function? stream) (mail 'chat-room ['talk (list->string (reverse str))]) (loop #null (force stream))) (else (loop (cons (car stream) str) (cdr stream))))) (syscall 3 fd) (let*((ss2 ms2 (clock))) (print "# " (timestamp) "> visitor leave us. It takes " (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) "ms."))) (mail 'chat-room ['part fd]) ))   (define (run port) (let ((socket (syscall 41))) ; bind (let loop ((port port)) (if (not (syscall 49 socket port)) ; bind (loop (+ port 2)) (print "Server binded to " port))) ; listen (if (not (syscall 50 socket)) ; listen (shutdown (print "Can't listen")))   ; accept (let loop () (if (syscall 23 socket) ; select (let ((fd (syscall 43 socket))) ; accept ;(print "\n# " (timestamp) ": new request from " (syscall 51 fd)) (fork (on-accept (syscall 51 fd) fd)))) (sleep 0) (loop))))   (run 8080)  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were separated by the separators, become the elements of the output list. Empty fields should be preserved, even at the start and end. Rules for escaping: "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself. When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special). Each occurrence of the escape character that was used to escape something, should not become part of the output. Test case Demonstrate that your function satisfies the following test-case: Input Output string: one^|uno||three^^^^|four^^^|^cuatro| separator character: | escape character: ^ one|uno three^^ four^|cuatro (Print the output list in any format you like, as long as it is it easy to see what the fields are.) 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
tokenize = iter (sep, esc: char, s: string) yields (string) escape: bool := false part: array[char] := array[char]$[] for c: char in string$chars(s) do if escape then escape := false array[char]$addh(part,c) elseif c=esc then escape := true elseif c=sep then yield(string$ac2s(part)) part := array[char]$[] else array[char]$addh(part,c) end end yield(string$ac2s(part)) end tokenize   start_up = proc () po: stream := stream$primary_output() testcase: string := "one^|uno||three^^^^|four^^^|^quatro|"   for part: string in tokenize('|', '^', testcase) do stream$putl(po, "\"" || part || "\"") end end start_up
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not include   1.   Those numbers for which this process end in   1   are       happy   numbers,   while   those numbers   that   do   not   end in   1   are   unhappy   numbers. Task Find and print the first   8   happy numbers. Display an example of your output here on this page. See also   The OEIS entry:   The     happy numbers:   A007770   The OEIS entry:   The unhappy numbers;   A031177
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 for i=1 to 100 30 i2=i 40 for l=1 to 20 50 a$=str$(i2) 60 i2=0 70 for j=1 to len(a$) 80 d=val(mid$(a$,j,1)) 90 i2=i2+d*d 100 next j 110 if i2=1 then print i;"is a happy number":n=n+1:goto 150 120 if i2=4 then 150 ' cycle found 130 next l 140 ' check if we have reached 8 numbers yet 150 if n=8 then end 160 next i
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#QB64
QB64
For n = 1 To 100 If n Mod 15 = 0 Then Print "FizzBuzz" ElseIf n Mod 5 = 0 Then Print "Buzz" ElseIf n Mod 3 = 0 Then Print "Fizz" Else Print n End If Next
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code”. You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
#Ruby
Ruby
require 'digest' puts Digest::RMD160.hexdigest('Rosetta Code')
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of   1,2,3,4,6 & 12   which sum to   28   ( > 24 or 2n). Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers. To make things more interesting, this task is specifically about finding   odd abundant numbers. Task Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum. Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum. Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum. References   OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)   American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
#Java
Java
import java.util.ArrayList; import java.util.List;   public class AbundantOddNumbers { private static List<Integer> list = new ArrayList<>(); private static List<Integer> result = new ArrayList<>();   public static void main(String[] args) { System.out.println("First 25: "); abundantOdd(1,100000, 25, false);   System.out.println("\n\nThousandth: "); abundantOdd(1,2500000, 1000, true);   System.out.println("\n\nFirst over 1bn:"); abundantOdd(1000000001, 2147483647, 1, false); } private static void abundantOdd(int start, int finish, int listSize, boolean printOne) { for (int oddNum = start; oddNum < finish; oddNum += 2) { list.clear(); for (int toDivide = 1; toDivide < oddNum; toDivide+=2) { if (oddNum % toDivide == 0) list.add(toDivide); } if (sumList(list) > oddNum) { if(!printOne) System.out.printf("%5d <= %5d \n",oddNum, sumList(list) ); result.add(oddNum); } if(printOne && result.size() >= listSize) System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );   if(result.size() >= listSize) break; } } private static int sumList(List list) { int sum = 0; for (int i = 0; i < list.size(); i++) { String temp = list.get(i).toString(); sum += Integer.parseInt(temp); } return sum; } }    
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#bc
bc
$ bc # trying for negative zero -0 0 # trying to underflow to negative zero -1 / 2 0 # trying for NaN (not a number) 0 / 0 dc: divide by zero 0 sqrt(-1) dc: square root of negative number dc: stack empty dc: stack empty
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Eiffel
Eiffel
class MAIN creation main feature main is local x, y: INTEGER; retried: BOOLEAN; do x := 42; y := 0;   if not retried then io.put_real(x / y); else print("NaN%N"); end rescue print("Caught division by zero!%N"); retried := True; retry end end
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#REXX
REXX
/*REXX program enumerates all possible configurations (or an error) for nonogram puzzles*/ $.=; $.1= 5 2 1 $.2= 5 $.3= 10 8 $.4= 15 2 3 2 3 $.5= 5 2 3 do i=1 while $.i\=='' parse var $.i N blocks /*obtain N and blocks from array. */ N= strip(N); blocks= space(blocks) /*assign stripped N and blocks. */ call nono /*incoke NONO subroutine for heavy work*/ end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ nono: say copies('=', 70) /*display seperator for title.*/ say 'For ' N " cells and blocks of: " blocks /*display the title for output*/ z= /*assign starter value for Z. */ do w=1 for words(blocks) /*process each of the blocks. */ z= z copies('#', word(blocks,w) ) /*build a string for 1st value*/ end /*w*/ /*Z now has a leading blank. */ #= 1 /*number of positions (so far)*/ z= translate( strip(z), ., ' '); L= length(z) /*change blanks to periods. */ if L>N then do; say '***error*** invalid blocks for number of cells.'; return end @.0=; @.1= z;  !.=0 /*assign default and the first position*/ z= pad(z) /*fill─out (pad) the value with periods*/   do prepend=1 while words(blocks)\==0 /*process all the positions (leading .)*/ new= . || @.prepend /*create positions with leading dots. */ if length(new)>N then leave /*Length is too long? Then stop adding*/ call add /*add position that has a leading dot. */ end /*prepend*/ /* [↑] prepend positions with dots. */   do k=1 for N /*process each of the positions so far.*/ do c=1 for N /* " " " " position blocks. */ if @.c=='' then iterate /*if string is null, skip the string. */ p= loc(@.c, k) /*find location of block in position. */ if p==0 | p>=N then iterate /*Location zero or out─of─range? Skip.*/ new= strip( insert(., @.c, p),'T',.) /*insert a dot and strip trailing dots.*/ if strip(new,'T',.)=@.c then iterate /*Is it the same value? Then skip it. */ if length(new)<=N then call add /*Is length OK? Then add position. */ end /*k*/ end /*c*/ say say '─position─' center("value", max(7, length(z) ), '─') /*show hdr for output.*/   do m=1 for # say center(m, 10) pad(@.m) /*display the index count and position.*/ end /*m*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ loc: _=0; do arg(2); _=pos('#.',pad(arg(1)),_+1); if _==0 then return 0; end; return _+1 add: if !.new==1 then return; #= # + 1; @.#= new;  !.new=1; return pad: return left( arg(1), N, .)
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 Related tasks Five weekends Day of the week Find the last Sunday of each month
#Sidef
Sidef
require('DateTime') var (year=2016) = ARGV.map{.to_i}...   for month (1..12) { var dt = %O<DateTime>.last_day_of_month(year => year, month => month) while (dt.day_of_week != 5) { dt.subtract(days => 1) } say dt.ymd }
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#VBScript
VBScript
  WScript.Echo DotProduct("1,3,-5","4,-2,-1")   Function DotProduct(vector1,vector2) arrv1 = Split(vector1,",") arrv2 = Split(vector2,",") If UBound(arrv1) <> UBound(arrv2) Then WScript.Echo "The vectors are not of the same length." Exit Function End If DotProduct = 0 For i = 0 To UBound(arrv1) DotProduct = DotProduct + (arrv1(i) * arrv2(i)) Next End Function  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Vlang
Vlang
import os   fn main() { for i, x in os.args[1..] { println("the argument #$i is $x") } }
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: Base case (if the step() call returns true): it stepped up one step. QED Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
#Prolog
Prolog
step_up :- \+ step, step_up, step_up.
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Visual_Basic
Visual Basic
Option Explicit '---------------------------------------------------------------------- Function TransposeMatrix(InitMatrix() As Long, TransposedMatrix() As Long) Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long l1 = LBound(InitMatrix, 1) l2 = LBound(InitMatrix, 2) u1 = UBound(InitMatrix, 1) u2 = UBound(InitMatrix, 2) ReDim TransposedMatrix(l2 To u2, l1 To u1) For r = l1 To u1 For c = l2 To u2 TransposedMatrix(c, r) = InitMatrix(r, c) Next c Next r End Function '---------------------------------------------------------------------- Sub PrintMatrix(a() As Long) Dim l1 As Long, l2 As Long, u1 As Long, u2 As Long, r As Long, c As Long Dim s As String * 8 l1 = LBound(a(), 1) l2 = LBound(a(), 2) u1 = UBound(a(), 1) u2 = UBound(a(), 2) For r = l1 To u1 For c = l2 To u2 RSet s = Str$(a(r, c)) Debug.Print s; Next c Debug.Print Next r End Sub '---------------------------------------------------------------------- Sub TranspositionDemo(ByVal DimSize1 As Long, ByVal DimSize2 As Long) Dim r, c, cc As Long Dim a() As Long Dim b() As Long cc = DimSize2 DimSize1 = DimSize1 - 1 DimSize2 = DimSize2 - 1 ReDim a(0 To DimSize1, 0 To DimSize2) For r = 0 To DimSize1 For c = 0 To DimSize2 a(r, c) = (cc * r) + c + 1 Next c Next r Debug.Print "initial matrix:" PrintMatrix a() TransposeMatrix a(), b() Debug.Print "transposed matrix:" PrintMatrix b() End Sub '---------------------------------------------------------------------- Sub Main() TranspositionDemo 3, 3 TranspositionDemo 3, 7 End Sub
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Get two integers from the user. Then,   display a message if the first integer is:   less than,   equal to,   or   greater than the second integer. Test the condition   for each case separately,   so that   all three comparison operators are used   in the code. Related task   String comparison
#PL.2FI
PL/I
  declare (a, b) fixed binary;   get list (a, b); if a = b then put skip list ('The numbers are equal'); if a > b then put skip list ('The first number is greater than the second'); if a < b then put skip list ('The second number is greater than the first');  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. Note: Please be careful when running any code presented here. Related task   Walk Directory Tree   (read entire directory tree).
#BBC_BASIC
BBC BASIC
directory$ = "C:\Windows\" pattern$ = "*.ini" PROClistdir(directory$ + pattern$) END   DEF PROClistdir(afsp$) LOCAL dir%, sh%, res% DIM dir% LOCAL 317 SYS "FindFirstFile", afsp$, dir% TO sh% IF sh% <> -1 THEN REPEAT PRINT $$(dir%+44) SYS "FindNextFile", sh%, dir% TO res% UNTIL res% = 0 SYS "FindClose", sh% ENDIF ENDPROC
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are also called   Hamming numbers. 7-smooth   numbers are also called    humble   numbers. A way to express   11-smooth   numbers is: 11-smooth = 2i × 3j × 5k × 7m × 11p where i, j, k, m, p ≥ 0 Task   calculate and show the first   25   n-smooth numbers   for   n=2   ───►   n=29   calculate and show   three numbers starting with   3,000   n-smooth numbers   for   n=3   ───►   n=29   calculate and show twenty numbers starting with  30,000   n-smooth numbers   for   n=503   ───►   n=521   (optional) All ranges   (for   n)   are to be inclusive, and only prime numbers are to be used. The (optional) n-smooth numbers for the third range are:   503,   509,   and   521. Show all n-smooth numbers for any particular   n   in a horizontal list. Show all output here on this page. Related tasks   Hamming numbers   humble numbers References   Wikipedia entry:   Hamming numbers     (this link is re-directed to   Regular number).   Wikipedia entry:   Smooth number   OEIS entry:   A000079    2-smooth numbers or non-negative powers of two   OEIS entry:   A003586    3-smooth numbers   OEIS entry:   A051037    5-smooth numbers or Hamming numbers   OEIS entry:   A002473    7-smooth numbers or humble numbers   OEIS entry:   A051038   11-smooth numbers   OEIS entry:   A080197   13-smooth numbers   OEIS entry:   A080681   17-smooth numbers   OEIS entry:   A080682   19-smooth numbers   OEIS entry:   A080683   23-smooth numbers
#Julia
Julia
using Primes   function nsmooth(N, needed) nexts, smooths = [BigInt(i) for i in 2:N if isprime(i)], [BigInt(1)] prim, count = deepcopy(nexts), 1 indices = ones(Int, length(nexts)) while count < needed x = minimum(nexts) push!(smooths, x) count += 1 for j in 1:length(nexts) (nexts[j] <= x) && (nexts[j] = prim[j] * smooths[(indices[j] += 1)]) end end return (smooths[end] > typemax(Int)) ? smooths : Int.(smooths) end   function testnsmoothfilters() for i in filter(isprime, 1:29) println("The first 25 n-smooth numbers for n = $i are: ", nsmooth(i, 25)) end for i in filter(isprime, 3:29) println("The 3000th through 3002nd ($i)-smooth numbers are: ", nsmooth(i, 3002)[3000:3002]) end for i in filter(isprime, 503:521) println("The 30000th through 30019th ($i)-smooth numbers >= 30000 are: ", nsmooth(i, 30019)[30000:30019]) end end   testnsmoothfilters()  
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#jq
jq
# Generate the hailstone sequence as a stream to save space (and time) when counting def hailstone: recurse( if . > 1 then if . % 2 == 0 then ./2|floor else 3*. + 1 end else empty end );   def count(g): reduce g as $i (0; .+1);   # return [i, length] for the first maximal-length hailstone sequence where i is in [1 .. n] def max_hailstone(n): # state: [i, length] reduce range(1; n+1) as $i ([0,0]; ($i | count(hailstone)) as $l | if $l > .[1] then [$i, $l] else . end);
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Raku
Raku
rebol [ Title: "Basic Input Loop" URL: http://rosettacode.org/wiki/Basic_input_loop ]   ; Slurp the whole file in: x: read %file.txt   ; Bring the file in by lines: x: read/lines %file.txt   ; Read in first 10 lines: x: read/lines/part %file.txt 10   ; Read data a line at a time: f: open/lines %file.txt while [not tail? f][ print f/1 f: next f ; Advance to next line. ] close f
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
IntegerHalving[x_]:=Floor[x/2] IntegerDoubling[x_]:=x*2; OddInteger OddQ Ethiopian[x_, y_] := Total[Select[NestWhileList[{IntegerHalving[#[[1]]],IntegerDoubling[#[[2]]]}&, {x,y}, (#[[1]]>1&)], OddQ[#[[1]]]&]][[2]]   Ethiopian[17, 34]
train-00000-of-00001-8b4da49264116bbf.parquet
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an element in set S" A ∪ B -- union; a set of all elements either in set A or in set B. A ∩ B -- intersection; a set of all elements in both set A and set B. A ∖ B -- difference; a set of all elements in set A, except those in set B. A ⊆ B -- subset; true if every element in set A is also in set B. A = B -- equality; true if every element of set A is in set B and vice versa. As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an associative array (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators). The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   (*------------------------------------------------------------------*) (* String hashing using XXH3_64bits from the xxHash suite. *)   #define ATS_EXTERN_PREFIX "hashsets_postiats_"   %{^ /* Embedded C code. */   #include <xxhash.h>   ATSinline() atstype_uint64 hashsets_postiats_mem_hash (atstype_ptr data, atstype_size len) { return (atstype_uint64) XXH3_64bits (data, len); }   %}   extern fn mem_hash : (ptr, size_t) -<> uint64 = "mac#%"   fn string_hash (s : string) :<> uint64 = let val len = string_length s in mem_hash ($UNSAFE.cast{ptr} s, len) end   (*------------------------------------------------------------------*) (* A trimmed down version of the AVL trees from the AVL Tree task. *)   datatype bal_t = | bal_minus1 | bal_zero | bal_plus1   datatype avl_t (key_t  : t@ype+, data_t : t@ype+, size  : int) = | avl_t_nil (key_t, data_t, 0) | {size_L, size_R : nat} avl_t_cons (key_t, data_t, size_L + size_R + 1) of (key_t, data_t, bal_t, avl_t (key_t, data_t, size_L), avl_t (key_t, data_t, size_R)) typedef avl_t (key_t  : t@ype+, data_t : t@ype+) = [size : int] avl_t (key_t, data_t, size)   extern fun {key_t : t@ype} avl_t$compare (u : key_t, v : key_t) :<> int   #define NIL avl_t_nil () #define CONS avl_t_cons #define LNIL list_nil () #define :: list_cons #define F false #define T true   typedef fixbal_t = bool   prfn lemma_avl_t_param {key_t : t@ype} {data_t : t@ype} {size : int} (avl : avl_t (key_t, data_t, size)) :<prf> [0 <= size] void = case+ avl of NIL => () | CONS _ => ()   fn {} minus_neg_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_minus1 () => bal_plus1 | _ => bal_zero ()   fn {} minus_pos_bal (bal : bal_t) :<> bal_t = case+ bal of | bal_plus1 () => bal_minus1 | _ => bal_zero ()   fn avl_t_is_empty {key_t : t@ype} {data_t : t@ype} {size  : int} (avl : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size == 0)] bool b = case+ avl of | NIL => T | CONS _ => F   fn avl_t_isnot_empty {key_t : t@ype} {data_t : t@ype} {size  : int} (avl : avl_t (key_t, data_t, size)) :<> [b : bool | b == (size <> 0)] bool b = ~avl_t_is_empty avl   fn {key_t : t@ype} {data_t : t@ype} avl_t_search_ref {size  : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt> #[found : bool] void = let fun search (p  : avl_t (key_t, data_t), data  : &data_t? >> opt (data_t, found), found : &bool? >> bool found) :<!wrt,!ntm> #[found : bool] void = case+ p of | NIL => { prval _ = opt_none {data_t} data val _ = found := F } | CONS (k, d, _, left, right) => begin case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => search (left, data, found) | cmp when cmp > 0 => search (right, data, found) | _ => { val _ = data := d prval _ = opt_some {data_t} data val _ = found := T } end in $effmask_ntm search (avl, data, found) end   fn {key_t : t@ype} {data_t : t@ype} avl_t_search_opt {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t) :<> Option (data_t) = let var data : data_t? var found : bool? val _ = $effmask_wrt avl_t_search_ref (avl, key, data, found) in if found then let prval _ = opt_unsome data in Some {data_t} data end else let prval _ = opt_unnone data in None {data_t} () end end   fn {key_t : t@ype} {data_t : t@ype} avl_t_insert_or_replace {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] (avl_t (key_t, data_t, sz), bool) = let fun search {size  : nat} (p  : avl_t (key_t, data_t, size), fixbal : fixbal_t, found  : bool) :<!ntm> [sz : pos] (avl_t (key_t, data_t, sz), fixbal_t, bool) = case+ p of | NIL => (CONS (key, data, bal_zero, NIL, NIL), T, F) | CONS (k, d, bal, left, right) => case+ avl_t$compare<key_t> (key, k) of | cmp when cmp < 0 => let val (p1, fixbal, found) = search (left, fixbal, found) in case+ (fixbal, bal) of | (F, _) => (CONS (k, d, bal, p1, right), F, found) | (T, bal_plus1 ()) => (CONS (k, d, bal_zero (), p1, right), F, found) | (T, bal_zero ()) => (CONS (k, d, bal_minus1 (), p1, right), fixbal, found) | (T, bal_minus1 ()) => let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_minus1 () => let val q = CONS (k, d, bal_zero (), right1, right) val q1 = CONS (k1, d1, bal_zero (), left1, q) in (q1, F, found) end | _ => let val p2 = right1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_neg_bal bal2, right2, right) val q1 = CONS (k1, d1, minus_pos_bal bal2, left1, left2) val q2 = CONS (k2, d2, bal_zero (), q1, q) in (q2, F, found) end end end | cmp when cmp > 0 => let val (p1, fixbal, found) = search (right, fixbal, found) in case+ (fixbal, bal) of | (F, _) => (CONS (k, d, bal, left, p1), F, found) | (T, bal_minus1 ()) => (CONS (k, d, bal_zero (), left, p1), F, found) | (T, bal_zero ()) => (CONS (k, d, bal_plus1 (), left, p1), fixbal, found) | (T, bal_plus1 ()) => let val+ CONS (k1, d1, bal1, left1, right1) = p1 in case+ bal1 of | bal_plus1 () => let val q = CONS (k, d, bal_zero (), left, left1) val q1 = CONS (k1, d1, bal_zero (), q, right1) in (q1, F, found) end | _ => let val p2 = left1 val- CONS (k2, d2, bal2, left2, right2) = p2 val q = CONS (k, d, minus_pos_bal bal2, left, left2) val q1 = CONS (k1, d1, minus_neg_bal bal2, right2, right1) val q2 = CONS (k2, d2, bal_zero (), q, q1) in (q2, F, found) end end end | _ => (CONS (key, data, bal, left, right), F, T) in if avl_t_is_empty avl then (CONS (key, data, bal_zero, NIL, NIL), F) else let prval _ = lemma_avl_t_param avl val (avl, _, found) = $effmask_ntm search (avl, F, F) in (avl, found) end end   fn {key_t : t@ype} {data_t : t@ype} avl_t_insert {size : int} (avl  : avl_t (key_t, data_t, size), key  : key_t, data : data_t) :<> [sz : pos] avl_t (key_t, data_t, sz) = (avl_t_insert_or_replace<key_t><data_t> (avl, key, data)).0   fun {key_t : t@ype} {data_t : t@ype} push_all_the_way_left (stack : List (avl_t (key_t, data_t)), p  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in case+ p of | NIL => stack | CONS (_, _, _, left, _) => push_all_the_way_left (p :: stack, left) end   fun {key_t : t@ype} {data_t : t@ype} update_generator_stack (stack  : List (avl_t (key_t, data_t)), right  : avl_t (key_t, data_t)) : List0 (avl_t (key_t, data_t)) = let prval _ = lemma_list_param stack in if avl_t_is_empty right then stack else push_all_the_way_left<key_t><data_t> (stack, right) end   fn {key_t : t@ype} {data_t : t@ype} avl_t_make_data_generator {size : int} (avl  : avl_t (key_t, data_t, size)) : () -<cloref1> Option data_t = let typedef avl_t = avl_t (key_t, data_t)   val stack = push_all_the_way_left<key_t><data_t> (LNIL, avl) val stack_ref = ref stack   (* Cast stack_ref to its (otherwise untyped) pointer, so it can be enclosed within ‘generate’. *) val p_stack_ref = $UNSAFE.castvwtp0{ptr} stack_ref   fun generate () :<cloref1> Option data_t = let (* Restore the type information for stack_ref. *) val stack_ref = $UNSAFE.castvwtp0{ref (List avl_t)} p_stack_ref   var stack : List0 avl_t = !stack_ref var retval : Option data_t in begin case+ stack of | LNIL => retval := None () | p :: tail => let val- CONS (_, d, _, left, right) = p in retval := Some d; stack := update_generator_stack<key_t><data_t> (tail, right) end end;  !stack_ref := stack; retval end in generate end   (*------------------------------------------------------------------*) (* Sets implemented with a hash function, AVL trees and association *) (* lists. *)   (* The interface - - - - - - - - - - - - - - - - - - - - - - - - - *)   (* For simplicity, let us support only 64-bit hashes. *)   typedef hashset_t (key_t : t@ype+) = avl_t (uint64, List1 key_t)   extern fun {key_t : t@ype} (* Implement a hash function with this. *) hashset_t$hashfunc : key_t -<> uint64   extern fun {key_t : t@ype} (* Implement key equality with this. *) hashset_t$key_eq : (key_t, key_t) -<> bool   extern fun hashset_t_nil : {key_t : t@ype} () -<> hashset_t key_t   extern fun {key_t : t@ype} hashset_t_add_member : (hashset_t key_t, key_t) -<> hashset_t key_t   (* "remove_member" is not implemented here, because the trimmed down AVL tree implementation above does not include deletion. We shall implement everything else without using a member deletion routine.   extern fun {key_t : t@ype} hashset_t_remove_member : (hashset_t key_t, key_t) -<> hashset_t key_t   Of course you can remove a member by using hashset_t_difference. *)   extern fun {key_t : t@ype} hashset_t_has_member : (hashset_t key_t, key_t) -<> bool   typedef hashset_t_binary_operation (key_t : t@ype) = (hashset_t key_t, hashset_t key_t) -> hashset_t key_t   extern fun {key_t : t@ype} hashset_t_union : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_intersection : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_difference : hashset_t_binary_operation key_t   extern fun {key_t : t@ype} hashset_t_subset : (hashset_t key_t, hashset_t key_t) -> bool   extern fun {key_t : t@ype} hashset_t_equal : (hashset_t key_t, hashset_t key_t) -> bool   (* Note: generators for hashset_t produce their output in unspecified order. *) extern fun {key_t : t@ype} hashset_t_make_generator : hashset_t key_t -> () -<cloref1> Option key_t   (* The implementation - - - - - - - - - - - - - - - - - - - - - - - *)   (* I make no promises that these are the most efficient implementations I could devise. They certainly are not! But they were easy to write and will work. *)   implement hashset_t_nil () = avl_t_nil ()   fun {key_t  : t@ype} find_key {n : nat} .<n>. (lst : list (key_t, n), key : key_t) :<> List0 key_t = (* This implementation is tail recursive. It will not build up the stack. *) case+ lst of | list_nil () => lst | list_cons (head, tail) => if hashset_t$key_eq<key_t> (key, head) then lst else find_key (tail, key)   implement {key_t} hashset_t_add_member (set, key) = (* The following implementation assumes equal keys are interchangeable. *) let implement avl_t$compare<uint64> (u, v) = if u < v then ~1 else if v < u then 1 else 0 typedef lst_t = List1 key_t val hash = hashset_t$hashfunc<key_t> key val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash) in case+ lst_opt of | Some lst => begin case+ find_key<key_t> (lst, key) of | list_cons _ => set | list_nil () => avl_t_insert<uint64><lst_t> (set, hash, list_cons (key, lst)) end | None () => avl_t_insert<uint64><lst_t> (set, hash, list_cons (key, list_nil ())) end   implement {key_t} hashset_t_has_member (set, key) = let implement avl_t$compare<uint64> (u, v) = if u < v then ~1 else if v < u then 1 else 0 typedef lst_t = List1 key_t val hash = hashset_t$hashfunc<key_t> key val lst_opt = avl_t_search_opt<uint64><lst_t> (set, hash) in case+ lst_opt of | None () => false | Some lst => begin case+ find_key<key_t> (lst, key) of | list_nil () => false | list_cons _ => true end end   implement {key_t} hashset_t_union (u, v) = let val gen_u = hashset_t_make_generator<key_t> u val gen_v = hashset_t_make_generator<key_t> v var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) w := hashset_t_add_member (w, option_unsome k_opt); for (k_opt := gen_v (); option_is_some k_opt; k_opt := gen_v ()) w := hashset_t_add_member (w, option_unsome k_opt); w end   implement {key_t} hashset_t_intersection (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) let val+ Some k = k_opt in if hashset_t_has_member<key_t> (v, k) then w := hashset_t_add_member (w, k) end; w end   implement {key_t} hashset_t_difference (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var w : hashset_t key_t = hashset_t_nil () var k_opt : Option key_t in for (k_opt := gen_u (); option_is_some k_opt; k_opt := gen_u ()) let val+ Some k = k_opt in if ~hashset_t_has_member<key_t> (v, k) then w := hashset_t_add_member (w, k) end; w end   implement {key_t} hashset_t_subset (u, v) = let val gen_u = hashset_t_make_generator<key_t> u var subset : bool = true var done : bool = false in while (~done) case+ gen_u () of | None () => done := true | Some k => if ~hashset_t_has_member<key_t> (v, k) then begin subset := false; done := true end; subset end   implement {key_t} hashset_t_equal (u, v) = hashset_t_subset<key_t> (u, v) && hashset_t_subset<key_t> (v, u)   implement {key_t} hashset_t_make_generator (set) = let typedef lst_t = List1 key_t typedef lst_t_0 = List0 key_t   val avl_gen = avl_t_make_data_generator<uint64><lst_t> (set)   val current_list_ref : ref lst_t_0 = ref (list_nil ()) val current_list_ptr = $UNSAFE.castvwtp0{ptr} current_list_ref in lam () => let val current_list_ref = $UNSAFE.castvwtp0{ref lst_t_0} current_list_ptr in case+ !current_list_ref of | list_nil () => begin case+ avl_gen () of | None () => None () | Some lst => begin case+ lst of | list_cons (head, tail) => begin  !current_list_ref := tail; Some head end end end | list_cons (head, tail) => begin  !current_list_ref := tail; Some head end end end   (*------------------------------------------------------------------*)   implement hashset_t$hashfunc<string> (s) = string_hash s   implement hashset_t$key_eq<string> (s, t) = s = t   typedef strset_t = hashset_t string   fn {} strset_t_nil () :<> strset_t = hashset_t_nil ()   fn strset_t_add_member (set  : strset_t, member : string) :<> strset_t = hashset_t_add_member<string> (set, member)   fn {} strset_t_member_add (member : string, set  : strset_t) :<> strset_t = strset_t_add_member (set, member)   #define SNIL strset_t_nil () infixr ( :: ) ++ (* Right associative, same precedence as :: *) overload ++ with strset_t_member_add   fn strset_t_has_member (set  : strset_t, member : string) :<> bool = hashset_t_has_member<string> (set, member) overload [] with strset_t_has_member   fn strset_t_union (u : strset_t, v : strset_t) : strset_t = hashset_t_union<string> (u, v) overload + with strset_t_union   fn strset_t_intersection (u : strset_t, v : strset_t) : strset_t = hashset_t_intersection<string> (u, v) infixl ( + ) ^ overload ^ with strset_t_intersection   fn strset_t_difference (u : strset_t, v : strset_t) : strset_t = hashset_t_difference<string> (u, v) overload - with strset_t_difference   fn strset_t_subset (u : strset_t, v : strset_t) : bool = hashset_t_subset<string> (u, v) overload <= with strset_t_subset   fn strset_t_equal (u : strset_t, v : strset_t) : bool = hashset_t_equal<string> (u, v) overload = with strset_t_equal   fn strset_t_make_generator (set : strset_t) : () -<cloref1> Option string = hashset_t_make_generator<string> set   fn strset_t_print (set : strset_t) : void = let val gen = strset_t_make_generator set var s_opt : Option string var separator : string = "" in print! ("#<strset_t "); for (s_opt := gen (); option_is_some s_opt; s_opt := gen ()) case+ s_opt of | Some s => begin (* The following quick and dirty implemenetation does not insert escape sequences. *) print! (separator, "\"", s, "\""); separator := " " end; print! (">") end   implement main0 () = let val set1 = "one" ++ "two" ++ "three" ++ "guide" ++ "design" ++ SNIL val set2 = "ett" ++ "två" ++ "tre" ++ "guide" ++ "design" ++ SNIL in print! ("set1 = "); strset_t_print set1;   println! (); println! (); println! ("set1[\"one\"] = ", set1["one"]); println! ("set1[\"two\"] = ", set1["two"]); println! ("set1[\"three\"] = ", set1["three"]); println! ("set1[\"four\"] = ", set1["four"]);   println! (); print! ("set2 = "); strset_t_print set2;   println! (); println! (); println! ("set2[\"ett\"] = ", set2["ett"]); println! ("set2[\"två\"] = ", set2["två"]); println! ("set2[\"tre\"] = ", set2["tre"]); println! ("set2[\"fyra\"] = ", set2["fyra"]);   println! (); print! ("Union\nset1 + set2 = "); strset_t_print (set1 + set2); println! ();   println! (); print! ("Intersection\nset1 ^ set2 = "); strset_t_print (set1 ^ set2); println! ();   println! (); print! ("Difference\nset1 - set2 = "); strset_t_print (set1 - set2); println! ();   println! (); println! ("Subset"); println! ("set1 <= set1: ", set1 <= set1); println! ("set2 <= set2: ", set2 <= set2); println! ("set1 <= set2: ", set1 <= set2); println! ("set2 <= set1: ", set2 <= set1); println! ("(set1 ^ set2) <= set1: ", (set1 ^ set2) <= set1); println! ("(set1 ^ set2) <= set2: ", (set1 ^ set2) <= set2);   println! (); println! ("Equal"); println! ("set1 = set1: ", set1 = set1); println! ("set2 = set2: ", set2 = set2); println! ("set1 = set2: ", set1 = set2); println! ("set2 = set1: ", set2 = set1); println! ("(set1 ^ set2) = (set2 ^ set1): ", (set1 ^ set2) = (set2 ^ set1)); println! ("(set1 ^ set2) = set1: ", (set1 ^ set2) = set1); println! ("(set1 ^ set2) = set2: ", (set1 ^ set2) = set2) end   (*------------------------------------------------------------------*)
train-00000-of-00001-8b4da49264116bbf.parquet
README.md exists but content is empty.
Downloads last month
13