task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. 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
#Lambdatalk
Lambdatalk
  {def firstDifferingChar {def firstDifferingChar.r {lambda {:w :i :n} {if {or {> :i :n} {= {+ :i 1} {W.length :w}}} then all characters are the same else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}} then at position {+ :i 1} {W.get :i :w} becomes {W.get {+ :i 1} :w} else {firstDifferingChar.r :w {+ :i 1} :n}}}}} {lambda {:w} {if {= {W.length :w} 1} then :w is a single character else {firstDifferingChar.r :w 0 {W.length :w}}}}} -> firstDifferingChar   {firstDifferingChar 2} -> 2 is a single character {firstDifferingChar 333} -> all characters are the same {firstDifferingChar .55} -> at position 1 . becomes 5 {firstDifferingChar tttTTT} -> at position 3 t becomes T  
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#Phix
Phix
without js -- threads integer fork1 = init_cs(), fork2 = init_cs(), fork3 = init_cs(), fork4 = init_cs(), fork5 = init_cs() integer terminate = 0 -- control flag procedure person(sequence name, atom left_fork, atom right_fork) -- (except Russell, who gets left and right the other way round) while terminate=0 do enter_cs(left_fork) enter_cs(right_fork) puts(1, name & " grabs forks.\n") for i=1 to rand(10) do -- if terminate then exit end if puts(1, name & " is eating.\n") -- sleep(1) end for puts(1, name & " puts forks down and leaves the dinning room.\n") leave_cs(left_fork) leave_cs(right_fork) for i=1 to rand(10) do -- if terminate then exit end if puts(1, name & " is thinking.\n") -- sleep(1) end for puts(1, name & " becomes hungry.\n") end while end procedure constant r_person = routine_id("person") constant threads = {create_thread(r_person,{"Aristotle",fork1,fork2}), create_thread(r_person,{"Kant",fork2,fork3}), create_thread(r_person,{"Spinoza",fork3,fork4}), create_thread(r_person,{"Marx",fork4,fork5}), -- create_thread(r_person,{"Russell",fork5,fork1})} -- this will deadlock! create_thread(r_person,{"Russell",fork1,fork5})} constant ESC = #1B while not find(get_key(),{ESC,'q','Q'}) do sleep(1) end while terminate = 1 wait_thread(threads) -- (not strictly necessary) delete_cs(fork1) -- "" delete_cs(fork2) delete_cs(fork3) delete_cs(fork4) delete_cs(fork5)
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PHP
PHP
  <?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux");         // Get the current system date and assign to some variables $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3];   // If the user supplied us with a date overide the one we got from the system. // If you could get the date from users browser via javascript and then call // this script with the users date. ddate.php?y=year&m=month&d=day mostly it // won't matter but if the server is in a different time zone to the user // There will be occasional incorrect results from the users POV.   if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; }   // We need to know the total number of days in the year so far   $userdays = 0; $i = 0; while ($i < ($userm-1)) {   $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd;   // We can now work out the full discordian date for most dates // PHP does not do integer division, so we use 73.2 as a divisor // the value 73.2 works, larger values cause an off-by-one on season // changes for the later seasons . // This is not needed with the mod operator.   $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; }   if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;   // work out the suffix to the day number $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th';   // code to display the date ...   if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear;   ?>  
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#PHP
PHP
  <?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices);   foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; }   $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) {   // TODO - Find faster way to get minimum $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } }   $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; }   if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; }   $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) );   $path = dijkstra($graph_array, "a", "e");   echo "path is: ".implode(", ", $path)."\n";  
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Lua
Lua
function digital_root(n, base) p = 0 while n > 9.5 do n = sum_digits(n, base) p = p + 1 end return n, p end   print(digital_root(627615, 10)) print(digital_root(39390, 10)) print(digital_root(588225, 10)) print(digital_root(393900588225, 10))
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES INP = $I12*$ VECTOR VALUES OUTP = $I12,S1,I12*$ BASE = 10   R READ NUMBERS UNTIL 0 INPUT RDNUM READ FORMAT INP,NUMBER WHENEVER NUMBER.NE.0 SUMMAT PERS = 0 DSUM = 0   R CALCULATE ROOT AND PERSISTENCE DIGIT DSUM = DSUM + NUMBER-NUMBER/BASE*BASE NUMBER = NUMBER/BASE PERS = PERS + 1 WHENEVER NUMBER.NE.0, TRANSFER TO DIGIT NUMBER = DSUM WHENEVER NUMBER.GE.10, TRANSFER TO SUMMAT   PRINT FORMAT OUTP,DSUM,PERS TRANSFER TO RDNUM END OF CONDITIONAL END OF PROGRAM
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#Python
Python
import re from itertools import product   problem_re = re.compile(r"""(?msx)(?:   # Multiple names of form n1, n2, n3, ... , and nK (?P<namelist> [a-zA-Z]+ (?: , \s+ [a-zA-Z]+)* (?: ,? \s+ and) \s+ [a-zA-Z]+ )   # Flexible floor count (2 to 10 floors) | (?: .* house \s+ that \s+ contains \s+ only \s+ (?P<floorcount> two|three|four|five|six|seven|eight|nine|ten ) \s+ floors \s* \.)   # Constraint: "does not live on the n'th floor" |(?: (?P<not_live> \b [a-zA-Z]+ \s+ does \s+ not \s+ live \s+ on \s+ the \s+ (?: top|bottom|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth) \s+ floor \s* \. ))   # Constraint: "does not live on either the I'th or the J'th [ or the K'th ...] floor |(?P<not_either> \b [a-zA-Z]+ \s+ does \s+ not \s+ live \s+ on \s+ either (?: \s+ (?: or \s+)? the \s+ (?: top|bottom|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth))+ \s+ floor \s* \. )   # Constraint: "P1 lives on a higher/lower floor than P2 does" |(?P<hi_lower> \b [a-zA-Z]+ \s+ lives \s+ on \s+ a \s (?: higher|lower) \s+ floor \s+ than (?: \s+ does) \s+ [a-zA-Z]+ \s* \. )   # Constraint: "P1 does/does not live on a floor adjacent to P2's" |(?P<adjacency> \b [a-zA-Z]+ \s+ does (?:\s+ not)? \s+ live \s+ on \s+ a \s+ floor \s+ adjacent \s+ to \s+ [a-zA-Z]+ (?: 's )? \s* \. )   # Ask for the solution |(?P<question> Where \s+ does \s+ everyone \s+ live \s* \?)   ) """)   names, lennames = None, None floors = None constraint_expr = 'len(set(alloc)) == lennames' # Start with all people on different floors   def do_namelist(txt): " E.g. 'Baker, Cooper, Fletcher, Miller, and Smith'" global names, lennames names = txt.replace(' and ', ' ').split(', ') lennames = len(names)   def do_floorcount(txt): " E.g. 'five'" global floors floors = '||two|three|four|five|six|seven|eight|nine|ten'.split('|').index(txt)   def do_not_live(txt): " E.g. 'Baker does not live on the top floor.'" global constraint_expr t = txt.strip().split() who, floor = t[0], t[-2] w, f = (names.index(who), ('|first|second|third|fourth|fifth|sixth|' + 'seventh|eighth|ninth|tenth|top|bottom|').split('|').index(floor) ) if f == 11: f = floors if f == 12: f = 1 constraint_expr += ' and alloc[%i] != %i' % (w, f)   def do_not_either(txt): " E.g. 'Fletcher does not live on either the top or the bottom floor.'" global constraint_expr t = txt.replace(' or ', ' ').replace(' the ', ' ').strip().split() who, floor = t[0], t[6:-1] w, fl = (names.index(who), [('|first|second|third|fourth|fifth|sixth|' + 'seventh|eighth|ninth|tenth|top|bottom|').split('|').index(f) for f in floor] ) for f in fl: if f == 11: f = floors if f == 12: f = 1 constraint_expr += ' and alloc[%i] != %i' % (w, f)     def do_hi_lower(txt): " E.g. 'Miller lives on a higher floor than does Cooper.'" global constraint_expr t = txt.replace('.', '').strip().split() name_indices = [names.index(who) for who in (t[0], t[-1])] if 'lower' in t: name_indices = name_indices[::-1] constraint_expr += ' and alloc[%i] > alloc[%i]' % tuple(name_indices)   def do_adjacency(txt): ''' E.g. "Smith does not live on a floor adjacent to Fletcher's."''' global constraint_expr t = txt.replace('.', '').replace("'s", '').strip().split() name_indices = [names.index(who) for who in (t[0], t[-1])] constraint_expr += ' and abs(alloc[%i] - alloc[%i]) > 1' % tuple(name_indices)   def do_question(txt): global constraint_expr, names, lennames   exec_txt = ''' for alloc in product(range(1,floors+1), repeat=len(names)): if %s: break else: alloc = None ''' % constraint_expr exec(exec_txt, globals(), locals()) a = locals()['alloc'] if a: output= ['Floors are numbered from 1 to %i inclusive.' % floors] for a2n in zip(a, names): output += [' Floor %i is occupied by %s' % a2n] output.sort(reverse=True) print('\n'.join(output)) else: print('No solution found.') print()   handler = { 'namelist': do_namelist, 'floorcount': do_floorcount, 'not_live': do_not_live, 'not_either': do_not_either, 'hi_lower': do_hi_lower, 'adjacency': do_adjacency, 'question': do_question, } def parse_and_solve(problem): p = re.sub(r'\s+', ' ', problem).strip() for x in problem_re.finditer(p): groupname, txt = [(k,v) for k,v in x.groupdict().items() if v][0] #print ("%r, %r" % (groupname, txt)) handler[groupname](txt)
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
#JavaScript
JavaScript
function dot_product(ary1, ary2) { if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths"; var dotprod = 0; for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i]; return dotprod; }   print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3 print(dot_product([1,3,-5],[4,-2,-1,0])); // ==> exception
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#PHP
PHP
<?php   function squeezeString($string, $squeezeChar) { $previousChar = null; $squeeze = ''; $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar || $currentChar !== $squeezeChar) { $squeeze .= $charArray[$i]; } $previousChar = $currentChar; } return $squeeze; }   function isSqueezable($string, $squeezeChar) { return ($string !== squeezeString($string, $squeezeChar)); }   $strings = array( ['-', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '], ['1', '..1111111111111111111111111111111111111111111111111111111111111117777888'], ['l', "I never give 'em hell, I just tell the truth, and they think it's hell. "], [' ', ' --- Harry S Truman '], ['9', '0112223333444445555556666666777777778888888889999999999'], ['e', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ['k', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"], ); foreach ($strings as $params) { list($char, $original) = $params; echo 'Original  : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isSqueezable($original, $char)) { $squeeze = squeezeString($original, $char); echo 'Squeeze(', $char, ') : <<<', $squeeze, '>>> (len=', mb_strlen($squeeze), ')', PHP_EOL, PHP_EOL; } else { echo 'Squeeze(', $char, ') : string is not squeezable (char=', $char, ')...', PHP_EOL, PHP_EOL; } }
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. Rule 1: The funnel remains directly above the target. Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. Rule 4: The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. Stretch goal 2: Show scatter plots of all four results. Further information Further explanation and interpretation Video demonstration of the funnel experiment at the Mayo Clinic.
#Python
Python
import math   dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087]   dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]   def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs   def mean(xs): return sum(xs) / len(xs)   def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))   def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print     experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and must add up to   12. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. Task Write a computer program which outputs all valid combinations. Possible output   (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#BCPL
BCPL
get "libhdr"   let start() be for p=2 to 6 by 2 for s=1 to 7 for f=1 to 7 if p~=s & s~=f & p~=f & p+s+f=12 then writef("%N %N %N*N", p, s, f)
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and must add up to   12. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. Task Write a computer program which outputs all valid combinations. Possible output   (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#BASIC
BASIC
print "--police-- --sanitation-- --fire--"   for police = 2 to 7 step 2 for fire = 1 to 7 if fire = police then continue for sanitation = 12 - police - fire if sanitation = fire or sanitation = police then continue for if sanitation >= 1 and sanitation <= 7 then print rjust(police, 6); rjust(fire, 13); rjust(sanitation, 12) end if next fire next police
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#J
J
coclass 'delegator' operation=:3 :'thing__delegate ::thing y' thing=: 'default implementation'"_ setDelegate=:3 :'delegate=:y' NB. result is the reference to our new delegate delegate=:<'delegator'   coclass 'delegatee1'   coclass 'delegatee2' thing=: 'delegate implementation'"_   NB. set context in case this script was used interactively, instead of being loaded cocurrent 'base'
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Java
Java
interface Thingable { String thing(); }   class Delegator { public Thingable delegate;   public String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } }   class Delegate implements Thingable { public String thing() { return "delegate implementation"; } }   // Example usage // Memory management ignored for simplification public class DelegateExample { public static void main(String[] args) { // Without a delegate: Delegator a = new Delegator(); assert a.operation().equals("default implementation");   // With a delegate: Delegate d = new Delegate(); a.delegate = d; assert a.operation().equals("delegate implementation");   // Same as the above, but with an anonymous class: a.delegate = new Thingable() { public String thing() { return "anonymous delegate implementation"; } }; assert a.operation().equals("anonymous delegate implementation"); } }
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#Lambdatalk
Lambdatalk
  Here we present a rasterized version based on a single function "isInside".   1) isInside   Given A, B, C, P is in the triangle ABC if the three cross-products PA^PB, PB^PC and PC^PA are of equal sign.   {def isInside {lambda {:a :b :c :p} {let { {:ax {car :a}} {:ay {cdr :a}} {:bx {car :b}} {:by {cdr :b}} {:cx {car :c}} {:cy {cdr :c}} {:px {car :p}} {:py {cdr :p}} } {let { {:w1 {- {* {- :px :ax} {- :cy :ay}} {* {- :cx :ax} {- :py :ay}} }} {:w2 {- {* {- :px :bx} {- :ay :by}} {* {- :ax :bx} {- :py :by}} }} {:w3 {- {* {- :px :cx} {- :by :cy}} {* {- :bx :cx} {- :py :cy}} }} } {or {and {>= :w1 0} {>= :w2 0} {>= :w3 0}} {and {<  :w1 0} {<  :w2 0} {<  :w3 0}}} }}}} -> isInside   2) overlapping   For every points in the rectangle surrounding two given triangles we compute the number of points inside both. If it is null they don't overlap.   {def overlap   {def overlap.row {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h :y} {S.map {{lambda {:p0 :p1 :p2 :q0 :q1 :q2 :qp} {if {and {isInside :p0 :p1 :p2 :qp} {isInside :q0 :q1 :q2 :qp}} then x else}} :p0 :p1 :p2 :q0 :q1 :q2} {S.map {{lambda {:y :x} {cons :x :y}} :y} {S.serie :w :h} }}}}   {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h} {S.length {S.map {overlap.row :p0 :p1 :p2 :q0 :q1 :q2 :w :h} {S.serie :w :h}} }}} -> overlap   Given coordonnees will just be scaled to become integers, here miltiplied by 10   {overlap {cons 0 0} {cons 50 0} {cons 0 50} {cons 0 0} {cons 50 0} {cons 0 60} 0 60} -> 1326   {overlap {cons 0 0} {cons 0 50} {cons 50 0} {cons 0 0} {cons 0 50} {cons 50 0} 0 50} -> 1176   {overlap {cons 0 0} {cons 50 0} {cons 0 50} {cons -100 0} {cons -50 0} {cons -10 60} 100 60} -> 0   {overlap {cons 0 0} {cons 50 0} {cons 25 50} {cons 0 40} {cons 25 -10} {cons 50 40} -10 50} -> 831   {overlap {cons 0 0} {cons 10 10} {cons 0 20} {cons 20 10} {cons 30 0} {cons 30 20} 0 20} -> 0   {overlap {cons 0 0} {cons 10 10} {cons 0 20} {cons 20 10} {cons 30 -20} {cons 40 40} -20 40} -> 0   {overlap {cons 0 0} {cons 10 0} {cons 0 10} {cons 10 0} {cons 20 0} {cons 10 10} 0 20} -> 1   3) plot   The first triangle is plotted with 1s, the second with 2s, the intersection with 3s, else with dots.   {def plot {def plot.row {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h :y} {br}{S.replace \s by in {S.map {{lambda {:p0 :p1 :p2 :q0 :q1 :q2 :qp} {let { {:isinp {isInside :p0 :p1 :p2 :qp}} {:isinq {isInside :q0 :q1 :q2 :qp}} } {if {and :isinp :isinq} then 3 else {if :isnp then 1 else {if :isnq then 2 else .}}} }} :p0 :p1 :p2 :q0 :q1 :q2} {S.map {{lambda {:y :x} {cons :x :y}} :y} {S.serie :w :h} }}} }} {lambda {:p0 :p1 :p2 :q0 :q1 :q2 :w :h} {S.map {plot.row :p0 :p1 :p2 :q0 :q1 :q2 :w :h} {S.serie :w :h}} }} -> plot   {plot {cons 0 0} {cons 30 0} {cons 30 30} {cons 5 10} {cons 25 10} {cons 5 25} 0 30} ->   1111111111111111111111111111111 .111111111111111111111111111111 ..11111111111111111111111111111 ...1111111111111111111111111111 ....111111111111111111111111111 .....11111111111111111111111111 ......1111111111111111111111111 .......111111111111111111111111 ........11111111111111111111111 .........1111111111111111111111 .....22222333333333333333311111 .....22222233333333333331111111 .....22222223333333333311111111 .....22222222333333333111111111 .....22222222233333311111111111 .....22222222223333111111111111 .....22222222222331111111111111 .....22222222222.11111111111111 .....2222222222...1111111111111 .....222222222.....111111111111 .....2222222........11111111111 .....222222..........1111111111 .....22222............111111111 .....222...............11111111 .....22.................1111111 .....2...................111111 ..........................11111 ...........................1111 ............................111 .............................11 ..............................1  
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Elena
Elena
import system'io;   public program() { File.assign("output.txt").delete();   File.assign("\output.txt").delete();   Directory.assign("docs").delete();   Directory.assign("\docs").delete(); }
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Elixir
Elixir
File.rm!("input.txt") File.rmdir!("docs") File.rm!("/input.txt") File.rmdir!("/docs")
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by perm ⁡ ( A ) = ∑ σ ∏ i = 1 n M i , σ i {\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}} In both cases the sum is over the permutations σ {\displaystyle \sigma } of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known. Related task Permutations by swapping
#Lambdatalk
Lambdatalk
  {require lib_matrix}   {M.determinant {M.new [[1,2,3], [4,5,6], [7,8,9]]}} -> 0 {M.permanent {M.new [[1,2,3], [4,5,6], [7,8,9]]}} -> 450   {M.determinant {M.new [[1,2,3], [4,5,6], [7,8,-9]]}} -> 54 {M.permanent {M.new [[1,2,3], [4,5,6], [7,8,-9]]}} -> 216  
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.
#Forth
Forth
: safe-/ ( x y -- x/y ) ['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;
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.
#Fortran
Fortran
  program rosetta_divbyzero implicit none integer, parameter :: rdp = kind(1.d0) real(rdp) :: normal,zero   normal = 1.d0 zero = 0.d0   call div_by_zero_check(normal,zero)   contains   subroutine div_by_zero_check(x,y) use, intrinsic :: ieee_exceptions use, intrinsic :: ieee_arithmetic implicit none real(rdp), intent(in) :: x,y   real(rdp) :: check type(ieee_status_type) :: status_value logical :: flag flag = .false. ! Get the flags call ieee_get_status(status_value) ! Set the flags quiet call ieee_set_flag(ieee_divide_by_zero,.false.) write(*,*)"Inf supported? ",ieee_support_inf(check)   ! Calculation involving exception handling check = x/y write(*,*)"Is check finite?",ieee_is_finite(check), check   call ieee_get_flag(ieee_divide_by_zero, flag) if (flag) write(*,*)"Warning! Division by zero detected"   ! Restore the flags call ieee_set_status(status_value)   end subroutine div_by_zero_check   end program rosetta_divbyzero  
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D.C3.A9j.C3.A0_Vu
Déjà Vu
is-numeric s: true try: drop to-num s catch value-error: not   for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]: !.( v is-numeric v )
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#E
E
def isNumeric(specimen :String) { try { <import:java.lang.makeDouble>.valueOf(specimen) return true } catch _ { return false } }
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. 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
#Haskell
Haskell
import Data.List (groupBy, intersperse, sort, transpose) import Data.Char (ord, toUpper) import Data.Function(on) import Numeric (showHex)     hexFromChar :: Char -> String hexFromChar c = map toUpper $ showHex (ord c) ""   string :: String -> String string xs = ('\"' : xs) <> "\""   char :: Char -> String char c = ['\'', c, '\'']   size :: String -> String size = show . length   positions :: (Int, Int) -> String positions (a, b) = show a <> " " <> show b   forTable :: String -> [String] forTable xs = string xs : go (allUnique xs) where go Nothing = [size xs, "yes", "", "", ""] go (Just (u, ij)) = [size xs, "no", char u, hexFromChar u, positions ij]   showTable :: Bool -> Char -> Char -> Char -> [[String]] -> String showTable _ _ _ _ [] = [] showTable header ver hor sep contents = unlines $ hr : (if header then z : hr : zs else intersperse hr zss) <> [hr] where vss = map (map length) contents ms = map maximum (transpose vss) :: [Int] hr = concatMap (\n -> sep : replicate n hor) ms <> [sep] top = replicate (length hr) hor bss = map (map (`replicate` ' ') . zipWith (-) ms) vss zss@(z:zs) = zipWith (\us bs -> concat (zipWith (\x y -> (ver : x) <> y) us bs) <> [ver]) contents bss   table xs = showTable True '|' '-' '+' (["string", "length", "all unique", "1st diff", "hex", "positions"] : map forTable xs)   allUnique :: (Ord b, Ord a, Num b, Enum b) => [a] -> Maybe (a, (b, b)) allUnique xs = go . groupBy (on (==) fst) . sort . zip xs $ [0 ..] where go [] = Nothing go ([_]:us) = go us go (((u, i):(_, j):_):_) = Just (u, (i, j))   main :: IO () main = putStrLn $ table ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]
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
#Phix
Phix
with javascript_semantics constant tests = {"", `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman "}, fmt = """ length %2d input: <<<%s>>> length %2d output: <<<%s>>> """ for i=1 to length(tests) do string ti = tests[i], ci = unique(ti, "PRESORTED") printf(1,fmt,{length(ti),ti,length(ci),ci}) end for function collapsible(string t) -- sequence utf32 = utf8_to_utf32(t) -- maybe -- for i=2 to length(utf32) do -- """ -- if utf32[i]=utf32[i-1] then -- """ for i=2 to length(t) do if t[i]=t[i-1] then return true end if end for return false end function puts(1,"\nAs predicate: ") for i=1 to length(tests) do printf(1,"%t ",collapsible(tests[i])) end for puts(1,"\n")
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
#PHP
PHP
<?php   function collapseString($string) { $previousChar = null; $collapse = ''; $charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0 ; $i < count($charArray) ; $i++) { $currentChar = $charArray[$i]; if ($previousChar !== $currentChar) { $collapse .= $charArray[$i]; } $previousChar = $currentChar; } return $collapse; }   function isCollapsible($string) { return ($string !== collapseString($string)); }   $strings = array( '', 'another non colapsing string', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '..1111111111111111111111111111111111111111111111111111111111111117777888', "I never give 'em hell, I just tell the truth, and they think it's hell. ", ' --- Harry S Truman ', '0112223333444445555556666666777777778888888889999999999', "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'headmistressship', "😍😀🙌💃😍😍😍🙌", );   foreach ($strings as $original) { echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL; if (isCollapsible($original)) { $collapse = collapseString($original); echo 'Collapse : <<<', $collapse, '>>> (len=', mb_strlen($collapse), ')', PHP_EOL, PHP_EOL; } else { echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL; } }
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. 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
#Lua
Lua
function analyze(s) print(string.format("Examining [%s] which has a length of %d:", s, string.len(s))) if string.len(s) > 1 then local last = string.byte(string.sub(s,1,1)) for i=1,string.len(s) do local c = string.byte(string.sub(s,i,i)) if last ~= c then print(" Not all characters in the string are the same.") print(string.format(" '%s' (0x%x) is different at position %d", string.sub(s,i,i), c, i - 1)) return end end end print(" All characters in the string are the same.") end   function main() analyze("") analyze(" ") analyze("2") analyze("333") analyze(".55") analyze("tttTTT") analyze("4444 444k") end   main()
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#PicoLisp
PicoLisp
(de dining (Name State) (loop (prinl Name ": " State) (state 'State # Dispatch according to state (thinking 'hungry) # If thinking, get hungry (hungry # If hungry, grab random fork (if (rand T) (and (acquire leftFork) 'leftFork) (and (acquire rightFork) 'rightFork) ) ) (hungry 'hungry # Failed, stay hungry for a while (wait (rand 1000 3000)) ) (leftFork # If holding left fork, try right one (and (acquire rightFork) 'eating) (wait 2000) ) # then eat for 2 seconds (rightFork # If holding right fork, try left one (and (acquire leftFork) 'eating) (wait 2000) ) # then eat for 2 seconds ((leftFork rightFork) 'hungry # Otherwise, go back to hungry, (release (val State)) # release left or right fork (wait (rand 1000 3000)) ) # and stay hungry (eating 'thinking # After eating, resume thinking (release leftFork) (release rightFork) (wait 6000) ) ) ) ) # for 6 seconds   (setq *Philosophers (maplist '((Phils Forks) (let (leftFork (tmp (car Forks)) rightFork (tmp (cadr Forks))) (or (fork) # Parent: Collect child process IDs (dining (car Phils) 'hungry) ) ) ) # Initially hungry '("Aristotle" "Kant" "Spinoza" "Marx" "Russell") '("ForkA" "ForkB" "ForkC" "ForkD" "ForkE" .) ) )   (push '*Bye '(mapc kill *Philosophers)) # Terminate all upon exit
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PicoLisp
PicoLisp
(de disdate (Year Month Day) (let? Date (date Year Month Day) (let (Leap (date Year 2 29) D (- Date (date Year 1 1))) (if (and Leap (= 2 Month) (= 29 Day)) (pack "St. Tib's Day, YOLD " (+ Year 1166)) (and Leap (>= D 60) (dec 'D)) (pack (get '("Chaos" "Discord" "Confusion" "Bureaucracy" "The Aftermath") (inc (/ D 73)) ) " " (inc (% D 73)) ", YOLD " (+ Year 1166) ) ) ) ) )
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#PicoLisp
PicoLisp
(de neighbor (X Y Cost) (push (prop X 'neighbors) (cons Y Cost)) (push (prop Y 'neighbors) (cons X Cost)) )   (de dijkstra (Curr Dest) (let Cost 0 (until (== Curr Dest) (let (Min T Next) (for N (; Curr neighbors) (with (car N) (let D (+ Cost (cdr N)) (unless (and (: distance) (>= D @)) (=: distance D) ) ) (when (> Min (: distance)) (setq Min (: distance) Next This) ) (del (asoq Curr (: neighbors)) (:: neighbors)) ) ) (setq Curr Next Cost Min) ) ) Cost ) )
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Malbolge
Malbolge
seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n]; root[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]] persistance[n_Integer, base_: 10] := Length[seq[n, base]] - 2;
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n]; root[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]] persistance[n_Integer, base_: 10] := Length[seq[n, base]] - 2;
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#R
R
  names = unlist(strsplit("baker cooper fletcher miller smith", " "))   test <- function(floors) { f <- function(name) which(name == floors) if ((f('baker') != 5) && (f('cooper') != 1) && (any(f('fletcher') == 2:4)) && (f('miller') > f('cooper')) && (abs(f('fletcher') - f('cooper')) > 1) && (abs(f('smith') - f('fletcher')) > 1)) cat("\nFrom bottom to top: --> ", floors, "\n") }   do.perms <- function(seq, func, built = c()){ if (0 == length(seq)) func(built) else for (x in seq) do.perms( seq[!seq==x], func, c(x, built)) }  
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
#jq
jq
  def dot(x; y): reduce range(0;x|length) as $i (0; . + x[$i] * y[$i]);  
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
#Jsish
Jsish
/* Dot product, in Jsish */ function dot_product(ary1, ary2) { if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths"; var dotprod = 0; for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i]; return dotprod; }   ;dot_product([1,3,-5],[4,-2,-1]); ;//dot_product([1,3,-5],[4,-2,-1,0]);   /* =!EXPECTSTART!= dot_product([1,3,-5],[4,-2,-1]) ==> 3 dot_product([1,3,-5],[4,-2,-1,0]) ==> PASS!: err = can't find dot product: arrays have different lengths =!EXPECTEND!= */
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#Prolog
Prolog
squeeze_( [], _, [] ). squeeze_( [A], _, [A] ). squeeze_( [A,A|T], A, R ) :- squeeze_( [A|T], A, R ). squeeze_( [A,A|T], B, [A|R] ) :- dif( A, B ), squeeze_( [A|T], B, R ). squeeze_( [A,B|T], S, [A|R] ) :- dif( A, B ), squeeze_( [B|T], S, R ).   squeeze( Str, SqueezeChar, Collapsed ) :- string_chars( Str, Chars ), squeeze_( Chars, SqueezeChar, Result ), string_chars( Collapsed, Result ).
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#Python
Python
from itertools import groupby   def squeezer(s, txt): return ''.join(item if item == s else ''.join(grp) for item, grp in groupby(txt))   if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',') for txt, chars in zip(strings, squeezers): this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) for ch in chars: this = f"Squeezer '{ch}'" sqz = squeezer(ch, txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. Rule 1: The funnel remains directly above the target. Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. Rule 4: The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. Stretch goal 2: Show scatter plots of all four results. Further information Further explanation and interpretation Video demonstration of the funnel experiment at the Mayo Clinic.
#Racket
Racket
#lang racket (require math/distributions math/statistics plot)   (define dxs '(-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181 -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521 -0.799 0.087))   (define dys '(0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000 0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226 0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104 -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032))   ;(define radii (map abs (sample (normal-dist 0 1) 100))) ;(define angles (sample (uniform-dist (- pi) pi) 100)) ;(define dxs (map (λ (r theta) (* r (cos theta))) radii angles)) ;(define dys (map (λ (r theta) (* r (sin theta))) radii angles))   (define (funnel dxs rule) (let ([x 0]) (for/fold ([rxs null]) ([dx dxs]) (let ([rx (+ x dx)]) (set! x (rule x dx)) (cons rx rxs)))))   (define (experiment label rule) (define (p s) (real->decimal-string s 4)) (let ([rxs (funnel dxs rule)] [rys (funnel dys rule)]) (displayln label) (printf "Mean x, y  : ~a, ~a\n" (p (mean rxs)) (p (mean rys))) (printf "Std dev x, y: ~a, ~a\n\n" (p (stddev rxs)) (p (stddev rys))) #;(plot (points (map vector rxs rys) #:x-min -15 #:x-max 15 #:y-min -15 #:y-max 15))))   (experiment "Rule 1:" (λ (z dz) 0)) (experiment "Rule 2:" (λ (z dz) (- dz))) (experiment "Rule 3:" (λ (z dz) (- (+ z dz)))) (experiment "Rule 4:" (λ (z dz) (+ z dz)))
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. Rule 1: The funnel remains directly above the target. Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. Rule 4: The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. Stretch goal 2: Show scatter plots of all four results. Further information Further explanation and interpretation Video demonstration of the funnel experiment at the Mayo Clinic.
#Raku
Raku
sub mean { @_ R/ [+] @_ } sub stddev { # <(x - <x>)²> = <x²> - <x>² sqrt( mean(@_ »**» 2) - mean(@_)**2 ) }   constant @dz = < -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181 -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521 -0.799 0.087 > Z+ (1i X* < 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000 0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226 0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104 -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032 >);   constant @rule = -> \z, \dz { 0 }, -> \z, \dz { -dz }, -> \z, \dz { -z - dz }, -> \z, \dz { z + dz }, ;   for @rule { say "Rule $(++$):"; my $target = 0i; my @z = gather for @dz -> $dz { take $target + $dz; $target = .($target, $dz) } printf "Mean x, y  : %7.4f %7.4f\n", mean(@z».re), mean(@z».im); printf "Std dev x, y  : %7.4f %7.4f\n", stddev(@z».re), stddev(@z».im); }
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and must add up to   12. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. Task Write a computer program which outputs all valid combinations. Possible output   (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#C
C
  #include<stdio.h>   int main() { int police,sanitation,fire;   printf("Police Sanitation Fire\n"); printf("----------------------------------");   for(police=2;police<=6;police+=2){ for(sanitation=1;sanitation<=7;sanitation++){ for(fire=1;fire<=7;fire++){ if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){ printf("\n%d\t\t%d\t\t%d",police,sanitation,fire); } } } }   return 0; }  
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#JavaScript
JavaScript
function Delegator() { this.delegate = null ; this.operation = function(){ if(this.delegate && typeof(this.delegate.thing) == 'function') return this.delegate.thing() ; return 'default implementation' ; } }   function Delegate() { this.thing = function(){ return 'Delegate Implementation' ; } }   function testDelegator(){ var a = new Delegator() ; document.write(a.operation() + "\n") ;   a.delegate = 'A delegate may be any object' ; document.write(a.operation() + "\n") ;   a.delegate = new Delegate() ; document.write(a.operation() + "\n") ; }
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Julia
Julia
module Delegates   export Delegator, Delegate   struct Delegator{T} delegate::T end   struct Delegate end   operation(x::Delegator) = thing(x.delegate) thing(::Any) = "default implementation" thing(::Delegate) = "delegate implementation"   end # module Delegates
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#Lua
Lua
function det2D(p1,p2,p3) return p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y) end   function checkTriWinding(p1,p2,p3,allowReversed) local detTri = det2D(p1,p2,p3) if detTri < 0.0 then if allowReversed then local t = p3 p3 = p2 p2 = t else error("triangle has wrong winding direction") end end return nil end   function boundaryCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) < eps end   function boundaryDoesntCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) <= eps end   function triTri2D(t1,t2,eps,allowReversed,onBoundary) eps = eps or 0.0 allowReversed = allowReversed or false onBoundary = onBoundary or true   -- triangles must be expressed anti-clockwise checkTriWinding(t1[1], t1[2], t1[3], allowReversed) checkTriWinding(t2[1], t2[2], t2[3], allowReversed)   local chkEdge if onBoundary then -- points on the boundary are considered as colliding chkEdge = boundaryCollideChk else -- points on the boundary are not considered as colliding chkEdge = boundaryDoesntCollideChk end   -- for edge E of triangle 1 for i=0,2 do local j = (i+1)%3   -- check all points of triangle 2 lay on the external side of the edge E. -- If they do, the triangles do not collide if chkEdge(t1[i+1], t1[j+1], t2[1], eps) and chkEdge(t1[i+1], t1[j+1], t2[2], eps) and chkEdge(t1[i+1], t1[j+1], t2[3], eps) then return false end end   -- for edge E of triangle 2 for i=0,2 do local j = (i+1)%3   -- check all points of triangle 1 lay on the external side of the edge E. -- If they do, the triangles do not collide if chkEdge(t2[i+1], t2[j+1], t1[1], eps) and chkEdge(t2[i+1], t2[j+1], t1[2], eps) and chkEdge(t2[i+1], t2[j+1], t1[3], eps) then return false end end   -- the triangles collide return true end   function formatTri(t) return "Triangle: ("..t[1].x..", "..t[1].y .."), ("..t[2].x..", "..t[2].y .."), ("..t[3].x..", "..t[3].y..")" end   function overlap(t1,t2,eps,allowReversed,onBoundary) if triTri2D(t1,t2,eps,allowReversed,onBoundary) then return "overlap\n" else return "do not overlap\n" end end   -- Main local t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}} local t2 = {{x=0,y=0},{x=5,y=0},{x=0,y=6}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2))   t1 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}} t2 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,true))   t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}} t2 = {{x=-10,y=0},{x=-5,y=0},{x=-1,y=6}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2))   t1 = {{x=0,y=0},{x=5,y=0},{x=2.5,y=5}} t2 = {{x=0,y=4},{x=2.5,y=-1},{x=5,y=4}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2))   t1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}} t2 = {{x=2,y=1},{x=3,y=0},{x=3,y=2}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2))   t1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}} t2 = {{x=2,y=1},{x=3,y=-2},{x=3,y=4}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2))   -- Barely touching t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}} t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,false,true))   -- Barely touching local t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}} local t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,false,false))
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Emacs_Lisp
Emacs Lisp
(delete-file "input.txt") (delete-directory "docs") (delete-file "/input.txt") (delete-directory "/docs")
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Erlang
Erlang
  -module(delete). -export([main/0]).   main() -> % current directory ok = file:del_dir( "docs" ), ok = file:delete( "input.txt" ), % root directory ok = file:del_dir( "/docs" ), ok = file:delete( "/input.txt" ).  
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by perm ⁡ ( A ) = ∑ σ ∏ i = 1 n M i , σ i {\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}} In both cases the sum is over the permutations σ {\displaystyle \sigma } of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known. Related task Permutations by swapping
#Lua
Lua
-- Johnson–Trotter permutations generator _JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end   function _JT:largestMobile() for i=#self.values,1,-1 do local loc=self.positions[i]+self.directions[i] if loc >= 1 and loc <= #self.values and self.values[loc] < i then return i end end return 0 end   function _JT:next() local r=self:largestMobile() if r==0 then return false end local rloc=self.positions[r] local lloc=rloc+self.directions[r] local l=self.values[lloc] self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc] self.positions[l],self.positions[r] = self.positions[r],self.positions[l] self.sign=-self.sign for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end return true end   -- matrix class   _MTX={} function MTX(matrix) setmetatable(matrix,{__index=_MTX}) matrix.rows=#matrix matrix.cols=#matrix[1] return matrix end   function _MTX:dump() for _,r in ipairs(self) do print(unpack(r)) end end   function _MTX:perm() return self:det(1) end function _MTX:det(perm) local det=0 local jt=JT(self.cols) repeat local pi=perm or jt.sign for i,v in ipairs(jt.values) do pi=pi*self[i][v] end det=det+pi until not jt:next() return det end   -- test   matrix=MTX { { 7, 2, -2, 4}, { 4, 4, 1, 7}, {11, -8, 9, 10}, {10, 5, 12, 13} } matrix:dump(); print("det:",matrix:det(), "permanent:",matrix:perm(),"\n")   matrix2=MTX { {-2, 2,-3}, {-1, 1, 3}, { 2, 0,-1} } matrix2:dump(); print("det:",matrix2:det(), "permanent:",matrix2:perm())  
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const divByZeroResult As Integer = -9223372036854775808   Sub CheckForDivByZero(result As Integer) If result = divByZeroResult Then Print "Division by Zero" Else Print "Division by Non-Zero" End If End Sub   Dim As Integer x, y   x = 0 : y = 0 CheckForDivByZero(x/y) ' automatic conversion to type of parameter which is Integer x = 1 CheckForDivByZero(x/y) x = -1 CheckForDivByZero(x/y) y = 1 CheckForDivByZero(x/y) Print Print "Press any key to exit" Sleep
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.
#FutureBasic
FutureBasic
  include "ConsoleWindow"   on error stop dim as long a print a / 0  
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.
#Gambas
Gambas
Public Sub Main()   Try Print 1 / 0 If Error Then Print Error.Text   End
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. 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
#EasyLang
EasyLang
func is_numeric a$ . r . h = number a$ r = 1 - error # because every variable must be used h = h . for s$ in [ "abc" "21a" "1234" "-13" "7.65" ] call is_numeric s$ r if r = 1 print s$ & " is numeric" else print s$ & " is not numeric" . .
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#EchoLisp
EchoLisp
  (string->number "albert") → #f (string->number -666) → -666 (if (string->number 666) 'YES 'NO) → YES  
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. 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
#J
J
  rc_unique=: monad define string=. '"' , y , '"' self_classification=. = y NB. deprecated- consumes space proportional to the squared tally of y (*: # y) is_unique=. self_classification =&# y if. is_unique do. (# y) ; string ; 'unique' else. duplicate_masks=. (#~ (1 < +/"1)) self_classification duplicate_characters=. ~. y #~ +./ duplicate_masks ASCII_values_of_duplicates=. a. i. duplicate_characters markers=. duplicate_masks { ' ^' A=. (# y) ; string , ' ' ,. markers B=. 'duplicate' , ASCII_values_of_duplicates ('<' , (#~ 31&<)~ , '> ASCII ' , ":@:[)"0 duplicate_characters A , < B end. )  
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. 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
#Java
Java
  import java.util.HashMap; import java.util.Map;   // Title: Determine if a string has all unique characters   public class StringUniqueCharacters {   public static void main(String[] args) { System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions"); System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------"); for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) { processString(s); } }       private static void processString(String input) { Map<Character,Integer> charMap = new HashMap<>(); char dup = 0; int index = 0; int pos1 = -1; int pos2 = -1; for ( char key : input.toCharArray() ) { index++; if ( charMap.containsKey(key) ) { dup = key; pos1 = charMap.get(key); pos2 = index; break; } charMap.put(key, index); } String unique = dup == 0 ? "yes" : "no"; String diff = dup == 0 ? "" : "'" + dup + "'"; String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase(); String position = dup == 0 ? "" : pos1 + " " + pos2; System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length(), unique, diff, hex, position); }   }  
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
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;   /* PRINT NUMBER */ PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('.....$'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = .S(5); DIGIT: P = P - 1; C = N MOD 10 + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   /* STRING LENGTH */ STR$LEN: PROCEDURE (STR) ADDRESS; DECLARE (STR, I) ADDRESS, S BASED STR BYTE; I = 0; DO WHILE S(I) <> '$'; I = I + 1; END; RETURN I; END STR$LEN;   /* COLLAPSE */ COLLAPSE: PROCEDURE (IN, OUT); DECLARE (IN, OUT) ADDRESS, (I BASED IN, O BASED OUT, C) BYTE; C = I; DO WHILE C <> '$'; IN = IN + 1; IF I <> C THEN DO; O = C; OUT = OUT + 1; C = I; END; END; O = '$'; END COLLAPSE;   /* PRINT STRING AND LENGTH WITH BRACKETS */ PRINT$BRACKETS: PROCEDURE (S); DECLARE S ADDRESS; CALL PRINT$NUMBER(STR$LEN(S)); CALL PRINT(.' <<<$'); CALL PRINT(S); CALL PRINT(.('>>>',13,10,'$')); END PRINT$BRACKETS;   /* GIVEN A STRING, PRINT IT AND ITS COLLAPSED FORM */ SHOW: PROCEDURE (S); DECLARE S ADDRESS, BUFFER (256) BYTE; CALL COLLAPSE(S, .BUFFER); CALL PRINT$BRACKETS(S); CALL PRINT$BRACKETS(.BUFFER); CALL PRINT(.(13,10,'$')); END SHOW;   /* STRINGS FROM THE TASK */ DECLARE X (5) ADDRESS; X(0)=.'$'; X(1)=.('''IF I WERE TWO-FACED, WOULD I BE WEARING ', 'THIS ONE.'' --- ABRAHAM LINCOLN $'); X(2)=.('..111111111111111111111111111111111111111', '1111111111111111111111117777888$'); X(3)=.('I NEVER GIVE ''EM HELL, I JUST TELL THE TR', 'UTH, AND THEY THINK IT''S HELL. $'); X(4)=.(' ', ' --- HARRY S TRUMAN $');   DECLARE I BYTE; DO I=0 TO LAST(X); CALL SHOW(X(I)); END; CALL EXIT; EOF  
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
#Prolog
Prolog
collapse_( [], [] ). collapse_( [A], [A] ). collapse_( [A,A|T], R ) :- collapse_( [A|T], R ). collapse_( [A,B|T], [A|R] ) :- dif( A, B ), collapse_( [B|T], R ).   collapse( Str, Collapsed ) :- string_chars( Str, Chars ), collapse_( Chars, Result ), string_chars( Collapsed, Result ).
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. 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
#Maple
Maple
CheckSame:=proc(s) local i, index; printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s)); for i from 2 to StringTools:-Length(s) do if (s[i - 1] <> s[i]) then printf("The given string has different characters.\n"); printf("The first different character is %a (0x%x) which appears at index %a.\n\n", s[i], convert(s[i], 'bytes')[1], i); return; end if; end do; # if no difference found printf("The given string has all same characters.\n\n"); end proc:   # Test CheckSame(""); CheckSame(" "); CheckSame("2"); CheckSame("333"); CheckSame(".55"); CheckSame("tttTTT"); CheckSame("4444 444k");
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. 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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[AllSameCharacters] AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf}, If[Length[c] > 1, tf = AllTrue[Rest[c], (i++; # == First[c]) &]; If[tf, Print["input = \"", s, "\", Length = ", StringLength[s], ", All the same!"] , Print["input = \"", s, "\", Length = ", StringLength[s], ", Character " <> ToString[i + 1] <> " is different from character " <> ToString[i], ", hex = ", IntegerString[First@ToCharacterCode[c[[i + 1]]], 16]] ] , Print["input = \"", s, "\", Length = ", StringLength[s], ", All the same!"] ]; ] AllSameCharacters[""] AllSameCharacters[" "] AllSameCharacters["2"] AllSameCharacters["333"] AllSameCharacters[".55"] AllSameCharacters["tttTTT"] AllSameCharacters["4444 444k"]
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#Pike
Pike
class Philosopher { string name; object left; object right;   void create(string _name, object _left, object _right) { name = _name; left = _left; right = _right; }   void take_forks() { if (left->take(this) && right->take(this)) { write("%s is EATING\n", name); call_out(drop_forks, random(30)); } else { write("%s is WAITING\n", name); if (random(10) >= 8) drop_forks(); call_out(take_forks, random(10)); } }   void drop_forks() { left->drop(this); right->drop(this); write("%s is THINKING\n", name); call_out(take_forks, random(30)); } }   class Fork { int number; Philosopher user;   void create(int _number) { number = _number; }   int take(object new_user) { if (!user) { write("%s takes fork %d\n", new_user->name, number); user = new_user; return 1; } else if (new_user == user) { write("%s has fork %d\n", new_user->name, number); return 1; } else write("%s tries to take fork %d from %s\n", new_user->name, number, user->name); }   void drop(object old_user) { if (old_user == user) { write("%s drops fork %d\n", old_user->name, number); user = 0; } } }   int main(int argc, array argv) {   array forks = ({ Fork(1), Fork(2), Fork(3), Fork(4), Fork(5) }); array philosophers = ({ Philosopher("einstein", forks[0], forks[1]), Philosopher("plato", forks[1], forks[2]), Philosopher("sokrates", forks[2], forks[3]), Philosopher("chomsky", forks[3], forks[4]), Philosopher("archimedes", forks[4], forks[0]), });   call_out(philosophers[0]->take_forks, random(5)); call_out(philosophers[1]->take_forks, random(5)); call_out(philosophers[2]->take_forks, random(5)); call_out(philosophers[3]->take_forks, random(5)); call_out(philosophers[4]->take_forks, random(5)); return -1; }
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Pike
Pike
> Calendar.Discordian.now()->format_ext_ymd(); Result: "Pungenday, 59 Bureaucracy 3177" > Calendar.Discordian.Day(Calendar.Day(2011,11,11))->format_ext_ymd(); Result: "Setting Orange, 23 The Aftermath 3177" > Calendar.Discordian.Day(Calendar.Badi.Day(168,13,9))->format_ext_ymd(); Result: "Setting Orange, 23 The Aftermath 3177" > Calendar.Day((Calendar.Discordian.Month()+1)->day(1)); Result: Day(Thu 20 Oct 2011)
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#Prolog
Prolog
rpath([target|reversed_path], distance)
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Modula-2
Modula-2
MODULE DigitalRoot; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Root = RECORD persistence,root : LONGINT; END;   PROCEDURE digitalRoot(inRoot,base : LONGINT) : Root; VAR root,persistence,num : LONGINT; BEGIN root := ABS(inRoot); persistence := 0; WHILE root>=base DO num := root; root := 0; WHILE num#0 DO root := root + (num MOD base); num := num DIV base; END; INC(persistence) END; RETURN Root{persistence, root} END digitalRoot;   PROCEDURE Print(n,b : LONGINT); VAR buf : ARRAY[0..63] OF CHAR; r : Root; BEGIN r := digitalRoot(n,b); FormatString("%u (base %u): persistence=%u, digital root=%u\n", buf, n, b, r.persistence, r.root); WriteString(buf) END Print;   VAR buf : ARRAY[0..63] OF CHAR; b,n : LONGINT; r : Root; BEGIN Print(1,10); Print(14,10); Print(267,10); Print(8128,10); Print(39390,10); Print(627615,10); Print(588225,10);   ReadChar END DigitalRoot.
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#Racket
Racket
  #lang racket   ;; A quick `amb' implementation (define fails '()) (define (fail) (if (pair? fails) ((car fails)) (error "no more choices!"))) (define (amb xs) (let/cc k (set! fails (cons k fails))) (if (pair? xs) (begin0 (car xs) (set! xs (cdr xs))) (begin (set! fails (cdr fails)) (fail)))) (define (assert . conditions) (when (memq #f conditions) (fail)))   ;; Convenient macro for definining problem items (define-syntax-rule (with: all (name ...) #:in choices body ...) (let* ([cs choices] [name (amb cs)] ... [all `([,name name] ...)]) body ...))   ;; ===== problem translation starts here =====   ;; Baker, Cooper, Fletcher, Miller, and Smith live on different floors ;; of an apartment house that contains only five floors. (with: residents [Baker Cooper Fletcher Miller Smith] #:in (range 1 6)  ;; Some helpers (define (on-top x) (for/and ([y residents]) (x . >= . (car y)))) (define (on-bottom x) (for/and ([y residents]) (x . <= . (car y)))) (define (adjacent x y) (= 1 (abs (- x y)))) (assert  ;; ... live on different floors ... (assert (= 5 (length (remove-duplicates (map car residents)))))  ;; Baker does not live on the top floor. (not (on-top Baker))  ;; Cooper does not live on the bottom floor. (not (on-bottom Cooper))  ;; Fletcher does not live on either the top or the bottom floor. (not (on-top Fletcher)) (not (on-bottom Fletcher))  ;; Miller lives on a higher floor than does Cooper. (> Miller Cooper)  ;; Smith does not live on a floor adjacent to Fletcher's. (not (adjacent Smith Fletcher))  ;; Fletcher does not live on a floor adjacent to Cooper's. (assert (not (adjacent Fletcher Cooper))))  ;; Where does everyone live? (printf "Solution:\n") (for ([x (sort residents > #:key car)]) (apply printf " ~a. ~a\n" x)))  
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
#Julia
Julia
x = [1, 3, -5] y = [4, -2, -1] z = dot(x, y) z = x'*y z = x ⋅ y
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
#K
K
+/1 3 -5 * 4 -2 -1 3   1 3 -5 _dot 4 -2 -1 3
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#R
R
squeeze_string <- function(string, character){   str_iterable <- strsplit(string, "")[[1]]   message(paste0("Original String: ", "<<<", string, ">>>\n", "Length: ", length(str_iterable), "\n", "Character: ", character))   detect <- rep(TRUE, length(str_iterable))     for(i in 2:length(str_iterable)){   if(length(str_iterable) == 0) break if(str_iterable[i] != character) next   if(str_iterable[i] == str_iterable[i-1])   detect[i] <- FALSE }   squeezed_string <- paste(str_iterable[detect], collapse = "")   message(paste0("squeezed string: ", "<<<",squeezed_string, ">>>\n", "Length: ", length(str_iterable[detect])), "\n")   }     squeeze_string("", " ") squeeze_string("'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ", "-") squeeze_string("..1111111111111111111111111111111111111111111111111111111111111117777888", "7") squeeze_string("I never give 'em hell, I just tell the truth, and they think it's hell. ", ".") squeeze_string(" --- Harry S Truman ", " ") squeeze_string(" --- Harry S Truman ", "-") squeeze_string(" --- Harry S Truman ", "r") squeeze_string(" Ciao Mamma, guarda come mi diverto!!! ", "!")  
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#Racket
Racket
#lang racket/base   (define (squeeze-string s c) (let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null)) (cond [(null? cs) (values l (list->string (reverse acc)))] [(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)] [else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons (car cs) acc))])))   (define (report-squeeze s c) (define-values (l′ s′) (squeeze-string s c)) (printf "Squeezing ~s in «««~a»»» (length ~a)~%" c s (string-length s)) (printf "Result: «««~a»»» (length ~a)~%~%" s′ l′))   (define (Determine-if-a-string-is-squeezeable) (report-squeeze "" #\space) (report-squeeze "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " #\-) (report-squeeze "..1111111111111111111111111111111111111111111111111111111111111117777888" #\7) (report-squeeze "I never give 'em hell, I just tell the truth, and they think it's hell. " #\.) (define truman-sig " --- Harry S Truman ") (report-squeeze truman-sig #\space) (report-squeeze truman-sig #\-) (report-squeeze truman-sig #\r))   (module+ main (Determine-if-a-string-is-squeezeable))
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. Rule 1: The funnel remains directly above the target. Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. Rule 4: The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. Stretch goal 2: Show scatter plots of all four results. Further information Further explanation and interpretation Video demonstration of the funnel experiment at the Mayo Clinic.
#Ruby
Ruby
def funnel(dxs, &rule) x, rxs = 0, [] for dx in dxs rxs << (x + dx) x = rule[x, dx] end rxs end   def mean(xs) xs.inject(:+) / xs.size end   def stddev(xs) m = mean(xs) Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size) end   def experiment(label, dxs, dys, &rule) rxs, rys = funnel(dxs, &rule), funnel(dys, &rule) puts label puts 'Mean x, y  : %7.4f, %7.4f' % [mean(rxs), mean(rys)] puts 'Std dev x, y : %7.4f, %7.4f' % [stddev(rxs), stddev(rys)] puts end   dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087]   dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]   experiment('Rule 1:', dxs, dys) {|z, dz| 0} experiment('Rule 2:', dxs, dys) {|z, dz| -dz} experiment('Rule 3:', dxs, dys) {|z, dz| -(z+dz)} experiment('Rule 4:', dxs, dys) {|z, dz| z+dz}
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and must add up to   12. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. Task Write a computer program which outputs all valid combinations. Possible output   (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#C.23
C#
using System; public class Program { public static void Main() { for (int p = 2; p <= 7; p+=2) { for (int s = 1; s <= 7; s++) { int f = 12 - p - s; if (s >= f) break; if (f > 7) continue; if (s == p || f == p) continue; //not even necessary Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}"); Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}"); } } } }
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Kotlin
Kotlin
// version 1.1.51   interface Thingable { fun thing(): String? }   class Delegate(val responds: Boolean) : Thingable { override fun thing() = if (responds) "delegate implementation" else null }   class Delegator(d: Delegate) : Thingable by d { fun operation() = thing() ?: "default implementation" }   fun main(args: Array<String>) { // delegate doesn't respond to 'thing' val d = Delegate(false) val dd = Delegator(d) println(dd.operation())   // delegate responds to 'thing' val d2 = Delegate(true) val dd2 = Delegator(d2) println(dd2.operation()) }
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Latitude
Latitude
Delegator ::= Object clone tap { self delegate := Nil. self clone := { Parents above (parent self, 'clone) call tap { self delegate := #'(self delegate). }. }. self operation := { localize. if { this delegate slot? 'thing. } then { this delegate thing. } else { "default implementation". }. }. }.   Delegate ::= Object clone tap { self thing := "delegate implementation". }.   ;; No delegate foo := Delegator clone. println: foo operation. ;; "default implementation"   ;; Delegate which lacks `thing` foo delegate := Object. println: foo operation. ;; "default implementation"   ;; Delegate which implements `thing` foo delegate := Delegate. println: foo operation. ;; "delegate implementation"
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}}; p2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, 0}, {3, 2}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, -2}, {3, 4}}; ! RegionDisjoint[p1, p2]   p1 = Polygon@{{0, 0}, {1, 0}, {0, 1}}; p2 = Polygon@{{1, 0}, {2, 0}, {1, 1}}; ! RegionDisjoint[p1, p2]
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#F.23
F#
open System.IO   [<EntryPoint>] let main argv = let fileName = "input.txt" let dirName = "docs" for path in ["."; "/"] do ignore (File.Delete(Path.Combine(path, fileName))) ignore (Directory.Delete(Path.Combine(path, dirName))) 0
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Factor
Factor
"docs" "/docs" [ delete-tree ] bi@ "input.txt" "/input.txt" [ delete-file ] bi@
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by perm ⁡ ( A ) = ∑ σ ∏ i = 1 n M i , σ i {\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}} In both cases the sum is over the permutations σ {\displaystyle \sigma } of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known. Related task Permutations by swapping
#Maple
Maple
M:=<<2|9|4>,<7|5|3>,<6|1|8>>:   with(LinearAlgebra):   Determinant(M); Permanent(M);
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by perm ⁡ ( A ) = ∑ σ ∏ i = 1 n M i , σ i {\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}} In both cases the sum is over the permutations σ {\displaystyle \sigma } of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known. Related task Permutations by swapping
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Permanent[m_List] := With[{v = Array[x, Length[m]]}, Coefficient[Times @@ (m.v), Times @@ v] ]
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.
#Go
Go
package main   import "fmt"   func divCheck(x, y int) (q int, ok bool) { defer func() { recover() }() q = x / y return q, true }   func main() { fmt.Println(divCheck(3, 2)) fmt.Println(divCheck(3, 0)) }
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.
#Groovy
Groovy
def dividesByZero = { double n, double d -> assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.' (n/d).infinite || (n/d).naN }
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. 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
defmodule RC do def is_numeric(str) do case Float.parse(str) do {_num, ""} -> true _ -> false end end end   ["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1)
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Erlang
Erlang
is_numeric(L) -> Float = (catch erlang:list_to_float(L)), Int = (catch erlang:list_to_integer(L)), is_number(Float) orelse is_number(Int).
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as unique   process the strings from left─to─right   if       unique,   display a message saying such   if not unique,   then:   display a message saying such   display what character is duplicated   only the 1st non─unique character need be displayed   display where "both" duplicated characters are in the string   the above messages can be part of a single message   display the hexadecimal value of the duplicated character Use (at least) these five test values   (strings):   a string of length     0   (an empty string)   a string of length     1   which is a single period   (.)   a string of length     6   which contains:   abcABC   a string of length     7   which contains a blank in the middle:   XYZ  ZYX   a string of length   36   which   doesn't   contain the letter "oh": 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ Show all output here on this page. 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
#JavaScript
JavaScript
(() => { 'use strict';   // duplicatedCharIndices :: String -> Maybe (Char, [Int]) const duplicatedCharIndices = s => { const duplicates = filter(g => 1 < g.length)( groupBy(on(eq)(snd))( sortOn(snd)( zip(enumFrom(0))(chars(s)) ) ) ); return 0 < duplicates.length ? Just( fanArrow(compose(snd, fst))(map(fst))( sortOn(compose(fst, fst))( duplicates )[0] ) ) : Nothing(); };   // ------------------------TEST------------------------ const main = () => console.log( fTable('First duplicated character, if any:')( s => `'${s}' (${s.length})` )(maybe('None')(tpl => { const [c, ixs] = Array.from(tpl); return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}` }))(duplicatedCharIndices)([ "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" ]) );     // -----------------GENERIC FUNCTIONS------------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // chars :: String -> [Char] const chars = s => s.split('');   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x);   // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { let v = x; while (true) { yield v; v = 1 + v; } }   // eq (==) :: Eq a => a -> a -> Bool const eq = a => b => a === b;   // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => // Compose a function from a simple value to a tuple of // the separate outputs of two different functions. g => x => Tuple(f(x))(g(x));   // filter :: (a -> Bool) -> [a] -> [a] const filter = f => xs => xs.filter(f);   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // fTable :: String -> (a -> String) -> (b -> String) // -> (a -> b) -> [a] -> String const fTable = s => xShow => fxShow => f => xs => { // Heading -> x display function -> // fx display function -> // f -> values -> tabular string const ys = xs.map(xShow), w = Math.max(...ys.map(length)); return s + '\n' + zipWith( a => b => a.padStart(w, ' ') + ' -> ' + b )(ys)( xs.map(x => fxShow(f(x))) ).join('\n'); };   // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] const groupBy = fEq => // Typical usage: groupBy(on(eq)(f), xs) xs => 0 < xs.length ? (() => { const tpl = xs.slice(1).reduce( (gw, x) => { const gps = gw[0], wkg = gw[1]; return fEq(wkg[0])(x) ? ( Tuple(gps)(wkg.concat([x])) ) : Tuple(gps.concat([wkg]))([x]); }, Tuple([])([xs[0]]) ); return tpl[0].concat([tpl[1]]) })() : [];   // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // map :: (a -> b) -> [a] -> [b] const map = f => xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f);   // maybe :: b -> (a -> b) -> Maybe a -> b const maybe = v => // Default value (v) if m is Nothing, or f(m.Just) f => m => m.Nothing ? v : f(m.Just);   // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c const on = f => g => a => b => f(g(a))(g(b));   // ord :: Char -> Int const ord = c => c.codePointAt(0);   // showHex :: Int -> String const showHex = n => n.toString(16);   // snd :: (a, b) -> b const snd = tpl => tpl[1];   // sortOn :: Ord b => (a -> b) -> [a] -> [a] const sortOn = f => // Equivalent to sortBy(comparing(f)), but with f(x) // evaluated only once for each x in xs. // ('Schwartzian' decorate-sort-undecorate). xs => xs.map( x => [f(x), x] ).sort( (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) ).map(x => x[1]);   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => xs => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => (x, y) => f(x)(y)   // zip :: [a] -> [b] -> [(a, b)] const zip = xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => Tuple(x)(vs[i])); };   // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => f(x)(vs[i])); };   // MAIN --- return main(); })();
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
#PureBasic
PureBasic
EnableExplicit DataSection STR1: Data.s "" STR2: Data.s "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln " STR3: Data.s "..1111111111111111111111111111111111111111111111111111111111111117777888" STR4: Data.s "I never give 'em hell, I just tell the truth, and they think it's hell. " STR5: Data.s " --- Harry S Truman " EndDataSection   Procedure.s collapse(txt$) Define *c.Character=@txt$, last.c=0, result$ While *c\c If *c\c<>last result$+Chr(*c\c) last=*c\c EndIf *c+SizeOf(Character) Wend ProcedureReturn result$ EndProcedure   OpenConsole("") Define *p_data=?STR1, buf$ While *p_data<=?STR4+StringByteLength(PeekS(?STR4))+2 buf$=PeekS(*p_data) PrintN("Before collapse: «««"+buf$+"»»» (length: "+Str(Len(buf$))+")") buf$=collapse(PeekS(*p_data)) PrintN("After collapse: «««"+buf$+~"»»» (length: "+Str(Len(buf$))+~")\n") *p_data+StringByteLength(PeekS(*p_data))+2 Wend Input()
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
#Python
Python
from itertools import groupby   def collapser(txt): return ''.join(item for item, grp in groupby(txt))   if __name__ == '__main__': strings = [ "", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman ", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "aardvark", "😍😀🙌💃😍😍😍🙌", ] for txt in strings: this = "Original" print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" ) this = "Collapsed" sqz = collapser(txt) print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nanoquery
Nanoquery
def analyze(s) s = str(s) println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"   if len(s) < 2 println "\tAll characters in the string are the same." return end   for i in range(0, len(s) - 2) if s[i] != s[i + 1] println "\tNot all characters in the string are the same." println "\t'" + s[i + 1] + "' " + format("(0x%x)", ord(s[i + 1])) +\ " is different at position " + str(i + 2) return end end   println "\tAll characters in the string are the same." end   tests = {"", " ", "2", "333", ".55", "tttTTT", "444 444k"} for s in tests analyze(s) end
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the strings are being examined)   a zero─length (empty) string shall be considered as all the same character(s)   process the strings from left─to─right   if       all the same character,   display a message saying such   if not all the same character,   then:   display a message saying such   display what character is different   only the 1st different character need be displayed   display where the different character is in the string   the above messages can be part of a single message   display the hexadecimal value of the different character Use (at least) these seven test values   (strings):   a string of length   0   (an empty string)   a string of length   3   which contains three blanks   a string of length   1   which contains:   2   a string of length   3   which contains:   333   a string of length   3   which contains:   .55   a string of length   6   which contains:   tttTTT   a string of length   9   with a blank in the middle:   4444   444k Show all output here on this page. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import strformat   proc analyze(str: string) = if str.len() > 1: var first = str[0] for i, c in str: if c != first: echo "'", str, "': [len: ", str.len(), "] not all characters are the same. starts to differ at index ", i, ": '", first, "' != '", c, "' [", fmt"{ord(c):#x}", "]" return echo "'", str, "': [len: ", str.len(), "] all characters are the same"   var strings = @["", " ", "2", "333", ".55", "tttTTT", "4444 444k"] for str in strings: analyze(str)
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#Prolog
Prolog
dining_philosophers :- new(D, window('Dining philosophers')), new(S, window('Dining philosophers : statistics')), send(D, size, new(_, size(800,800))),   new(E, ellipse(400,400)), send(E, center, point(400,400)), send(D, display, E),   new(F1, fork(0)), new(F2, fork(1)), new(F3, fork(2)), new(F4, fork(3)), new(F5, fork(4)),   send_list(D, display, [F1,F2,F3,F4,F5]),   new(Waiter, waiter(F1, F2, F3, F4, F5)),   create_plate(P1, 0), create_plate(P2, 1), create_plate(P3, 2), create_plate(P4, 3), create_plate(P5, 4),   create_point(0, Pt1), create_point(1, Pt2), create_point(2, Pt3), create_point(3, Pt4), create_point(4, Pt5),     new(Ph1, philosopher('Aristotle', Waiter, P1, D, S, 0, Pt1, left)), new(Ph2, philosopher('Kant', Waiter, P2, D, S, 1, Pt2, left)), new(Ph3, philosopher('Spinoza', Waiter, P3, D, S, 2, Pt3, right)), new(Ph4, philosopher('Marx', Waiter, P4, D, S, 3, Pt4, right)), new(Ph5, philosopher('Russell', Waiter, P5, D, S, 4, Pt5, left)),   send(Waiter, init_phi, Ph1, Ph2, Ph3, Ph4, Ph5),   send_list([Ph1, Ph2, Ph3, Ph4, Ph5], start),   send(D, done_message, and(message(Waiter, free), message(Ph1, free), message(Ph2, free), message(Ph3, free), message(Ph4, free), message(Ph5, free), message(S, open), message(D, destroy))),   send(D, open).     create_plate(P, N) :- new(P, ellipse(80,80)), X is 400 + 140 * cos(N * pi / 2.5), Y is 400 + 140 * sin(N * pi / 2.5), send(P, center, point(X, Y)).   create_point(N, point(X, Y)) :- X is 400 + 220 * cos(N * pi / 2.5), Y is 400 + 220 * sin(N * pi / 2.5) - 20.     :- pce_begin_class(waiter , object, "gives the forks to the philosophers"). variable(f1, fork, both, "free or used"). variable(f2, fork, both, "free or used"). variable(f3, fork, both, "free or used"). variable(f4, fork, both, "free or used"). variable(f5, fork, both, "free or used"). variable(phi1, philosopher, both, "philosopher"). variable(phi2, philosopher, both, "philosopher"). variable(phi3, philosopher, both, "philosopher"). variable(phi4, philosopher, both, "philosopher"). variable(phi5, philosopher, both, "philosopher").   initialise(P, F1, F2, F3, F4, F5) :-> send(P, slot, f1, F1), send(P, slot, f2, F2), send(P, slot, f3, F3), send(P, slot, f4, F4), send(P, slot, f5, F5).   init_phi(P, Phi1,Phi2, Phi3, Phi4, Phi5) :-> send(P, slot, phi1, Phi1), send(P, slot, phi2, Phi2), send(P, slot, phi3, Phi3), send(P, slot, phi4, Phi4), send(P, slot, phi5, Phi5).     want_forks(P, Phi) :-> ( get(P, slot, phi1, Phi) ,!, check_forks(P, Phi, f5, f1); get(P, slot, phi2, Phi),!, check_forks(P, Phi, f1, f2); get(P, slot, phi3, Phi),!, check_forks(P, Phi, f2, f3); get(P, slot, phi4, Phi),!, check_forks(P, Phi, f3, f4); get(P, slot, phi5, Phi),!, check_forks(P, Phi, f4, f5)).         give_back_forks(P, Phi) :-> ( get(P, slot, phi1, Phi) ,!, release_forks(P, phi1); get(P, slot, phi2, Phi),!, release_forks(P, phi2); get(P, slot, phi3, Phi),!, release_forks(P, phi3); get(P, slot, phi4, Phi),!, release_forks(P, phi4); get(P, slot, phi5, Phi),!, release_forks(P, phi5)),   get(P, slot, phi1, Phi1), check_forks(P, Phi1, f5, f1), get(P, slot, phi2, Phi2), check_forks(P, Phi2, f1, f2), get(P, slot, phi3, Phi3), check_forks(P, Phi3, f2, f3), get(P, slot, phi4, Phi4), check_forks(P, Phi4, f3, f4), get(P, slot, phi5, Phi5), check_forks(P, Phi5, f4, f5).   release_forks(P, phi1) :- get(P, slot, f5, F5), send(F5, free), get(P, slot, f1, F1), send(F1, free).   release_forks(P, phi2) :- get(P, slot, f1, F1), send(F1, free), get(P, slot, f2, F2), send(F2, free).   release_forks(P, phi3) :- get(P, slot, f2, F2), send(F2, free), get(P, slot, f3, F3), send(F3, free).   release_forks(P, phi4) :- get(P, slot, f3, F3), send(F3, free), get(P, slot, f4, F4), send(F4, free).   release_forks(P, phi5) :- get(P, slot, f4, F4), send(F4, free), get(P, slot, f5, F5), send(F5, free).   check_forks(P, Phi, F1, F2) :- get(P, slot, F1, FF1), get(P, slot, F2, FF2), ( (get(Phi, slot, status, waiting), get(FF1, slot, status, free), get(FF2, slot, status, free)) -> send(Phi, receive_forks), send(FF1, used, right), send(FF2, used, left) ; true).   :- pce_end_class.     :- pce_begin_class(philosopher , object, "eat, think or wait !"). variable(name, string, both). variable(window, object, both). variable(status, object, both, "eating/thinking/waiting"). variable(waiter, object, both). variable(plate, object, both). variable(mytimer, timer, both). variable(pos, point, both). variable(side, object, both). variable(old_text, object, both). variable(window_stat, object, both). variable(line_stat, number, both). variable(stat_wait, my_stat, both). variable(stat_eat, my_stat, both). variable(stat_think, my_stat, both).   % méthode appelée lors de la destruction de l'objet % On arrête d'abord le timer pour poursuivre ensuite % sans problème (appel par le timer de ressources libérées) unlink(P) :-> send(P?mytimer, stop),   get(P, status, Sta), stop_timer(P, Sta), get(P, slot, window_stat, WS), get(P, slot, line_stat, LS), get(LS, value, VLS), get(P, slot, name, Name), get(Name, value, V), sformat(A, 'Statistics of philosopher : ~w', [V]), new(Text, text(A)), send(Text, font, font(times, bold, 16)), Y is VLS * 30, send(WS, display, Text, point(30, Y)),   VLS1 is VLS+1, get(P, slot, stat_think, ST), send(ST, statistics, WS, VLS1),   VLS2 is VLS+2, get(P, slot, stat_eat, SE), send(SE, statistics, WS, VLS2),   VLS3 is VLS+3, get(P, slot, stat_wait, SW), send(SW, statistics, WS, VLS3),   send(P, send_super, unlink).   initialise(P, Name, Waiter, Plate, Window, Window_stat, Line_stat, Point, Side) :-> % gtrace, send(P, slot, name, Name), send(P, slot, window, Window), send(P, slot, window_stat, Window_stat), Line is Line_stat * 5, send(P, slot, line_stat, Line), send(P, slot, waiter,Waiter), send(P, slot, plate,Plate), send(P, slot, status, thinking), send(P, slot, pos, Point), send(P, slot, side, Side), send(Window, display, Plate), send(P, slot, old_text, new(_, text(' '))), send(P, display_status), send(P, slot, stat_wait, new(_, my_stat('Waiting'))), send(P, slot, stat_eat, new(_, my_stat('Eating'))), send(P, slot, stat_think, new(_, my_stat('Thinking'))).     stop_timer(P, eating) :- get(P, slot, stat_eat, SE), send(SE, stop).   stop_timer(P, waiting) :- get(P, slot, stat_wait, SW), send(SW, stop).   stop_timer(P, thinking) :- get(P, slot, stat_think, ST), send(ST, stop).     % internal message send by the timer my_message(P) :-> % gtrace, get(P, slot, status, Status), next_status(P, Status).   % philosopher eating ==> thinking next_status(P, eating) :- get(P, slot, waiter, Waiter), get(P, slot, stat_eat, SE), send(SE, stop), get(P, slot, stat_think, ST), send(ST, start), send(Waiter, give_back_forks, P), send(P, slot, status, thinking), send(P, display_status), get(P, plate, Plate), send(Plate, fill_pattern, colour(white)), I is random(20)+ 10, get(P, slot, mytimer, Timer), send(Timer, interval, I), send(Timer, start, once).   next_status(P, thinking) :- get(P, slot, waiter, Waiter), send(P, slot, status, waiting), send(P, display_status), get(P, slot, stat_think, ST), send(ST, stop), get(P, slot, stat_wait, SW), send(SW, start), send(Waiter, want_forks, P).   % send by the waiter % philosopher can eat ! receive_forks(P) :-> get(P, slot, stat_wait, SW), send(SW, stop), get(P, slot, stat_eat, SE), send(SE, start), send(P, slot, status, eating), send(P, display_status), get(P, plate, Plate), send(Plate, fill_pattern, colour(black)), I is random(20)+ 5, get(P, slot, mytimer, Timer), send(Timer, interval, I), send(Timer, start, once).   display_status(P) :-> get(P, old_text, OT), free(OT), get(P, name, Name), get(Name, value, V), get(P, status, Status), choose_color(Status, Colour), sformat(A, '~w ~w', [V, Status]), get(P, window, W), get(P, pos, point(X, Y)), new(Text, text(A)), send(Text, font, font(times, bold, 16)), send(Text, colour, Colour), get(Text, string, Str), get(font(times, bold, 16), width(Str), M), (get(P, side, right) -> X1 is X - M; X1 = X), send(W, display, Text, point(X1, Y)), send(P, old_text, Text).     start(P) :-> I is random(10)+ 2, get(P, slot, stat_think, ST), send(ST, start), send(P, mytimer, new(_, timer(I,message(P, my_message)))), send(P?mytimer, start, once).     choose_color(eating, colour(blue)). choose_color(thinking, colour(green)). choose_color(waiting, colour(red)).   :- pce_end_class.       :- pce_begin_class(disk, ellipse, "disk with color ").   initialise(P, C, R, Col) :-> send(P, send_super, initialise, R, R), send(P, center, C), send(P, pen, 0), send(P, fill_pattern, Col).   change_color(P, Col) :-> send(P, fill_pattern, Col).   :- pce_end_class.   :- pce_begin_class(my_stat , object, "statistics"). variable(name, string, both). variable(nb, number, both). variable(duration, real, both). variable(start, real, both).   initialise(P, Name) :-> send(P, name, Name), send(P, nb, 0), send(P, duration, 0.0).   start(P) :-> get_time(T), send(P, slot, start, T).   stop(P) :-> get_time(Fin),   get(P, slot, nb, N), send(N, plus,1), send(P, slot, nb, N),   get(P, slot, duration, D), get(P, slot, start, Deb),   get(D, value, VD), get(Deb, value, VDeb), X is VD + Fin - VDeb,   send(P, slot, duration, X).   statistics(P, W, L) :-> get(P, nb, N), get(N, value, VN), get(P, duration, D), get(D, value, VD), get(P, name, Name), get(Name, value, V), sformat(A, '~w~tnb :~13| ~t~w~17| duration : ~t~1f~35|', [V, VN, VD]), new(Text, text(A)), send(Text, font, font(screen, roman, 14)), Y is L * 30, send(W, display, Text, point(40, Y)).   :-pce_end_class.   % forks changes of place :- pce_begin_class(fork, line, "to help philosopphers to eat"). variable(value, number, both, "0 => 4"). variable(side, object, both), "left / right". variable(status, object, both, "free / used").   initialise(P, Val) :-> send_super(P, initialise), send(P, slot, value, Val), send(P, slot, status, free), compute(Val, free, _, PS, PE), send(P, start, PS), send(P, end, PE).   free(P) :-> send(P, status, free), send(P, position).     used(P, Side) :-> send(P, status, used), send(P, side, Side), send(P, position).   position(P) :-> get(P, value, V), get(V, value, N), get(P, status, St), get(P, side, Side), compute(N, St, Side, PS, PE), send(P, start, PS), send(P, end, PE).     compute(N, free, _Side, point(XS,YS), point(XE,YE)) :- A is N * pi / 2.5 + pi / 5, XS is 400 + 100 * cos(A), YS is 400 + 100 * sin(A), XE is 400 + 180 * cos(A), YE is 400 + 180 * sin(A).     compute(N, used, left, point(XS,YS), point(XE,YE)) :- A is N * pi / 2.5 + pi / 5 - 2 * pi / 15, XS is 400 + 100 * cos(A), YS is 400 + 100 * sin(A), XE is 400 + 180 * cos(A), YE is 400 + 180 * sin(A).   compute(N, used, right, point(XS,YS), point(XE,YE)) :- A is N * pi / 2.5 + pi / 5 + 2 * pi / 15, XS is 400 + 100 * cos(A), YS is 400 + 100 * sin(A), XE is 400 + 180 * cos(A), YE is 400 + 180 * sin(A).   :- pce_end_class.  
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL   'change this for systems that use a different character $DATESEP = "-"   FUNCTION day(date AS STRING) AS LONG 'date is same format as date$ DIM tmpdash1 AS LONG, tmpdash2 AS LONG tmpdash1 = INSTR(date, $DATESEP) tmpdash2 = INSTR(-1, date, $DATESEP) FUNCTION = VAL(MID$(date, tmpdash1 + 1, tmpdash2 - tmpdash1 - 1)) END FUNCTION   FUNCTION month(date AS STRING) AS LONG 'date is same format as date$ DIM tmpdash AS LONG tmpdash = INSTR(date, $DATESEP) FUNCTION = VAL(LEFT$(date, tmpdash - 1)) END FUNCTION   FUNCTION year(date AS STRING) AS LONG 'date is same format as date$ DIM tmpdash AS LONG tmpdash = INSTR(-1, date, $DATESEP) FUNCTION = VAL(MID$(date, tmpdash + 1)) END FUNCTION   FUNCTION julian(date AS STRING) AS LONG 'date is same format as date$ 'doesn't account for leap years (not needed for ddate) 'days preceding 1st of month ' jan feb mar apr may jun jul aug sep oct nov dec DATA 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 FUNCTION = VAL(READ$(month(date))) + day(date) END FUNCTION   FUNCTION PBMAIN () AS LONG 'Season names DATA "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" 'Weekdays DATA "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle"   DIM dyear AS LONG, dseason AS STRING, dday AS LONG, dweekday AS STRING DIM tmpdate AS STRING, jday AS LONG, result AS STRING   IF LEN(COMMAND$) THEN tmpdate = COMMAND$ ELSE tmpdate = DATE$ END IF dyear = year(tmpdate) + 1166 IF (2 = month(tmpdate)) AND (29 = day(tmpdate)) THEN result = "Saint Tib's Day, " & STR$(dyear) & " YOLD" ELSE jday = julian(tmpdate) dseason = READ$((jday \ 73) + 1) dday = (jday MOD 73) IF 0 = dday THEN dday = 73 dweekday = READ$((jday MOD 5) + 6) result = dweekday & ", " & dseason & " " & TRIM$(STR$(dday)) & ", " & TRIM$(STR$(dyear)) & " YOLD" END IF    ? result END FUNCTION
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#Python
Python
from collections import namedtuple, deque from pprint import pprint as pp     inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost'])   class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] # print(dir(self.edges[0])) self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}   def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost))   #pp(neighbours)   while q: # pp(q) u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: # Relax (u,v,a) dist[v] = alt previous[v] = u #pp(previous) s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s     graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Nanoquery
Nanoquery
def digital_root(n) ap = 0 n = +(int(n)) while n >= 10 sum = 0 for digit in str(n) sum += int(digit) end n = sum ap += 1 end return {ap, n} end   println "here"   if main values = {627615, 39390, 588825, 393900588225, 55} for n in values aproot = digital_root(n) println format("%12d has additive persistence %2d and digital root %d.", n, aproot[0], aproot[1]) end end
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#NetRexx
NetRexx
/* NetRexx ************************************************************ * Test digroot **********************************************************************/ Say 'number -> digital_root persistence' test_digroot(7 ,7, 0) test_digroot(627615 ,9, 2) test_digroot(39390 ,6, 2) test_digroot(588225 ,3, 2) test_digroot(393900588225,9, 2) test_digroot(393900588225,9, 3) /* test error case */   method test_digroot(n,dx,px) static res=digroot(n) Parse res d p If d=dx & p=px Then tag='ok' Else tag='expected:' dx px Say n '->' d p tag   method digroot(n) static /********************************************************************** * Compute the digital root and persistence of the given decimal number * 19.08.2012 Walter Pachl derived from Rexx **************************** Bottom of Data **************************/ p=0 /* persistence */ Loop While n.length()>1 /* more than one digit in n */ s=0 /* initialize sum */ p=p+1 /* increment persistence */ Loop while n<>'' /* as long as there are digits */ Parse n c +1 n /* pick the first one */ s=s+c /* add to the new sum */ End n=s /* the 'new' number */ End return n p /* return root and persistence */
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   sub parse_and_solve ($text) { my %ids; my $expr = (grammar { state $c = 0; rule TOP { <fact>+ { make join ' && ', $<fact>>>.made } }   rule fact { <name> (not)? <position> { make sprintf $<position>.made.fmt($0 ?? "!(%s)" !! "%s"), $<name>.made } } rule position { || on bottom { make "\@f[%s] == 1" } || on top { make "\@f[%s] == +\@f" } || lower than <name> { make "\@f[%s] < \@f[{$<name>.made}]" } || higher than <name> { make "\@f[%s] > \@f[{$<name>.made}]" } || directly below <name> { make "\@f[%s] == \@f[{$<name>.made}] - 1" } || directly above <name> { make "\@f[%s] == \@f[{$<name>.made}] + 1" } || adjacent to <name> { make "\@f[%s] == \@f[{$<name>.made}] + (-1|1)" } || on <ordinal> { make "\@f[%s] == {$<ordinal>.made}" } || { note "Failed to parse line " ~ +$/.prematch.comb(/^^/); exit 1; } }   token name { :i <[a..z]>+ { make %ids{~$/} //= $c++ } } token ordinal { [1st | 2nd | 3rd | \d+th] { make +$/.match(/(\d+)/)[0] } } }).parse($text).made;   EVAL 'for [1..%ids.elems].permutations -> @f { say %ids.kv.map({ "$^a=@f[$^b]" }) if (' ~ $expr ~ '); }' }   parse_and_solve Q:to/END/; Baker not on top Cooper not on bottom Fletcher not on top Fletcher not on bottom Miller higher than Cooper Smith not adjacent to Fletcher Fletcher not adjacent to Cooper END
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
#Klingphix
Klingphix
:sq_mul  %c %i ( ) !c len [  !i $i get rot $i get rot * $c swap 0 put !c ] for $c ;   :sq_sum 0 swap len [ get rot + swap ] for swap ;   ( 1 3 -5 ) ( 4 -2 -1 ) sq_mul sq_sum pstack   " " input
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
#Kotlin
Kotlin
fun dot(v1: Array<Double>, v2: Array<Double>) = v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }   fun main(args: Array<String>) { dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) } }
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#Raku
Raku
map { my $squeeze = $^phrase; sink $^reg; $squeeze ~~ s:g/($reg)$0+/$0/; printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n", $phrase.chars, $phrase, $reg.uniname, $phrase ne $squeeze, $squeeze.chars, $squeeze }, '', ' ', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-', '..1111111111111111111111111111111111111111111111111111111111111117777888', '7', "I never give 'em hell, I just tell the truth, and they think it's hell. ", '.', ' --- Harry S Truman ', ' ', ' --- Harry S Truman ', '-', ' --- Harry S Truman ', 'r'
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead of any character that is immediately repeated. If a character string has a specified   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). A specified   immediately repeated   character is any specified 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:   squeeze.} Examples In the following character string with a specified   immediately repeated   character of   e: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd   e   is an specified repeated character,   indicated by an underscore (above),   even though they (the characters) appear elsewhere in the character string. So, after squeezing the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string,   using a specified immediately repeated character   s: headmistressship The "squeezed" string would be: headmistreship Task Write a subroutine/function/procedure/routine···   to locate a   specified immediately repeated   character and   squeeze   (delete)   them from the character string.   The character string can be processed from either direction. Show all output here, on this page:   the   specified repeated character   (to be searched for and possibly squeezed):   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: immediately string repeated number character ( ↓ a blank, a minus, a seven, a period) ╔╗ 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero) 2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-' 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7' 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.' 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks ╚════════════════════════════════════════════════════════════════════════╝ ↑ │ │ For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: • a blank • a minus • a lowercase r Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for the 5th string. 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
#REXX
REXX
/*REXX program "squeezes" all immediately repeated characters in a string (or strings). */ @.= /*define a default for the @. array. */ #.1= ' '; @.1= #.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ' #.3= '7'; @.3= ..1111111111111111111111111111111111111111111111111111111111111117777888 #.4= . ; @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. " #.5= ' '; @.5= ' --- Harry S Truman ' #.6= '-'; @.6= @.5 #.7= 'r'; @.7= @.5   do j=1; L= length(@.j) /*obtain the length of an array element*/ say copies('═', 105) /*show a separator line between outputs*/ if j>1 & L==0 then leave /*if arg is null and J>1, then leave. */ say ' specified immediate repeatable character=' #.j " ('"c2x(#.j)"'x)" say ' length='right(L, 3) " input=«««" || @.j || '»»»' new= squeeze(@.j, #.j) w= length(new) say ' length='right(w, 3) " output=«««" || new || '»»»' end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ squeeze: procedure; parse arg y 1 $ 2,z /*get string; get immed. repeated char.*/ if pos(z || z, y)==0 then return y /*No repeated immediate char? Return Y*/ /* [↑] Not really needed; a speed─up.*/ do k=2 to length(y) /*traipse through almost all the chars.*/ _= substr(y, k, 1) /*pick a character from Y */ if _==right($, 1) & _==z then iterate /*Same character? Skip it.*/ $= $ || _ /*append char., it's diff. */ end /*j*/ return $
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target. Rule 1: The funnel remains directly above the target. Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position. Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target. Rule 4: The funnel is moved directly over the last place a marble landed. Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule. Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples. Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed. Stretch goal 2: Show scatter plots of all four results. Further information Further explanation and interpretation Video demonstration of the funnel experiment at the Mayo Clinic.
#Sidef
Sidef
func x̄(a) { a.sum / a.len }   func σ(a) { sqrt(x̄(a.map{.**2}) - x̄(a)**2) }   const Δ = (%n< -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047 -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181 -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521 -0.799 0.087 > ~Z+ %n< 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000 0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226 0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104 -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032 >.map{ .i })   const rules = [ { 0 }, {|_,dz| -dz }, {|z,dz| -z - dz }, {|z,dz| z + dz }, ]   for i,v in (rules.kv) { say "Rule #{i+1}:" var target = 0 var z = gather { Δ.each { |d| take(target + d) target = v.run(target, d) } } printf("Mean x, y  : %.4f %.4f\n", x̄(z.map{.re}), x̄(z.map{.im})) printf("Std dev x, y  : %.4f %.4f\n", σ(z.map{.re}), σ(z.map{.im})) }
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and must add up to   12. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. Task Write a computer program which outputs all valid combinations. Possible output   (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#C.2B.2B
C++
  #include <iostream> #include <iomanip>   int main( int argc, char* argv[] ) { int sol = 1; std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n"; for( int f = 1; f < 8; f++ ) { for( int p = 1; p < 8; p++ ) { for( int s = 1; s < 8; s++ ) { if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) { std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 ) << ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p << "\t\t" << std::setw( 6 ) << s << "\n"; } } } } return 0; }
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Logtalk
Logtalk
% define a category for holding the interface % and implementation for delegator objects   :- category(delegator).   :- public(delegate/1). :- public(set_delegate/1).   :- private(delegate_/1). :- dynamic(delegate_/1).   delegate(Delegate) :- ::delegate_(Delegate).   set_delegate(Delegate) :- ::retractall(delegate_(Delegate)), ::assertz(delegate_(Delegate)).   :- end_category.   % define a simpler delegator object, with a % method, operation/1, for testing delegation   :- object(a_delegator, imports(delegator)).   :- public(operation/1).   operation(String) :- ( ::delegate(Delegate), Delegate::current_predicate(thing/1) -> % a delegate is defined that understands the method thing/1 Delegate::thing(String) ; % otherwise just use the default implementation String = 'default implementation' ).   :- end_object.   % define an interface for delegate objects   :- protocol(delegate).   :- public(thing/1).   :- end_protocol.   % define a simple delegate   :- object(a_delegate, implements(delegate)).   thing('delegate implementation').   :- end_object.   % define a simple object that doesn't implement the "delegate" interface   :- object(an_object).   :- end_object.   % test the delegation solution when this file is compiled and loaded   :- initialization(( % without a delegate: a_delegator::operation(String1), String1 == 'default implementation', % with a delegate that does not implement thing/1: a_delegator::set_delegate(an_object), a_delegator::operation(String2), String2 == 'default implementation', % with a delegate that implements thing/1: a_delegator::set_delegate(a_delegate), a_delegator::operation(String3), String3 == 'delegate implementation' )).
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects responsibilities: Delegator: Keep an optional delegate instance. Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation". Delegate: Implement "thing" and return the string "delegate implementation" Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
#Lua
Lua
local function Delegator() return { operation = function(self) if (type(self.delegate)=="table") and (type(self.delegate.thing)=="function") then return self.delegate:thing() else return "default implementation" end end } end   local function Delegate() return { thing = function(self) return "delegate implementation" end } end   local function NonDelegate(which) if (which == 1) then return true -- boolean elseif (which == 2) then return 12345 -- number elseif (which == 3) then return "Hello" -- string elseif (which == 4) then return function() end -- function elseif (which == 5) then return { nothing = function() end } -- table (without "thing") elseif (which == 6) then return coroutine.create(function() end) -- thread elseif (which == 7) then return io.open("delegates.lua","r") -- userdata (if exists, or nil) end end   -- WITH NO (NIL) DELEGATE local d = Delegator() assert(d:operation() == "default implementation")   -- WITH A NON-DELEGATE for i = 1, 7 do d.delegate = NonDelegate(i) assert(d:operation() == "default implementation") end   -- WITH A PROPER DELEGATE d.delegate = Delegate() assert(d:operation() == "delegate implementation")   print("pass")
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)   (0,0),(5,0),(2.5,5)   and   (0,4),(2.5,-1),(5,4)   (0,0),(1,1),(0,2)     and   (2,1),(3,0),(3,2)   (0,0),(1,1),(0,2)     and   (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):   (0,0),(1,0),(0,1)   and   (1,0),(2,0),(1,1)
#Modula-2
Modula-2
MODULE Overlap; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM LongStr IMPORT RealToFixed; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Point = RECORD x,y : LONGREAL; END; Triangle = RECORD p1,p2,p3 : Point; END;   VAR TextWinExSrc : ExceptionSource;   PROCEDURE WritePoint(p : Point); VAR buf : ARRAY[0..31] OF CHAR; BEGIN WriteString("("); RealToFixed(p.x, 2, buf); WriteString(buf); WriteString(", "); RealToFixed(p.y, 2, buf); WriteString(buf); WriteString(")") END WritePoint;   PROCEDURE WriteTriangle(t : Triangle); BEGIN WriteString("Triangle: "); WritePoint(t.p1); WriteString(", "); WritePoint(t.p2); WriteString(", "); WritePoint(t.p3) END WriteTriangle;   PROCEDURE Det2D(p1,p2,p3 : Point) : LONGREAL; BEGIN RETURN p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y) END Det2D;   PROCEDURE CheckTriWinding(VAR p1,p2,p3 : Point; allowReversed : BOOLEAN); VAR detTri : LONGREAL; t : Point; BEGIN detTri := Det2D(p1, p2, p3); IF detTri < 0.0 THEN IF allowReversed THEN t := p3; p3 := p2; p2 := t ELSE RAISE(TextWinExSrc, 0, "triangle has wrong winding direction") END END END CheckTriWinding;   PROCEDURE BoundaryCollideChk(p1,p2,p3 : Point; eps : LONGREAL) : BOOLEAN; BEGIN RETURN Det2D(p1, p2, p3) < eps END BoundaryCollideChk;   PROCEDURE BoundaryDoesntCollideChk(p1,p2,p3 : Point; eps : LONGREAL) : BOOLEAN; BEGIN RETURN Det2D(p1, p2, p3) <= eps END BoundaryDoesntCollideChk;   PROCEDURE TriTri2D(t1,t2 : Triangle; eps : LONGREAL; allowReversed,onBoundary : BOOLEAN) : BOOLEAN; TYPE Points = ARRAY[0..2] OF Point; VAR chkEdge : PROCEDURE(Point, Point, Point, LONGREAL) : BOOLEAN; lp1,lp2 : Points; i,j : CARDINAL; BEGIN (* Triangles must be expressed anti-clockwise *) CheckTriWinding(t1.p1, t1.p2, t1.p3, allowReversed); CheckTriWinding(t2.p1, t2.p2, t2.p3, allowReversed);   (* 'onBoundary' determines whether points on boundary are considered as colliding or not *) IF onBoundary THEN chkEdge := BoundaryCollideChk ELSE chkEdge := BoundaryDoesntCollideChk END;   lp1 := Points{t1.p1, t1.p2, t1.p3}; lp2 := Points{t2.p1, t2.p2, t2.p3};   (* for each edge E of t1 *) FOR i:=0 TO 2 DO j := (i + 1) MOD 3; (* Check all points of t2 lay on the external side of edge E. If they do, the triangles do not overlap. *) IF chkEdge(lp1[i], lp1[j], lp2[0], eps) AND chkEdge(lp1[i], lp1[j], lp2[1], eps) AND chkEdge(lp1[i], lp1[j], lp2[2], eps) THEN RETURN FALSE END END;   (* for each edge E of t2 *) FOR i:=0 TO 2 DO j := (i + 1) MOD 3; (* Check all points of t1 lay on the external side of edge E. If they do, the triangles do not overlap. *) IF chkEdge(lp2[i], lp2[j], lp1[0], eps) AND chkEdge(lp2[i], lp2[j], lp1[1], eps) AND chkEdge(lp2[i], lp2[j], lp1[2], eps) THEN RETURN FALSE END END;   (* The triangles overlap *) RETURN TRUE END TriTri2D;   PROCEDURE CheckOverlap(t1,t2 : Triangle; eps : LONGREAL; allowReversed,onBoundary : BOOLEAN); BEGIN WriteTriangle(t1); WriteString(" and"); WriteLn; WriteTriangle(t2); WriteLn;   IF TriTri2D(t1, t2, eps, allowReversed, onBoundary) THEN WriteString("overlap") ELSE WriteString("do not overlap") END; WriteLn END CheckOverlap;   (* main *) VAR t1,t2 : Triangle; BEGIN t1 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,5.0}}; t2 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,6.0}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{0.0,5.0},{5.0,0.0}}; t2 := Triangle{{0.0,0.0},{0.0,5.0},{5.0,0.0}}; CheckOverlap(t1, t2, 0.0, TRUE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{5.0,0.0},{0.0,5.0}}; t2 := Triangle{{-10.0,0.0},{-5.0,0.0},{-1.0,6.0}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{5.0,0.0},{2.5,5.0}}; t2 := Triangle{{0.0,4.0},{2.5,-1.0},{5.0,4.0}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{1.0,1.0},{0.0,2.0}}; t2 := Triangle{{2.0,1.0},{3.0,0.0},{3.0,2.0}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{1.0,1.0},{0.0,2.0}}; t2 := Triangle{{2.0,1.0},{3.0,-2.0},{3.0,4.0}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{1.0,0.0},{0.0,1.0}}; t2 := Triangle{{1.0,0.0},{2.0,0.0},{1.0,1.1}}; CheckOverlap(t1, t2, 0.0, FALSE, TRUE); WriteLn;   t1 := Triangle{{0.0,0.0},{1.0,0.0},{0.0,1.0}}; t2 := Triangle{{1.0,0.0},{2.0,0.0},{1.0,1.1}}; CheckOverlap(t1, t2, 0.0, FALSE, FALSE); WriteLn;   ReadChar END Overlap.
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Forth
Forth
s" input.txt" delete-file throw s" /input.txt" delete-file throw
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Fortran
Fortran
OPEN (UNIT=5, FILE="input.txt", STATUS="OLD") ! Current directory CLOSE (UNIT=5, STATUS="DELETE") OPEN (UNIT=5, FILE="/input.txt", STATUS="OLD") ! Root directory CLOSE (UNIT=5, STATUS="DELETE")