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/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Python
Python
def _menu(items): for indexitem in enumerate(items): print ("  %2i) %s" % indexitem)   def _ok(reply, itemcount): try: n = int(reply) return 0 <= n < itemcount except: return False   def selector(items, prompt): 'Prompt to select an item from the items' if not items: return '' reply = -1 itemcount = len(items) while not _ok(reply, itemcount): _menu(items) # Use input instead of raw_input for Python 3.x reply = raw_input(prompt).strip() return items[int(reply)]   if __name__ == '__main__': items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] item = selector(items, 'Which is from the three pigs: ') print ("You chose: " + item)
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#BQN
BQN
100 ((↕⊣)(⌈´⊣×⊣¬∘∊⥊∘⊢)(<⊢)(+´×)¨(↕⌊∘÷)) 6‿9‿20
http://rosettacode.org/wiki/Mayan_calendar
Mayan calendar
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregorian calendar. The Calendar Round The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle. The Tzolk’in The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names: Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1 through 13. Every day has both a number and a name that repeat in a 260 day cycle. For example: 1 Imix’ 2 Ik’ 3 Ak’bal ... 11 Chuwen 12 Eb 13 Ben 1 Hix 2 Men 3 K’ib’ ... and so on. The Haab’ The Mayan civil calendar is called the Haab’. This calendar has 365 days per year, and is sometimes called the ‘vague year.’ It is substantially the same as our year, but does not make leap year adjustments, so over long periods of time, gets out of synchronization with the seasons. It consists of 18 months with 20 days each, and the end of the year, a special month of only 5 days, giving a total of 365. The 5 days of the month of Wayeb’ (the last month), are usually considered to be a time of bad luck. Each month in the Haab’ has a name. The Mayan names for the civil months are: Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan Pax K’ayab Kumk’u Wayeb’ (Short, "unlucky" month) The months function very much like ours do. That is, for any given month we count through all the days of that month, and then move on to the next month. Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January is the first day of our year. In 2019, 1 Pop falls on April 2nd. But, because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023. The only really unusual aspect of the Haab’ calendar is that, although there are 20 (or 5) days in each month, the last day of the month is not called the 20th (5th). Instead, the last day of the month is referred to as the ‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In the language of the ancient Maya, the word for seating was chum, So you might have: ... 18 Pop (18th day of the first month) 19 Pop (19th day of the first month) Chum Wo’ (20th day of the first month) 1 Wo’ (1st day of the second month) ... and so on. Dates for any particular day are a combination of the Tzolk’in sacred date, and Haab’ civil date. When put together we get the “Calendar Round.” Calendar Round dates always have two numbers and two names, and they are always written in the same order: (1) the day number in the Tzolk’in (2) the day name in the Tzolk’in (3) the day of the month in the Haab’ (4) the month name in the Haab’ A calendar round is a repeating cycle with a period of just short of 52 Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days) Lords of the Night A third cycle of nine days honored the nine Lords of the Night; nine deities that were associated with each day in turn. The names of the nine deities are lost; they are now commonly referred to as G1 through G9. The Lord of the Night may or may not be included in a Mayan date, if it is, it is typically just the appropriate G(x) at the end. The Long Count Mayans had a separate independent way of measuring time that did not run in cycles. (At least, not on normal human scales.) Instead, much like our yearly calendar, each day just gets a little further from the starting point. For the ancient Maya, the starting point was the ‘creation date’ of the current world. This date corresponds to our date of August 11, 3114 B.C. Dates are calculated by measuring how many days have transpired since this starting date; This is called “The Long Count.” Rather than just an absolute count of days, the long count is broken up into unit blocks, much like our calendar has months, years, decades and centuries. The basic unit is a k’in - one day. A 20 day month is a winal. 18 winal (360 days) is a tun - sometimes referred to as a short year. 20 short years (tun) is a k’atun 20 k’atun is a bak’tun There are longer units too: Piktun == 20 Bak’tun (8,000 short years) Kalabtun == 20 Piktun (160,000 short years) Kinchiltun == 20 Kalabtun (3,200,000 short years) For the most part, the Maya only used the blocks of time up to the bak’tun. One bak’tun is around 394 years, much more than a human life span, so that was all they usually needed to describe dates in this era, or this world. It is worth noting, the two calendars working together allow much more accurate and reliable notation for dates than is available in many other calendar systems; mostly due to the pragmatic choice to make the calendar simply track days, rather than trying to make it align with seasons and/or try to conflate it with the notion of time. Mayan Date correlations There is some controversy over finding a correlation point between the Gregorian and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep the calendar aligned with the seasons so is much more difficult to work with. The most commonly used correlation factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE in the Gregorian calendar, and the final day in the last Mayan long count cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan calendar. There is nothing in known Mayan writing or history that suggests that a long count "cycle" resets every 13 bak’tun. Judging by their other practices, it would make much more sense for it to reset at 20, if at all. The reason there was much interest at all, outside historical scholars, in the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri, Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy theorists to predict a cataclysmic "end-of-the-world" scenario. Excerpts taken from, and recommended reading: From the website of the Foundation for the Advancement of Meso-America Studies, Inc. Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf wikipedia: Maya calendar wikipedia: Mesoamerican Long Count calendar The Task: Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations. Using the GMT correlation, the following Gregorian and Mayan dates are equivalent: Dec 21, 2012 (Gregorian) 4 Ajaw 3 K’ank’in G9 (Calendar round) 13.0.0.0.0 (Long count) Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.) Show the output here, on this page, for at least the following dates: (Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.) 2004-06-19 2012-12-18 2012-12-21 2019-01-19 2019-03-27 2020-02-29 2020-03-01
#Wren
Wren
import "/date" for Date import "/fmt" for Fmt   var sacred = "Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw".split(" ")   var civil = "Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’".split(" ")   var date1 = Date.new(2012, 12, 21) var date2 = Date.new(2019, 4, 2)   var tzolkin = Fn.new { |date| var diff = (date - date1).days var rem = diff % 13 if (rem < 0) rem = 13 + rem var num = (rem <= 9) ? rem + 4 : rem - 9 rem = diff % 20 if (rem <= 0) rem = 20 + rem return [num, sacred[rem-1]] }   var haab = Fn.new { |date| var diff = (date - date2).days var rem = diff % 365 if (rem < 0) rem = 365 + rem var month = civil[((rem+1)/20).floor] var last = (month == "Wayeb'") ? 5 : 20 var d = rem%20 + 1 if (d < last) return [d.toString, month] return ["Chum", month] }   var longCount = Fn.new { |date| var diff = (date - date1).days diff = diff + 13*400*360 var baktun = (diff/(400*360)).floor diff = diff % (400*360) var katun = (diff/(20 * 360)).floor diff = diff % (20*360) var tun = (diff/360).floor diff = diff % 360 var winal = (diff/20).floor var kin = diff % 20 return Fmt.swrite("$d.$d.$d.$d.$d", baktun, katun, tun, winal, kin) }   var lord = Fn.new { |date| var diff = (date - date1).days var rem = diff % 9 if (rem <= 0) rem = 9 + rem return Fmt.swrite("G$d", rem) }   var dates = [ "1961-10-06", "1963-11-21", "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16" ] System.print(" Gregorian Tzolk’in Haab’ Long Lord of") System.print(" Date # Name Day Month Count the Night") System.print("---------- -------- ------------- -------------- ---------") Date.default = Date.isoDate for (dt in dates) { var date = Date.parse(dt) var ns = tzolkin.call(date) var n = ns[0] var s = ns[1] var dm = haab.call(date) var d = dm[0] var m = dm[1] var lc = longCount.call(date) var l = lord.call(date) Fmt.lprint("$s $2d $-8s $4s $-9s $-14s $s", [dt, n, s, d, m, lc, l]) }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Pascal
Pascal
program Midl3dig; {$IFDEF FPC} {$MODE Delphi} //result /integer => Int32 aka longInt etc.. {$ELSE} {$APPTYPE console} // Delphi {$ENDIF} uses sysutils; //IntToStr function GetMid3dig(i:NativeInt):Ansistring; var n,l: NativeInt; Begin setlength(result,0); //n = |i| jumpless abs n := i-((ORD(i>0)-1)AND (2*i)); //calculate digitcount IF n > 0 then l := trunc(ln(n)/ln(10))+1 else l := 1; if l<3 then Begin write('got too few digits'); EXIT; end; If Not(ODD(l)) then Begin write('got even number of digits'); EXIT; end; result:= copy(IntToStr(n),l DIV 2,3); end; const Test : array [0..16] of NativeInt = ( 123,12345,1234567,987654321,10001,-10001, -123,-100,100,-12345,1,2,-1,-10,2002,-2002,0); var i,n : NativeInt; Begin For i := low(Test) to High(Test) do Begin n := Test[i]; writeln(n:9,': ',GetMid3dig(Test[i])); end; end.
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#R
R
showmenu <- function(choices = NULL) { if (is.null(choices)) return("") ans <- menu(choices) if(ans==0) "" else choices[ans]   } str <- showmenu(c("fee fie", "huff and puff", "mirror mirror", "tick tock")) str <- showmenu()  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Racket
Racket
  #lang racket   (define (menu choices) (cond [(null? choices) ""] [else (for ([c choices] [i (in-naturals 1)]) (printf "~a. ~a\n" i c)) (printf "Enter a number: ") (define n (string->number (read-line))) (or (and (exact-integer? n) (<= 1 n (length choices)) (list-ref choices (sub1 n))) (menu choices))]))   (menu '("fee fie" "huff and puff" "mirror mirror" "tick tock"))  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#C
C
#include <stdio.h>   int main() { int max = 0, i = 0, sixes, nines, twenties;   loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; }   for (nines = 0; nines*9 < i; nines++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; }   for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; }   printf("Maximum non-McNuggets number is %d\n", max);   return 0; }
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Ada
Ada
with Ada.Text_IO;   with CryptAda.Digests.Message_Digests.MD4; with CryptAda.Digests.Hashes; with CryptAda.Pragmatics; with CryptAda.Utils.Format;   procedure RC_MD4 is use CryptAda.Digests.Message_Digests; use CryptAda.Digests; use CryptAda.Pragmatics;   function To_Byte_Array (Item : String) return Byte_Array is Result : Byte_Array (Item'Range); begin for I in Result'Range loop Result (I) := Byte (Character'Pos (Item (I))); end loop; return Result; end To_Byte_Array;   Text  : constant String  := "Rosetta Code"; Bytes  : constant Byte_Array  := To_Byte_Array (Text); Handle  : constant Message_Digest_Handle := MD4.Get_Message_Digest_Handle; Pointer : constant Message_Digest_Ptr  := Get_Message_Digest_Ptr (Handle); Hash  : Hashes.Hash; begin Digest_Start (Pointer); Digest_Update (Pointer, Bytes); Digest_End (Pointer, Hash);   Ada.Text_IO.Put_Line ("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash))); end RC_MD4;
http://rosettacode.org/wiki/Mayan_calendar
Mayan calendar
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregorian calendar. The Calendar Round The Calendar Round has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle. The Tzolk’in The sacred cycle in the Mayan calendar round was called the Tzolk’in. The Tzolk'in has a cycle of 20 day names: Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw Intermeshed with the named days, the Tzolk’in has a cycle of 13 numbered days; 1 through 13. Every day has both a number and a name that repeat in a 260 day cycle. For example: 1 Imix’ 2 Ik’ 3 Ak’bal ... 11 Chuwen 12 Eb 13 Ben 1 Hix 2 Men 3 K’ib’ ... and so on. The Haab’ The Mayan civil calendar is called the Haab’. This calendar has 365 days per year, and is sometimes called the ‘vague year.’ It is substantially the same as our year, but does not make leap year adjustments, so over long periods of time, gets out of synchronization with the seasons. It consists of 18 months with 20 days each, and the end of the year, a special month of only 5 days, giving a total of 365. The 5 days of the month of Wayeb’ (the last month), are usually considered to be a time of bad luck. Each month in the Haab’ has a name. The Mayan names for the civil months are: Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan Pax K’ayab Kumk’u Wayeb’ (Short, "unlucky" month) The months function very much like ours do. That is, for any given month we count through all the days of that month, and then move on to the next month. Normally, the day 1 Pop is considered the first day of the civil year, just as 1 January is the first day of our year. In 2019, 1 Pop falls on April 2nd. But, because of the leap year in 2020, 1 Pop falls on April 1st in the years 2020-2023. The only really unusual aspect of the Haab’ calendar is that, although there are 20 (or 5) days in each month, the last day of the month is not called the 20th (5th). Instead, the last day of the month is referred to as the ‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In the language of the ancient Maya, the word for seating was chum, So you might have: ... 18 Pop (18th day of the first month) 19 Pop (19th day of the first month) Chum Wo’ (20th day of the first month) 1 Wo’ (1st day of the second month) ... and so on. Dates for any particular day are a combination of the Tzolk’in sacred date, and Haab’ civil date. When put together we get the “Calendar Round.” Calendar Round dates always have two numbers and two names, and they are always written in the same order: (1) the day number in the Tzolk’in (2) the day name in the Tzolk’in (3) the day of the month in the Haab’ (4) the month name in the Haab’ A calendar round is a repeating cycle with a period of just short of 52 Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days) Lords of the Night A third cycle of nine days honored the nine Lords of the Night; nine deities that were associated with each day in turn. The names of the nine deities are lost; they are now commonly referred to as G1 through G9. The Lord of the Night may or may not be included in a Mayan date, if it is, it is typically just the appropriate G(x) at the end. The Long Count Mayans had a separate independent way of measuring time that did not run in cycles. (At least, not on normal human scales.) Instead, much like our yearly calendar, each day just gets a little further from the starting point. For the ancient Maya, the starting point was the ‘creation date’ of the current world. This date corresponds to our date of August 11, 3114 B.C. Dates are calculated by measuring how many days have transpired since this starting date; This is called “The Long Count.” Rather than just an absolute count of days, the long count is broken up into unit blocks, much like our calendar has months, years, decades and centuries. The basic unit is a k’in - one day. A 20 day month is a winal. 18 winal (360 days) is a tun - sometimes referred to as a short year. 20 short years (tun) is a k’atun 20 k’atun is a bak’tun There are longer units too: Piktun == 20 Bak’tun (8,000 short years) Kalabtun == 20 Piktun (160,000 short years) Kinchiltun == 20 Kalabtun (3,200,000 short years) For the most part, the Maya only used the blocks of time up to the bak’tun. One bak’tun is around 394 years, much more than a human life span, so that was all they usually needed to describe dates in this era, or this world. It is worth noting, the two calendars working together allow much more accurate and reliable notation for dates than is available in many other calendar systems; mostly due to the pragmatic choice to make the calendar simply track days, rather than trying to make it align with seasons and/or try to conflate it with the notion of time. Mayan Date correlations There is some controversy over finding a correlation point between the Gregorian and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep the calendar aligned with the seasons so is much more difficult to work with. The most commonly used correlation factor is The GMT: 584283. Julian 584283 is a day count corresponding Mon, Aug 11, 3114 BCE in the Gregorian calendar, and the final day in the last Mayan long count cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan calendar. There is nothing in known Mayan writing or history that suggests that a long count "cycle" resets every 13 bak’tun. Judging by their other practices, it would make much more sense for it to reset at 20, if at all. The reason there was much interest at all, outside historical scholars, in the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri, Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy theorists to predict a cataclysmic "end-of-the-world" scenario. Excerpts taken from, and recommended reading: From the website of the Foundation for the Advancement of Meso-America Studies, Inc. Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf wikipedia: Maya calendar wikipedia: Mesoamerican Long Count calendar The Task: Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. If desired, support other correlations. Using the GMT correlation, the following Gregorian and Mayan dates are equivalent: Dec 21, 2012 (Gregorian) 4 Ajaw 3 K’ank’in G9 (Calendar round) 13.0.0.0.0 (Long count) Support looking up dates for at least 50 years before and after the Mayan Long Count 13 bak’tun rollover: Dec 21, 2012. (Will require taking into account Gregorian leap days.) Show the output here, on this page, for at least the following dates: (Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.) 2004-06-19 2012-12-18 2012-12-21 2019-01-19 2019-03-27 2020-02-29 2020-03-01
#zkl
zkl
var [const] sacred=T("Imix'","Ik'","Ak'bal","K'an","Chikchan","Kimi","Manik'","Lamat","Muluk","Ok", "Chuwen","Eb","Ben","Hix","Men","K'ib'","Kaban","Etz'nab'","Kawak","Ajaw"), civil=T("Pop","Wo'","Sip","Sotz'","Sek","Xul","Yaxk'in","Mol","Ch'en","Yax","Sak'","Keh", "Mak","K'ank'in","Muwan'","Pax","K'ayab","Kumk'u","Wayeb'"), Date=Time.Date, // correlation dates: Creation=T(2012, Date.December, 21), // 13.0.0.0.0, Mayan day of creation OnePop=T(2019, Date.April, 2), // 1 Pop in 2019 ;   fcn haab(date){ // (y,m,d)-->("Chum"|Int,month name) diff:=Date.deltaDays(OnePop,date.xplode()); //--> signed int rem:=diff%365; if(rem<0) rem=365 + rem; month,last := civil[(rem+1)/20], 20; if(month==civil[-1]) last=5; d:=rem%20 + 1; if(d<last) return(d, month); return("Chum",month); }   fcn tzolkin(date){ // (y,m,d)-->(Int,String) diff:=Date.deltaDays(Creation,date.xplode()); //--> signed int rem:=diff % 13; if(rem<0) rem=13 + rem;   num:=( if(rem<=9) rem + 4 else rem - 9 ); rem=diff % 20; if(rem<=0) rem=20 + rem; return(num, sacred[rem-1]); }   fcn longCount(date){ // (y,m,d) --> (5 Ints) diff:=Date.deltaDays(Creation,date.xplode()); //--> signed int diff,baktun  := diff + 13*400*360, diff/(400*360); diff,katun  := diff % (400*360), diff/(20*360); diff,tun  := diff % (20*360), diff/360; diff,winal,kin := diff%360, diff/20, diff % 20;   return(baktun, katun, tun, winal, kin) }   fcn lord(date){ // (y,m,d) --> String diff:=Date.deltaDays(Creation,date.xplode()); //--> signed int rem:=diff % 9; if(rem<=0) rem=9 + rem; "G%d".fmt(rem) }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ;   sub middlethree { my $number = shift ; my $testnumber = abs $number ; my $error = "Middle 3 digits can't be shown" ; my $numberlength = length $testnumber ; if ( $numberlength < 3 ) { print "$error : $number too short!\n" ; return ; } if ( $numberlength % 2 == 0 ) { print "$error : even number of digits in $number!\n" ; return ; } my $middle = int ( $numberlength / 2 ) ; print "Middle 3 digits of $number : " . substr( $testnumber , $middle - 1 , 3 ) . " !\n" ; return ; }   my @numbers = ( 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 , 1, 2, -1, -10, 2002, -2002, 0 ) ; map { middlethree( $_ ) } @numbers ;  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Raku
Raku
sub menu ( $prompt, @items ) { return '' unless @items.elems; repeat until my $selection ~~ /^ \d+ $/ && @items[--$selection] { my $i = 1; say " {$i++}) $_" for @items; $selection = prompt $prompt; } return @items[$selection]; }   my @choices = 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock'; my $prompt = 'Enter the number corresponding to your selection: ';   my $answer = menu( $prompt, [] ); say "You chose: $answer" if $answer.chars;   $answer = menu( $prompt, @choices ); say "You chose: $answer" if $answer.chars;
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#C.23
C#
  using System;   public class McNuggets { public static void Main() { bool[] isMcNuggetNumber = new bool[101];   for (int x = 0; x <= 100/6; x++) { for (int y = 0; y <= 100/9; y++) { for (int z = 0; z <= 100/20; z++) { int mcNuggetNumber = x*6 + y*9 + z*20; if (mcNuggetNumber <= 100) { isMcNuggetNumber[mcNuggetNumber] = true; } } } }   for (int mnnCheck = isMcNuggetNumber.Length-1; mnnCheck >= 0; mnnCheck--) { if (!isMcNuggetNumber[mnnCheck]) { Console.WriteLine("Largest non-McNuggett Number less than 100: " + mnnCheck.ToString()); break; } } } }  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#AutoHotkey
AutoHotkey
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nMD4:`n" MD4(str)       ; MD4 =============================================================================== MD4(string, encoding = "utf-8") { return CalcStringHash(string, 0x8002, encoding) }   ; CalcAddrHash ====================================================================== CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o }   ; CalcStringHash ==================================================================== CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Phix
Phix
procedure mid3(integer i) string s = sprintf("%d",abs(i)) integer k = length(s)-3 printf(1,"%10d: %s\n",{i,iff(k<0 or and_bits(k,1)?"error":s[k/2+1..k/2+3])}) end procedure constant tests = {123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345, 1,2,-1,-10,2002,-2002,0} for i=1 to length(tests) do mid3(tests[i]) end for
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#REBOL
REBOL
rebol [ Title: "Text Menu" URL: http://rosettacode.org/wiki/Select ]   choices: ["fee fie" "huff and puff" "mirror mirror" "tick tock"] choice: ""   valid?: func [ choices [block! list! series!] choice ][ if error? try [choice: to-integer choice] [return false] all [0 < choice choice <= length? choices] ]   while [not valid? choices choice][ repeat i length? choices [print [" " i ":" choices/:i]] choice: ask "Which is from the three pigs? " ] print ["You chose:" pick choices to-integer choice]
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Clojure
Clojure
(defn cart [colls] (if (empty? colls) '(()) (for [more (cart (rest colls)) x (first colls)] (cons x more))))   (defn nuggets [[n6 n9 n20]] (+ (* 6 n6) (* 9 n9) (* 20 n20)))   (let [possible (distinct (map nuggets (cart (map range [18 13 6])))) mcmax (apply max (filter (fn [x] (not-any? #{x} possible)) (range 101)))] (printf "Maximum non-McNuggets number is %d\n" mcmax))
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#C
C
  /* * * Author: George Mossessian * * The MD4 hash algorithm, as described in https://tools.ietf.org/html/rfc1320 */     #include <stdlib.h> #include <string.h> #include <stdint.h>   char *MD4(char *str, int len); //this is the prototype you want to call. Everything else is internal.   typedef struct string{ char *c; int len; char sign; }string;   static uint32_t *MD4Digest(uint32_t *w, int len); static void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD); static uint32_t changeEndianness(uint32_t x); static void resetMD4Registers(void); static string stringCat(string first, string second); static string uint32ToString(uint32_t l); static uint32_t stringToUint32(string s);   static const char *BASE16 = "0123456789abcdef=";   #define F(X,Y,Z) (((X)&(Y))|((~(X))&(Z))) #define G(X,Y,Z) (((X)&(Y))|((X)&(Z))|((Y)&(Z))) #define H(X,Y,Z) ((X)^(Y)^(Z))   #define LEFTROTATE(A,N) ((A)<<(N))|((A)>>(32-(N)))   #define MD4ROUND1(a,b,c,d,x,s) a += F(b,c,d) + x; a = LEFTROTATE(a, s); #define MD4ROUND2(a,b,c,d,x,s) a += G(b,c,d) + x + (uint32_t)0x5A827999; a = LEFTROTATE(a, s); #define MD4ROUND3(a,b,c,d,x,s) a += H(b,c,d) + x + (uint32_t)0x6ED9EBA1; a = LEFTROTATE(a, s);   static uint32_t A = 0x67452301; static uint32_t B = 0xefcdab89; static uint32_t C = 0x98badcfe; static uint32_t D = 0x10325476;   string newString(char * c, int t){ string r; int i; if(c!=NULL){ r.len = (t<=0)?strlen(c):t; r.c=(char *)malloc(sizeof(char)*(r.len+1)); for(i=0; i<r.len; i++) r.c[i]=c[i]; r.c[r.len]='\0'; return r; } r.len=t; r.c=(char *)malloc(sizeof(char)*(r.len+1)); memset(r.c,(char)0,sizeof(char)*(t+1)); r.sign = 1; return r; }   string stringCat(string first, string second){ string str=newString(NULL, first.len+second.len); int i;   for(i=0; i<first.len; i++){ str.c[i]=first.c[i]; } for(i=first.len; i<str.len; i++){ str.c[i]=second.c[i-first.len]; } return str; }   string base16Encode(string in){ string out=newString(NULL, in.len*2); int i,j;   j=0; for(i=0; i<in.len; i++){ out.c[j++]=BASE16[((in.c[i] & 0xF0)>>4)]; out.c[j++]=BASE16[(in.c[i] & 0x0F)]; } out.c[j]='\0'; return out; }     string uint32ToString(uint32_t l){ string s = newString(NULL,4); int i; for(i=0; i<4; i++){ s.c[i] = (l >> (8*(3-i))) & 0xFF; } return s; }   uint32_t stringToUint32(string s){ uint32_t l; int i; l=0; for(i=0; i<4; i++){ l = l|(((uint32_t)((unsigned char)s.c[i]))<<(8*(3-i))); } return l; }   char *MD4(char *str, int len){ string m=newString(str, len); string digest; uint32_t *w; uint32_t *hash; uint64_t mlen=m.len; unsigned char oneBit = 0x80; int i, wlen;     m=stringCat(m, newString((char *)&oneBit,1));   //append 0 ≤ k < 512 bits '0', such that the resulting message length in bits // is congruent to −64 ≡ 448 (mod 512)4 i=((56-m.len)%64); if(i<0) i+=64; m=stringCat(m,newString(NULL, i));   w = malloc(sizeof(uint32_t)*(m.len/4+2));   //append length, in bits (hence <<3), least significant word first for(i=0; i<m.len/4; i++){ w[i]=stringToUint32(newString(&(m.c[4*i]), 4)); } w[i++] = (mlen<<3) & 0xFFFFFFFF; w[i++] = (mlen>>29) & 0xFFFFFFFF;   wlen=i;     //change endianness, but not for the appended message length, for some reason? for(i=0; i<wlen-2; i++){ w[i]=changeEndianness(w[i]); }   hash = MD4Digest(w,wlen);   digest=newString(NULL,0); for(i=0; i<4; i++){ hash[i]=changeEndianness(hash[i]); digest=stringCat(digest,uint32ToString(hash[i])); }   return base16Encode(digest).c; }   uint32_t *MD4Digest(uint32_t *w, int len){ //assumes message.len is a multiple of 64 bytes. int i,j; uint32_t X[16]; uint32_t *digest = malloc(sizeof(uint32_t)*4); uint32_t AA, BB, CC, DD;   for(i=0; i<len/16; i++){ for(j=0; j<16; j++){ X[j]=w[i*16+j]; }   AA=A; BB=B; CC=C; DD=D;   MD4ROUND1(A,B,C,D,X[0],3); MD4ROUND1(D,A,B,C,X[1],7); MD4ROUND1(C,D,A,B,X[2],11); MD4ROUND1(B,C,D,A,X[3],19); MD4ROUND1(A,B,C,D,X[4],3); MD4ROUND1(D,A,B,C,X[5],7); MD4ROUND1(C,D,A,B,X[6],11); MD4ROUND1(B,C,D,A,X[7],19); MD4ROUND1(A,B,C,D,X[8],3); MD4ROUND1(D,A,B,C,X[9],7); MD4ROUND1(C,D,A,B,X[10],11); MD4ROUND1(B,C,D,A,X[11],19); MD4ROUND1(A,B,C,D,X[12],3); MD4ROUND1(D,A,B,C,X[13],7); MD4ROUND1(C,D,A,B,X[14],11); MD4ROUND1(B,C,D,A,X[15],19);   MD4ROUND2(A,B,C,D,X[0],3); MD4ROUND2(D,A,B,C,X[4],5); MD4ROUND2(C,D,A,B,X[8],9); MD4ROUND2(B,C,D,A,X[12],13); MD4ROUND2(A,B,C,D,X[1],3); MD4ROUND2(D,A,B,C,X[5],5); MD4ROUND2(C,D,A,B,X[9],9); MD4ROUND2(B,C,D,A,X[13],13); MD4ROUND2(A,B,C,D,X[2],3); MD4ROUND2(D,A,B,C,X[6],5); MD4ROUND2(C,D,A,B,X[10],9); MD4ROUND2(B,C,D,A,X[14],13); MD4ROUND2(A,B,C,D,X[3],3); MD4ROUND2(D,A,B,C,X[7],5); MD4ROUND2(C,D,A,B,X[11],9); MD4ROUND2(B,C,D,A,X[15],13);   MD4ROUND3(A,B,C,D,X[0],3); MD4ROUND3(D,A,B,C,X[8],9); MD4ROUND3(C,D,A,B,X[4],11); MD4ROUND3(B,C,D,A,X[12],15); MD4ROUND3(A,B,C,D,X[2],3); MD4ROUND3(D,A,B,C,X[10],9); MD4ROUND3(C,D,A,B,X[6],11); MD4ROUND3(B,C,D,A,X[14],15); MD4ROUND3(A,B,C,D,X[1],3); MD4ROUND3(D,A,B,C,X[9],9); MD4ROUND3(C,D,A,B,X[5],11); MD4ROUND3(B,C,D,A,X[13],15); MD4ROUND3(A,B,C,D,X[3],3); MD4ROUND3(D,A,B,C,X[11],9); MD4ROUND3(C,D,A,B,X[7],11); MD4ROUND3(B,C,D,A,X[15],15);   A+=AA; B+=BB; C+=CC; D+=DD; }   digest[0]=A; digest[1]=B; digest[2]=C; digest[3]=D; resetMD4Registers(); return digest; }   uint32_t changeEndianness(uint32_t x){ return ((x & 0xFF) << 24) | ((x & 0xFF00) << 8) | ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24); }   void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD){ A=AA; B=BB; C=CC; D=DD; }   void resetMD4Registers(void){ setMD4Registers(0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476); }  
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#PHP
PHP
// 32-bit builds of PHP: Integers can be from -2147483648 to 2147483647 // 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807   function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int);   if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } }   $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);   foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Red
Red
Red ["text menu"]   menu: function [items][ print either empty? items [""] [until [ repeat n length? items [print [n ":" items/:n]] attempt [pick items to-integer ask "Your choice: "] ]] ]
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#CLU
CLU
% Recursive nugget iterator. % This yields all the nugget numbers of the given box sizes from start to max. gen_nuggets = iter (start, max: int, sizes: sequence[int]) yields (int) si = sequence[int] if si$empty(sizes) then yield(start) else for i: int in int$from_to_by(start, max, si$bottom(sizes)) do for j: int in gen_nuggets(i, max, si$reml(sizes)) do yield(j) end end end end gen_nuggets   start_up = proc () max = 100 ab = array[bool] po: stream := stream$primary_output() nuggets: ab := ab$fill(0,max+1,false)   for nugget: int in gen_nuggets(0, max, sequence[int]$[6,9,20]) do nuggets[nugget] := true end   maxn: int for i: int in ab$indexes(nuggets) do if ~nuggets[i] then maxn := i end end   stream$putl(po, "Maximum non-McNuggets number: " || int$unparse(maxn)) end start_up
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MCNUGGETS.   DATA DIVISION. WORKING-STORAGE SECTION. 01 NUGGETS. 03 NUGGET-FLAGS PIC X OCCURS 100 TIMES. 88 IS-NUGGET VALUE 'X'.   01 A PIC 999. 01 B PIC 999. 01 C PIC 999.   PROCEDURE DIVISION. BEGIN. MOVE SPACES TO NUGGETS. PERFORM A-LOOP VARYING A FROM 0 BY 6 UNTIL A IS GREATER THAN 100. MOVE 100 TO A.   FIND-LARGEST. IF IS-NUGGET(A), SUBTRACT 1 FROM A, GO TO FIND-LARGEST. DISPLAY 'Largest non-McNugget number: ', A. STOP RUN.   A-LOOP. PERFORM B-LOOP VARYING B FROM A BY 9 UNTIL B IS GREATER THAN 100.   B-LOOP. PERFORM C-LOOP VARYING C FROM B BY 20 UNTIL C IS GREATER THAN 100.   C-LOOP. IF C IS NOT EQUAL TO ZERO, MOVE 'X' TO NUGGET-FLAGS(C).
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Md4 { public static string Md4Hash(this string input) { // get padded uints from bytes List<byte> bytes = Encoding.ASCII.GetBytes(input).ToList(); uint bitCount = (uint)(bytes.Count) * 8; bytes.Add(128); while (bytes.Count % 64 != 56) bytes.Add(0); var uints = new List<uint>(); for (int i = 0; i + 3 < bytes.Count; i += 4) uints.Add(bytes[i] | (uint)bytes[i + 1] << 8 | (uint)bytes[i + 2] << 16 | (uint)bytes[i + 3] << 24); uints.Add(bitCount); uints.Add(0);   // run rounds uint a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476; Func<uint, uint, uint> rol = (x, y) => x << (int)y | x >> 32 - (int)y; for (int q = 0; q + 15 < uints.Count; q += 16) { var chunk = uints.GetRange(q, 16); uint aa = a, bb = b, cc = c, dd = d; Action<Func<uint, uint, uint, uint>, uint[]> round = (f, y) => { foreach (uint i in new[] { y[0], y[1], y[2], y[3] }) { a = rol(a + f(b, c, d) + chunk[(int)(i + y[4])] + y[12], y[8]); d = rol(d + f(a, b, c) + chunk[(int)(i + y[5])] + y[12], y[9]); c = rol(c + f(d, a, b) + chunk[(int)(i + y[6])] + y[12], y[10]); b = rol(b + f(c, d, a) + chunk[(int)(i + y[7])] + y[12], y[11]); } }; round((x, y, z) => (x & y) | (~x & z), new uint[] { 0, 4, 8, 12, 0, 1, 2, 3, 3, 7, 11, 19, 0 }); round((x, y, z) => (x & y) | (x & z) | (y & z), new uint[] { 0, 1, 2, 3, 0, 4, 8, 12, 3, 5, 9, 13, 0x5a827999 }); round((x, y, z) => x ^ y ^ z, new uint[] { 0, 2, 1, 3, 0, 8, 4, 12, 3, 9, 11, 15, 0x6ed9eba1 }); a += aa; b += bb; c += cc; d += dd; }   // return hex encoded string byte[] outBytes = new[] { a, b, c, d }.SelectMany(BitConverter.GetBytes).ToArray(); return BitConverter.ToString(outBytes).Replace("-", "").ToLower(); } static void Main() { Console.WriteLine("Rosetta Code".Md4Hash()); } }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Picat
Picat
get_middle_f1(Str) = [X,Y,Z] => append(Pre,[X,Y,Z],Post,Str), length(Pre) = length(Post).
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#REXX
REXX
/*REXX program displays a list, then prompts the user for a selection number (integer).*/ do forever /*keep prompting until response is OK. */ call list_create /*create the list from scratch. */ call list_show /*display (show) the list to the user.*/ if #==0 then return '' /*if list is empty, then return null.*/ say right(' choose an item by entering a number from 1 ───►' #, 70, '═') parse pull x /*get the user's choice (if any). */   select when x='' then call sayErr "a choice wasn't entered" when words(x)\==1 then call sayErr 'too many choices entered:' when \datatype(x,'N') then call sayErr "the choice isn't numeric:" when \datatype(x,'W') then call sayErr "the choice isn't an integer:" when x<1 | x># then call sayErr "the choice isn't within range:" otherwise leave /*this leaves the DO FOREVER loop.*/ end /*select*/ end /*forever*/ /*user might've entered 2. or 003 */ x=x/1 /*normalize the number (maybe). */ say; say 'you chose item' x": " #.x return #.x /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ list_create: #.1= 'fee fie' /*this is one method for list-building.*/ #.2= 'huff and puff' #.3= 'mirror mirror' #.4= 'tick tock' #=4 /*store the number of choices in # */ return /*(above) is just one convention. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ list_show: say /*display a blank line. */ do j=1 for # /*display the list of choices. */ say '[item' j"] " #.j /*display item number with its choice. */ end /*j*/ say /*display another blank line. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ sayErr: say; say '***error***' arg(1) x; say; return
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Comal
Comal
0010 limit#:=100 0020 DIM nugget#(0:limit#) 0030 FOR a#:=0 TO limit# STEP 6 DO 0040 FOR b#:=a# TO limit# STEP 9 DO 0050 FOR c#:=b# TO limit# STEP 20 DO nugget#(c#):=TRUE 0060 ENDFOR b# 0070 ENDFOR a# 0080 FOR i#:=limit# TO 0 STEP -1 DO 0090 IF NOT nugget#(i#) THEN 0100 PRINT "Maximum non-McNuggets number: ",i# 0110 END 0120 ENDIF 0130 ENDFOR i#
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#11l
11l
F solve(&tri) L tri.len > 1 V t0 = tri.pop() V t1 = tri.pop() tri.append(enumerate(t1).map((i, t) -> max(@t0[i], @t0[i + 1]) + t)) R tri[0][0]   V data = ‘ 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93’   print(solve(&data.split("\n").map(row -> row.split(‘ ’, group_delimiters' 1B).map(Int))))
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Clojure
Clojure
(use 'pandect.core) (md4 "Rosetta Code")
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#PicoLisp
PicoLisp
(de middle3digits (N) (let (Lst (chop (abs N)) Len (length Lst)) (tab (10 -2 -30) N ":" (cond ((> 3 Len) "not enough digits") ((bit? 1 Len) (head 3 (nth Lst (/ Len 2))) ) (T "even number of digits") ) ) ) )
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Ring
Ring
  aList = ["fee fie", "huff and puff", "mirror mirror", "tick tock"] selected = menu(aList, "please make a selection: ") see "" + selected + nl   func menu aList, prompt ndex = 1 while index>0 and index<=len(aList) for index = 1 to len(aList) if aList[index]!="" see "" + index + " : " + aList[index] + " " ok next see nl see prompt give select index = number(select) see "" + aList[index] + nl if select!=string(index) index = -1 ok if index>=0 if index<=len(aList) if aList[index]="" index = -1 ok ok ok end return aList[index]  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Cowgol
Cowgol
include "cowgol.coh"; const LIMIT := 100;   var flags: uint8[LIMIT+1]; MemZero(&flags[0], @bytesof flags);   var a: @indexof flags; var b: @indexof flags; var c: @indexof flags;   a := 0; while a <= LIMIT loop b := a; while b <= LIMIT loop c := b; while c <= LIMIT loop flags[c] := 1; c := c + 20; end loop; b := b + 9; end loop; a := a + 6; end loop;   a := LIMIT; loop if flags[a] == 0 then print("Maximum non-McNuggets number: "); print_i32(a as uint32); print_nl(); break; end if; a := a - 1; end loop;
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Action.21
Action!
INT FUNC Max(INT a,b) IF a>b THEN RETURN (a) FI RETURN (b)   PROC Main() DEFINE ROWCOUNT="18" INT i,row,len,a,b INT ARRAY rows(ROWCOUNT) INT ARRAY data=[ 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93]   row=0 len=1 FOR i=0 TO ROWCOUNT-1 DO rows(i)=row row==+len len==+1 OD   row=ROWCOUNT-2 WHILE row>=0 DO len=row+1 FOR i=0 TO len-1 DO a=data(rows(row+1)+i) b=data(rows(row+1)+i+1) data(rows(row)+i)==+Max(a,b) OD row==-1 OD   PrintI(data(0)) RETURN
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Common_Lisp
Common Lisp
(ql:quickload 'ironclad) (defun md4 (str) (ironclad:byte-array-to-hex-string (ironclad:digest-sequence :md4 (ironclad:ascii-string-to-byte-array str))))   (md4 "Rosetta Code")
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Pike
Pike
string middlethree(int i) { i = abs(i); int length = sizeof((string)i);   if(length >= 3) { if(length % 2 == 1) { int middle = (int)floor(length / 2) - 1; return(((string)i)[middle..middle+2]); } else { return "The value must contain an odd amount of digits..."; } } else { return "The value must contain at least three digits..."; } }   int main() { array(int) numbers = ({123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0});   foreach(numbers, int nums) { write((string)nums + " : " + middlethree(nums) + "\n"); } return 0; }
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#8th
8th
  "md5" cr:hash! "Some text" cr:hash cr:hash>s . cr bye  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Ruby
Ruby
  def select(prompt, items = []) if items.empty? '' else answer = -1 until (0...items.length).cover?(answer) items.each_with_index {|i,j| puts "#{j}. #{i}"} print "#{prompt}: " begin answer = Integer(gets) rescue ArgumentError redo end end items[answer] end end   # test empty list response = select('Which is empty') puts "empty list returns: >#{response}<\n"   # "real" test items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] response = select('Which is from the three pigs', items) puts "you chose: >#{response}<"  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Dart
Dart
import 'dart:math'; main() { var nuggets = List<int>.generate(101, (int index) => index); for (int small in List<int>.generate((100 ~/ (6 + 1)), (int index) => index)) { for (int medium in List<int>.generate((100 ~/ (9 + 1)), (int index) => index)) { for (int large in List<int>.generate((100 ~/ (20 + 1)), (int index) => index)) { nuggets.removeWhere((element) => element == 6 * small + 9 * medium + 20 * large); } } } print('Largest non-McNuggets number: ${nuggets.reduce(max).toString() ?? 'none'}.'); }
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Draco
Draco
proc nonrec main() void: byte LIMIT = 100; [LIMIT+1] bool nugget; byte a, b, c;   for a from 0 upto LIMIT do nugget[a] := false od;   for a from 0 by 6 upto LIMIT do for b from a by 9 upto LIMIT do for c from b by 20 upto LIMIT do nugget[c] := true od od od;   a := LIMIT; while nugget[a] do a := a - 1 od; writeln("Maximum non-McNuggets number: ", a) corp
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#11l
11l
F dijkstra(graph, source) V n = graph.len V dist = [Float.infinity] * n V previous = [-1] * n dist[source] = 0 V Q = Array(0 .< n) L !Q.empty V u = min(Q, key' n -> @dist[n]) Q.remove(u) I dist[u] == Float.infinity L.break L(v) 0 .< n I graph[u][v] & (v C Q) V alt = dist[u] + graph[u][v] I alt < dist[v] dist[v] = alt previous[v] = u R previous   F display_solution(predecessor) V cell = predecessor.len - 1 L cell != 0 print(cell, end' ‘<’) cell = predecessor[cell] print(0)   V graph = [ [0,1,0,0,0,0], [1,0,1,0,1,0], [0,1,0,0,0,1], [0,0,0,0,1,0], [0,1,0,1,0,0], [0,0,1,0,0,0] ]   display_solution(dijkstra(graph, 0))
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Max_Sum is   Triangle : array (Positive range <>) of integer := (55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 07, 36, 79, 16, 37, 68, 48, 07, 09, 18, 70, 26, 06, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 07, 07, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52, 06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15, 27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93);   Last  : Integer := Triangle'Length; Tn  : Integer := 1;   begin while (Tn * (Tn + 1) / 2) < Last loop Tn := Tn + 1; end loop; for N in reverse 2 .. Tn loop for I in 2 .. N loop Triangle (Last - N) := Triangle (Last - N) + Integer'Max(Triangle (Last - 1), Triangle (Last)); Last := Last - 1; end loop; Last := Last - 1; end loop; Put_Line(Integer'Image(Triangle(1))); end Max_Sum;
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#D
D
import std.stdio, std.string, std.range;   ubyte[16] md4(const(ubyte)[] inData) pure nothrow { enum f = (uint x, uint y, uint z) => (x & y) | (~x & z); enum g = (uint x, uint y, uint z) => (x & y) | (x & z) | (y & z); enum h = (uint x, uint y, uint z) => x ^ y ^ z; enum r = (uint v, uint s) => (v << s) | (v >> (32 - s));   immutable bitLen = ulong(inData.length) << 3; inData ~= 0x80; while (inData.length % 64 != 56) inData ~= 0; const data = cast(uint[])inData ~ [uint(bitLen & uint.max), uint(bitLen >> 32)];   uint a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476;   foreach (const x; data.chunks(16)) { immutable a2 = a, b2 = b, c2 = c, d2 = d; foreach (immutable i; [0, 4, 8, 12]) { a = r(a + f(b, c, d) + x[i+0], 3); d = r(d + f(a, b, c) + x[i+1], 7); c = r(c + f(d, a, b) + x[i+2], 11); b = r(b + f(c, d, a) + x[i+3], 19); } foreach (immutable i; [0, 1, 2, 3]) { a = r(a + g(b, c, d) + x[i+0] + 0x5a827999, 3); d = r(d + g(a, b, c) + x[i+4] + 0x5a827999, 5); c = r(c + g(d, a, b) + x[i+8] + 0x5a827999, 9); b = r(b + g(c, d, a) + x[i+12] + 0x5a827999, 13); } foreach (immutable i; [0, 2, 1, 3]) { a = r(a + h(b, c, d) + x[i+0] + 0x6ed9eba1, 3); d = r(d + h(a, b, c) + x[i+8] + 0x6ed9eba1, 9); c = r(c + h(d, a, b) + x[i+4] + 0x6ed9eba1, 11); b = r(b + h(c, d, a) + x[i+12] + 0x6ed9eba1, 15); } a += a2, b += b2, c += c2, d += d2; }   //return cast(ubyte[16])[a, b, c, d]; immutable uint[4] result = [a, b, c, d]; return cast(ubyte[16])result; }   void main() { writefln("%(%02x%)", "Rosetta Code".representation.md4); }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#PL.2FI
PL/I
  middle: procedure options (main); /* 29 October 2013 */ declare n fixed (15); declare s character (25) varying; declare in file input;   open file (in) title ('/MIDDLE.DAT,type(text),recsize(100)'); on endfile (in) stop;   do forever; get file (in) list (n); put skip list (n); n = abs(n); s = trim(n); if length(s) < 3 then put list ('not possible'); else if mod(length(s), 2) = 0 then put list ('not possible'); else do; do while (length(s) > 3); s = substr(s, 2, length(s)-2); end; put list ('The middle three digits are: ' || s); end; end;   end middle;  
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program MD5_64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ MD5_DIGEST_LENGTH, 16 .equ ZWORKSIZE, 1000   /*********************************/ /* Initialized data */ /*********************************/ .data szMessRosetta: .asciz "Rosetta Code" szMessTest1: .asciz "" szMessTest2: .asciz "abc" szMessTest3: .asciz "abcdefghijklmnopqrstuvwxyz" szMessTest4: .asciz "12345678901234567890123456789012345678901234567890123456789012345678901234567890" szMessTest5: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" szMessFinPgm: .asciz "Program End ok.\n" szMessResult: .asciz "Result for " szMessResult1: .asciz " => " szMessSizeError: .asciz "\033[31mWork area too small !! \033[0m \n" szCarriageReturn: .asciz "\n"   /* array constantes K */ tbConstK: .int 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee .int 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501 .int 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be .int 0x6b901122,0xfd987193,0xa679438e,0x49b40821 .int 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa .int 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8 .int 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed .int 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a .int 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c .int 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70 .int 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05 .int 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665 .int 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039 .int 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1 .int 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1 .int 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391   /* array rotation coef R */ tbRotaR: .int 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22 .int 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20 .int 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23 .int 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21   tbConstH: .int 0x67452301 // H0 .int 0xEFCDAB89 // H1 .int 0x98BADCFE // H2 .int 0x10325476 // H3   /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 //iNbBlocs: .skip 8 sZoneConv: .skip 24 sZoneResult: .skip 24 tbH: .skip 4 * 4 // 4 variables H sZoneTrav: .skip ZWORKSIZE /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   ldr x0,qAdrszMessTest1 bl computeExemple   ldr x0,qAdrszMessTest2 bl computeExemple   ldr x0,qAdrszMessTest3 bl computeExemple   ldr x0,qAdrszMessTest4 bl computeExemple   ldr x0,qAdrszMessTest5 bl computeExemple   ldr x0,qAdrszMessFinPgm bl affichageMess // display message     100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrszCarriageReturn: .quad szCarriageReturn qAdrszMessResult: .quad szMessResult qAdrszMessResult1: .quad szMessResult1 qAdrszMessRosetta: .quad szMessRosetta qAdrszMessTest1: .quad szMessTest1 qAdrszMessTest2: .quad szMessTest2 qAdrszMessTest3: .quad szMessTest3 qAdrszMessTest4: .quad szMessTest4 qAdrszMessTest5: .quad szMessTest5 qAdrsZoneTrav: .quad sZoneTrav qAdrsZoneConv: .quad sZoneConv qAdrszMessFinPgm: .quad szMessFinPgm /***********************************************/ /* compute exemple */ /***********************************************/ /* x0 contains the address of the message */ computeExemple: stp x18,lr,[sp,-16]! // save registers mov x18,x0 bl computeMD5 // call routine MD5   ldr x0,qAdrszMessResult bl affichageMess mov x0,x18 bl affichageMess ldr x0,qAdrszMessResult1 bl affichageMess ldr x0, qAdrsZoneResult bl displayMD5   100: ldp x18,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* compute MD5 */ /******************************************************************/ /* x0 contains the address of the message */ computeMD5: stp x1,lr,[sp,-16]! // save registers ldr x1,qAdrsZoneTrav mov x2,#0 // counter length 1: // copy string in work area cmp x2,ZWORKSIZE bge 99f ldrb w3,[x0,x2] strb w3,[x1,x2] cmp x3,#0 add x4,x2,1 csel x2,x4,x2,ne bne 1b // add bit et compute length lsl x6,x2,#3 // initial message length in bits mov x3,#0b10000000 // add bit 1 at end of string strb w3,[x1,x2] add x2,x2,#1 // length in bytes lsl x4,x2,#3 // length in bits mov x3,#0 2: lsr x5,x2,#6 // padding block 512 bytes lsl x5,x5,#6 sub x5,x2,x5 cmp x5,#56 beq 3f // yes -> end add strb w3,[x1,x2] // add zero at message end add x2,x2,#1 // increment length bytes add x4,x4,#8 // increment length in bits b 2b 3: str x6,[x1,x2] // and store at end   ldr x7,qAdrtbConstH // constantes H address ldr x4,qAdrtbH // start area H mov x5,#0 4: // init array H with start constantes ldr w6,[x7,x5,lsl #2] // load constante str w6,[x4,x5,lsl #2] // and store add x5,x5,#1 cmp x5,#4 // constantes number blt 4b   // split into block of 64 bytes add x2,x2,#4 // TODO : à revoir lsr x4,x2,#6 // blocks number mov x7,#0 // no de block et x1 contient l'adresse zone de travail ldr x3,qAdrtbConstK // K constantes address ldr x5,qAdrtbRotaR // R rotation address   5: // begin loop of each block of 64 bytes // init variable a b c d with H0 H1 H2 H3 ldr x0,qAdrtbH ldr w8,[x0] // a ldr w9,[x0,#4] // b ldr w10,[x0,#8] // c ldr w11,[x0,#12] // d   mov x6,#0 // indice t /* x2 address begin each block */ ldr x1,qAdrsZoneTrav add x2,x1,x7,lsl #6 // compute block begin indice * 4 * 16 6: // begin loop one cmp x6,15 bgt 7f // cas 1 f := (b et c) ou ((non b) et d) // g := i and w12,w9,w10 mvn w13,w9 and w13,w13,w11 orr w12,w12,w13 // f mov x14,x6 // g b 10f 7: cmp x6,31 bgt 8f // f := (d et b) ou ((non d) et c) // g := (5×i + 1) mod 16 and w12,w11,w9 mvn w13,w11 and w13,w13,w10 orr w12,w12,w13 // f mov x13,5 mul x13,x6,x13 add x13,x13,1 lsr x15,x13,4 lsl x15,x15,4 sub x14,x13,x15 b 10f 8: cmp x6,47 bgt 9f // f := b xor c xor d // g := (3×i + 5) mod 16 eor w12,w9,w10 eor w12,w12,w11 mov x13,3 mul x13,x6,x13 add x13,x13,5 lsr x15,x13,4 lsl x15,x15,4 sub x14,x13,x15   b 10f 9: // f := c xor (b ou (non d)) // g := (7×i) mod 16 mvn w13,w11 orr w13,w13,w9 eor w12,w13,w10 // f mov x13,7 mul x13,x6,x13 lsr x15,x13,4 lsl x15,x15,4 sub x14,x13,x15 // g   10: mov w15,w11 mov w11,w10 // d = c mov w10,w9 // c = b add w16,w8,w12 // a + f ldr w17,[x2,x14,lsl #2] add w16,w16,w17 // + valeur bloc g ldr w13,[x3,x6,lsl #2] add w16,w16,w13 // + valeur constante K de i ldr w17,[x5,x6,lsl #2] // rotate left value mov w13,32 sub w17,w13,w17 ror w13,w16,w17 add w9,w9,w13 // new b mov w8, w15 // new a   add x6,x6,1 cmp x6,63 ble 6b   ldr x0,qAdrtbH ldr w1,[x0] // H0 add w1,w1,w8 // + a str w1,[x0] ldr w1,[x0,#4] // H1 add w1,w1,w9 // + b str w1,[x0,#4] ldr w1,[x0,#8] // H2 add w1,w1,w10 // + c str w1,[x0,#8] ldr w1,[x0,#12] // H3 add w1,w1,w11 // + d str w1,[x0,#12] // other bloc add x7,x7,1 // increment block cmp x7,x4 // maxi ? ble 5b   // compute final result ldr x0,qAdrtbH // start area H ldr x2,qAdrsZoneResult ldr w1,[x0] str w1,[x2] ldr w1,[x0,#4] str w1,[x2,#4] ldr w1,[x0,#8] str w1,[x2,#8] ldr w1,[x0,#12] str w1,[x2,#12]   mov x0,#0 // routine OK b 100f 99: // size error ldr x0,qAdrszMessSizeError bl affichageMess mov x0,-1 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrtbConstH: .quad tbConstH qAdrtbConstK: .quad tbConstK qAdrtbRotaR: .quad tbRotaR qAdrtbH: .quad tbH qAdrsZoneResult: .quad sZoneResult qAdrszMessSizeError: .quad szMessSizeError   /******************************************************************/ /* display hash MD5 */ /******************************************************************/ /* x0 contains the address of hash */ displayMD5: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x3,x0 mov x2,#0 1: ldr w0,[x3,x2,lsl #2] // load 4 bytes rev w0,w0 // reverse bytes ldr x1,qAdrsZoneConv bl conversion16_4W // conversion hexa ldr x0,qAdrsZoneConv bl affichageMess add x2,x2,#1 cmp x2,#MD5_DIGEST_LENGTH / 4 blt 1b // and loop ldr x0,qAdrszCarriageReturn bl affichageMess // display message 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* conversion hexadecimal register 32 bits */ /******************************************************************/ /* x0 contains value and x1 address zone receptrice */ conversion16_4W: stp x0,lr,[sp,-48]! // save registres stp x1,x2,[sp,32] // save registres stp x3,x4,[sp,16] // save registres mov x2,#28 // start bit position mov x4,#0xF0000000 // mask mov x3,x0 // save entry value 1: // start loop and x0,x3,x4 // value register and mask lsr x0,x0,x2 // right shift cmp x0,#10 // >= 10 ? bge 2f // yes add x0,x0,#48 // no is digit b 3f 2: add x0,x0,#55 // else is a letter A-F 3: strb w0,[x1],#1 // load result and + 1 in address lsr x4,x4,#4 // shift mask 4 bits left subs x2,x2,#4 // decrement counter 4 bits <= zero  ? bge 1b // no -> loop   100: // fin standard de la fonction ldp x3,x4,[sp,16] // restaur des 2 registres ldp x1,x2,[sp,32] // restaur des 2 registres ldp x0,lr,[sp],48 // restaur des 2 registres ret /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Run_BASIC
Run BASIC
dim choose$(5) choose$(1) = "1 Fee Fie" choose$(2) = "2 Huff Puff" choose$(3) = "3 Mirror, Mirror" choose$(4) = "4 Tick, Tock" choose$(5) = "Exit"   [start] print "Menu Selection" listbox #lb,choose$(),5 button #sel, "Accept",[select] wait   [select] selected$=#lb selection$() print " " if selected$<>"" then print "You selected ";selected$ else print "No selection made" end if button #con, "Continue",[go2] wait [go2] if selected$<>"Exit" then cls goto [start] else cls end end if
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Rust
Rust
  fn menu_select<'a>(items: &'a [&'a str]) -> &'a str { if items.len() == 0 { return ""; }   let stdin = std::io::stdin(); let mut buffer = String::new();   loop { for (i, item) in items.iter().enumerate() { println!("{}) {}", i + 1, item); } print!("Pick a number from 1 to {}: ", items.len());   // Read the user input: stdin.read_line(&mut buffer).unwrap(); println!();   if let Ok(selected_index) = buffer.trim().parse::<usize>() { if 0 < selected_index { if let Some(selected_item) = items.get(selected_index - 1) { return selected_item; } } }   // The buffer will contain the old input, so we need to clear it before we can reuse it. buffer.clear(); } }   fn main() { // Empty list: let selection = menu_select(&[]); println!("No choice: {:?}", selection);   // List with items: let items = [ "fee fie", "huff and puff", "mirror mirror", "tick tock", ];   let selection = menu_select(&items); println!("You chose: {}", selection); }  
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Dyalect
Dyalect
func mcnugget(limit) { var sv = Array.Empty(limit + 1, false) for s in 0^6..limit { for n in s^9..limit { for t in n^20..limit { sv[t] = true } } } for i in limit^-1..0 { if !sv[i] { print("Maximum non-McNuggets number is \(i)") return } } }   mcnugget(100)
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Elixir
Elixir
defmodule Mcnugget do def solve(limit) do 0..limit |> MapSet.new() |> MapSet.difference( for( x <- 0..limit, y <- 0..limit, z <- 0..limit, Integer.mod(x, 6) == 0, Integer.mod(y, 9) == 0, Integer.mod(z, 20) == 0, x + y + z <= limit, into: MapSet.new(), do: x + y + z ) ) |> Enum.max() end end   Mcnugget.solve(100) |> IO.puts  
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Action.21
Action!
DEFINE TOP="0" DEFINE RIGHT="1" DEFINE BOTTOM="2" DEFINE LEFT="3" DEFINE WIDTH="160" DEFINE HEIGHT="96"   DEFINE STACK_SIZE="5000" BYTE ARRAY stack(STACK_SIZE) INT stackSize   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stackSize>=STACK_SIZE THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE x,y) IF IsFull() THEN Break() RETURN FI stack(stackSize)=x stackSize==+1 stack(stackSize)=y stackSize==+1 RETURN   PROC Pop(BYTE POINTER x,y) IF IsEmpty() THEN Break() RETURN FI stackSize==-1 y^=stack(stackSize) stackSize==-1 x^=stack(stackSize) RETURN   PROC Push3(BYTE x,y,d) IF IsFull() THEN Break() RETURN FI stack(stackSize)=x stackSize==+1 stack(stackSize)=y stackSize==+1 stack(stackSize)=d stackSize==+1 RETURN   PROC Pop3(BYTE POINTER x,y,d) IF IsEmpty() THEN Break() RETURN FI stackSize==-1 d^=stack(stackSize) stackSize==-1 y^=stack(stackSize) stackSize==-1 x^=stack(stackSize) RETURN   PROC FillScreen() BYTE POINTER ptr ;pointer to the screen memory INT screenSize=[3840]   ptr=PeekC(88) SetBlock(ptr,screenSize,$55)   Color=0 Plot(0,HEIGHT-1) DrawTo(WIDTH-1,HEIGHT-1) DrawTo(WIDTH-1,0) RETURN   PROC GetNeighbors(BYTE x,y BYTE ARRAY n BYTE POINTER count) DEFINE WALL="1"   count^=0 IF y>2 AND Locate(x,y-2)=WALL THEN n(count^)=TOP count^==+1 FI IF x<WIDTH-3 AND Locate(x+2,y)=WALL THEN n(count^)=RIGHT count^==+1 FI IF y<HEIGHT-3 AND Locate(x,y+2)=WALL THEN n(count^)=BOTTOM count^==+1 FI IF x>2 AND Locate(x-2,y)=WALL THEN n(count^)=LEFT count^==+1 FI RETURN   PROC DrawConnection(BYTE POINTER x,y BYTE dir) Plot(x^,y^) IF dir=TOP THEN y^==-2 ELSEIF dir=RIGHT THEN x^==+2 ELSEIF dir=BOTTOM THEN y^==+2 ELSE x^==-2 FI DrawTo(x^,y^) RETURN   PROC Maze(BYTE x,y) BYTE ARRAY stack,neighbors BYTE dir,nCount   FillScreen()   Color=2 InitStack() Push(x,y) WHILE IsEmpty()=0 DO Pop(@x,@y) GetNeighbors(x,y,neighbors,@nCount) IF nCount>0 THEN Push(x,y) dir=neighbors(Rand(nCount)) DrawConnection(@x,@y,dir) Push(x,y) FI OD RETURN   BYTE FUNC IsConnection(BYTE x,y,dir) DEFINE WAY="2" IF dir=TOP AND y>2 AND Locate(x,y-1)=WAY THEN RETURN (1) ELSEIF dir=RIGHT AND x<WIDTH-3 AND Locate(x+1,y)=WAY THEN RETURN (1) ELSEIF dir=BOTTOM AND y<HEIGHT-3 AND Locate(x,y+1)=WAY THEN RETURN (1) ELSEIF dir=LEFT AND x>2 AND Locate(x-1,y)=WAY THEN RETURN (1) FI RETURN (0)   PROC Solve(BYTE x1,y1,x2,y2) BYTE dir,x,y,lastX,lastY,back   Color=3 Plot(x1,y1) Plot(x2,y2)   InitStack() Push3(x1,y1,TOP) WHILE IsEmpty()=0 DO Pop3(@x,@y,@dir) IF back THEN Color=2 Plot(lastX,lastY) DrawTo(x,y) FI IF IsConnection(x,y,dir) THEN Color=3 Push3(x,y,dir+1) DrawConnection(@x,@y,dir) IF x=x2 AND y=y2 THEN RETURN FI Push3(x,y,TOP) back=0 ELSEIF dir<=LEFT THEN Push3(x,y,dir+1) back=0 ELSE lastX=x lastY=y back=1 FI OD RETURN   PROC Main() BYTE CH=$02FC,COLOR0=$02C4,COLOR1=$02C5,COLOR2=$02C6 BYTE x,y,x2,y2   Graphics(7+16) COLOR0=$0A COLOR1=$04 COLOR2=$A6   x=Rand((WIDTH RSH 1)-1) LSH 1+1 y=Rand((HEIGHT RSH 1)-1) LSH 1+1 Maze(x,y)   x=Rand((WIDTH RSH 1)-1) LSH 1+1 y=Rand((HEIGHT RSH 1)-1) LSH 1+1 x2=Rand((WIDTH RSH 1)-1) LSH 1+1 y2=Rand((HEIGHT RSH 1)-1) LSH 1+1 Solve(x,y,x2,y2)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#ALGOL_68
ALGOL 68
# create a triangular array of the required values #   [ 1]INT row 1 := ( 55 ); [ 2]INT row 2 := ( 94, 48 ); [ 3]INT row 3 := ( 95, 30, 96 ); [ 4]INT row 4 := ( 77, 71, 26, 67 ); [ 5]INT row 5 := ( 97, 13, 76, 38, 45 ); [ 6]INT row 6 := ( 07, 36, 79, 16, 37, 68 ); [ 7]INT row 7 := ( 48, 07, 09, 18, 70, 26, 06 ); [ 8]INT row 8 := ( 18, 72, 79, 46, 59, 79, 29, 90 ); [ 9]INT row 9 := ( 20, 76, 87, 11, 32, 07, 07, 49, 18 ); [10]INT row 10 := ( 27, 83, 58, 35, 71, 11, 25, 57, 29, 85 ); [11]INT row 11 := ( 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55 ); [12]INT row 12 := ( 02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23 ); [13]INT row 13 := ( 92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42 ); [14]INT row 14 := ( 56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72 ); [15]INT row 15 := ( 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36 ); [16]INT row 16 := ( 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52 ); [17]INT row 17 := ( 06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15 ); [18]INT row 18 := ( 27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 );   [18]REF[]INT triangle := ( row 1, row 2, row 3, row 4, row 5, row 6 , row 7, row 8, row 9, row 10, row 11, row 12 , row 13, row 14, row 15, row 16, row 17, row 18 );   PROC max = ( INT a, INT b )INT: IF a > b THEN a ELSE b FI;   # working backwards, we replace the elements of each row with the sum of that # # element and the maximum of the two elements below it. # # That destroys the triangle but leaves element [1][1] equal to the required # # maximum #     FOR row FROM UPB triangle - 1 BY -1 TO 1 DO FOR element FROM 1 TO UPB triangle[row] DO # the elements "under" triangle[row][element] are # # triangle[row+1][element] and triangle[row+1][element+1] # triangle[row][element] +:= max( triangle[row+1][element], triangle[row+1][element+1] ) OD OD;   print( ( triangle[1][1], newline ) )  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Delphi
Delphi
  program CalcMD4;   {$APPTYPE CONSOLE}   uses System.SysUtils, DCPmd4;   function MD4(const Str: string): string; var HashDigest: array of byte; d: Byte; begin Result := ''; with TDCP_md4.Create(nil) do begin Init; UpdateStr(Str); SetLength(HashDigest, GetHashSize div 8); final(HashDigest[0]); for d in HashDigest do Result := Result + d.ToHexString(2); Free; end; end;   begin Writeln(MD4('Rosetta Code')); readln; end.
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Plain_English
Plain English
To run: Start up. Test 123. Test 12345. Test 1234567. Test 987654321. Test 10001. Test -10001. Test -123. Test -100. Test 100. Test -12345. Test 1. Test 2. Test -1. Test -10. Test 2002. Test -2002. Test 0. Wait for the escape key. Shut down.   To get the middle three digits of a number giving a string: Privatize the number. De-sign the number. Convert the number to the string. If the string's length is less than 3, put "Number has fewer than three digits" into the string; exit. If the string's length is even, put "Number has no middle" into the string; exit. Put the string's length divided by 2 into a midpoint number. Slap a substring on the string. Put the substring's first plus the midpoint minus 1 into the substring's first. Put the substring's first plus 2 into the substring's last. Put the substring into the string.   To test a number: Get the middle three digits of the number giving a string. Write "" then the number then " -> " then the string on the console.
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with GNAT.MD5;   procedure MD5_Digest is begin Put(GNAT.MD5.Digest("Foo bar baz")); end MD5_Digest;
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Scala
Scala
import scala.util.Try   object Menu extends App { val choice = menu(list)   def menu(menuList: Seq[String]): String = { if (menuList.isEmpty) "" else { val n = menuList.size   def getChoice: Try[Int] = { println("\n M E N U\n") menuList.zipWithIndex.map { case (text, index) => s"${index + 1}: $text" }.foreach(println(_)) print(s"\nEnter your choice 1 - $n : ") Try { io.StdIn.readInt() } }   menuList(Iterator.continually(getChoice) .dropWhile(p => p.isFailure || !(1 to n).contains(p.get)) .next.get - 1) } }   def list = Seq("fee fie", "huff and puff", "mirror mirror", "tick tock")   println(s"\nYou chose : $choice") }
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: menuSelect (in array string: items, in string: prompt) is func result var string: selection is ""; local var string: item is ""; var integer: index is 0; var integer: num is 0; begin if length(items) <> 0 then repeat for item key index range items do writeln(index <& ". " <& item); end for; write(prompt); readln(num); until num >= 1 and num <= length(items); selection := items[num]; end if end func;   const array string: items is [] ("fee fie", "huff and puff", "mirror mirror", "tick tock"); const string: prompt is "Which is from the three pigs? ";   const proc: main is func begin writeln("You chose " <& menuSelect(items, prompt)); end func;
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#F.23
F#
  // McNuggets. Nigel Galloway: October 28th., 2018 let fN n g = Seq.initInfinite(fun ng->ng*n+g)|>Seq.takeWhile(fun n->n<=100) printfn "%d" (Set.maxElement(Set.difference (set[1..100]) (fN 20 0|>Seq.collect(fun n->fN 9 n)|>Seq.collect(fun n->fN 6 n)|>Set.ofSeq)))  
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Ada
Ada
with Ada.Text_IO;   procedure Maze_Solver is   X_Size: constant Natural := 45; Y_Size: constant Natural := 17;   subtype X_Range is Natural range 1 .. X_Size; subtype Y_Range is Natural range 1 .. Y_Size;   East: constant X_Range := 2; South: constant Y_Range := 1;   X_Start: constant X_Range  := 3; -- start at the upper left Y_Start: constant Y_Range  := 1; X_Finish: constant X_Range := X_Size-East; -- go to the lower right Y_Finish: constant Y_Range := Y_Size;   type Maze_Type is array (Y_Range) of String(X_Range);   function Solved(X: X_Range; Y: Y_Range) return Boolean is begin return (X = X_Finish) and (Y = Y_Finish); end Solved;   procedure Output_Maze(M: Maze_Type; Message: String := "") is begin if Message /= "" then Ada.Text_IO.Put_Line(Message); end if; for I in M'Range loop Ada.Text_IO.Put_Line(M(I)); end loop; end Output_Maze;   procedure Search(M: in out Maze_Type; X: X_Range; Y:Y_Range) is begin M(Y)(X) := '*'; if Solved(X, Y) then Output_Maze(M, "Solution found!"); else if Integer(Y)-South >= 1 and then M(Y-South)(X) = ' ' then Search(M, X, Y-South); end if; if Integer(Y)+South <= Y_Size and then M(Y+South)(X) = ' ' then Search(M, X, Y+South); end if; if Integer(X)-East >= 1 and then M(Y)(X-East) = ' ' then Search(M, X-East, Y); end if; if Integer(Y)+East <= Y_Size and then M(Y)(X+East) = ' ' then Search(M, X+East, Y); end if; end if; M(Y)(X) := ' '; end Search;   Maze: Maze_Type; X: X_Range := X_Start; Y: Y_Range := Y_Start;   begin for I in 1 .. Y_Size loop Maze(I) := Ada.Text_IO.Get_Line; end loop; Maze(Y_Start)(X_Start)  := ' '; -- Start from Maze(Y_Finish)(X_Finish) := ' '; -- Go_To Output_Maze(Maze, "The Maze:"); Ada.Text_IO.New_Line;   Search(Maze, X, Y) ; -- Will output *all* Solutions. -- If there is no output, there is no solution. end Maze_Solver;
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#AppleScript
AppleScript
---------------- MAXIMUM TRIANGLE PATH SUM ---------------   -- Working from the bottom of the triangle upwards, -- summing each number with the larger of the two below -- until the maximum emerges at the top.   -- maxPathSum :: [[Int]] -> Int on maxPathSum(xss)   -- With the last row as the initial accumulator, -- folding from the penultimate line, -- towards the top of the triangle:   -- sumWithRowBelow :: [Int] -> [Int] -> [Int] script sumWithRowBelow on |λ|(row, accum)   -- plusGreaterOfTwoBelow :: Int -> Int -> Int -> Int script plusGreaterOfTwoBelow on |λ|(x, intLeft, intRight) x + max(intLeft, intRight) end |λ| end script   -- The accumulator, zipped with the tail of the -- accumulator, yields pairs of adjacent sums so far.   zipWith3(plusGreaterOfTwoBelow, row, accum, tail(accum)) end |λ| end script   -- A list of lists folded down to a list of just one remaining integer. -- Head returns that integer from the list.   head(foldr1(sumWithRowBelow, xss)) end maxPathSum     --------------------------- TEST ------------------------- on run   maxPathSum({¬ {55}, ¬ {94, 48}, ¬ {95, 30, 96}, ¬ {77, 71, 26, 67}, ¬ {97, 13, 76, 38, 45}, ¬ {7, 36, 79, 16, 37, 68}, ¬ {48, 7, 9, 18, 70, 26, 6}, ¬ {18, 72, 79, 46, 59, 79, 29, 90}, ¬ {20, 76, 87, 11, 32, 7, 7, 49, 18}, ¬ {27, 83, 58, 35, 71, 11, 25, 57, 29, 85}, ¬ {14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55}, ¬ {2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23}, ¬ {92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42}, ¬ {56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72}, ¬ {44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36}, ¬ {85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52}, ¬ {6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15}, ¬ {27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93} ¬ })   --> 1320 end run     -------------------- GENERIC FUNCTIONS -------------------   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- foldr1 :: (a -> a -> a) -> [a] -> a on foldr1(f, xs) if length of xs > 1 then tell mReturn(f) set v to item -1 of xs set lng to length of xs repeat with i from lng - 1 to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell else xs end if end foldr1     -- head :: [a] -> a on head(xs) if length of xs > 0 then item 1 of xs else missing value end if end head     -- max :: Ord a => a -> a -> a on max(x, y) if x > y then x else y end if end max     -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min     -- minimum :: [a] -> a on minimum(xs) script min on |λ|(a, x) if x < a or a is missing value then x else a end if end |λ| end script   foldl(min, missing value, xs) end minimum     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail     -- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] on zipWith3(f, xs, ys, zs) set lng to minimum({length of xs, length of ys, length of zs}) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys, item i of zs) end repeat return lst end tell end zipWith3
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Emacs_Lisp
Emacs Lisp
(require 'md4) (require 'hex-util) (let* ((s "Rosetta Code") (m (md4 s (length s)))) ;; m = 16 binary bytes (encode-hex-string m)) => "a52bcfc6a0d0d300cdc5ddbfbefe478b"
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#PowerShell
PowerShell
function middle3($inp){   $str = [Math]::abs($inp)   $leng = "$str".length   if ($leng -lt 3){ Write-host $inp": [ERROR] too short." Return } if (($leng % 2) -eq 0){ Write-host $inp": [ERROR] even number of digits." } else { $trimmer = ($leng - 3) / 2 $ans = "$str".subString($trimmer,3)   Write-host $inp": $ans" } Return }   $sample = 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0   foreach ($x in $sample){middle3 $x}
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#ALGOL_68
ALGOL 68
    # Based on wikipedia article pseudocode #   # s specifies the per-round shift amounts # []INT s = (7,12,17,22, 7,12,17,22, 7,12,17,22, 7,12,17,22, 5, 9,14,20, 5, 9,14,20, 5, 9,14,20, 5, 9,14,20, 4,11,16,23, 4,11,16,23, 4,11,16,23, 4,11,16,23, 6,10,15,21, 6,10,15,21, 6,10,15,21, 6,10,15,21);   []BITS k = (16rd76aa478, 16re8c7b756, 16r242070db, 16rc1bdceee, 16rf57c0faf, 16r4787c62a, 16ra8304613, 16rfd469501, 16r698098d8, 16r8b44f7af, 16rffff5bb1, 16r895cd7be, 16r6b901122, 16rfd987193, 16ra679438e, 16r49b40821, 16rf61e2562, 16rc040b340, 16r265e5a51, 16re9b6c7aa, 16rd62f105d, 16r02441453, 16rd8a1e681, 16re7d3fbc8, 16r21e1cde6, 16rc33707d6, 16rf4d50d87, 16r455a14ed, 16ra9e3e905, 16rfcefa3f8, 16r676f02d9, 16r8d2a4c8a, 16rfffa3942, 16r8771f681, 16r6d9d6122, 16rfde5380c, 16ra4beea44, 16r4bdecfa9, 16rf6bb4b60, 16rbebfbc70, 16r289b7ec6, 16reaa127fa, 16rd4ef3085, 16r04881d05, 16rd9d4d039, 16re6db99e5, 16r1fa27cf8, 16rc4ac5665, 16rf4292244, 16r432aff97, 16rab9423a7, 16rfc93a039, 16r655b59c3, 16r8f0ccc92, 16rffeff47d, 16r85845dd1, 16r6fa87e4f, 16rfe2ce6e0, 16ra3014314, 16r4e0811a1, 16rf7537e82, 16rbd3af235, 16r2ad7d2bb, 16reb86d391);   OP + = (BITS a, b) BITS: BEGIN BITS c = BIN (ABS (a AND 16rffff) + ABS (b AND 16rffff)); BITS d = BIN (ABS (a SHR 16) + ABS (b SHR 16) + ABS (c SHR 16)); (c AND 16rffff) OR (d SHL 16) END;   #[0:63]LONG INT k; FOR i FROM 0 TO 63 DO k[i] := ENTIER (ABS (sin(i+1)) * LONG INT(2)**32) OD;#   PROC md5 = (STRING intext) STRING: BEGIN # Initialize variables: # BITS a0 := 16r67452301, a1 := 16refcdab89, a2 := 16r98badcfe, a3 := 16r10325476;   STRING text := intext;   # Pre-processing: adding a single 1 bit # text +:= REPR 128;   # Pre-processing: padding with zeros append "0" bit until message length in bits ≡ 448 (mod 512) # WHILE ELEMS text MOD 64 ≠ 56 DO text +:= REPR 0 OD;   # append original length in bits mod (2 pow 64) to message # text +:= dec2asc (ELEMS intext * 8);   # MD5 rounds # # Process the message in successive 512-bit chunks: # WHILE text ≠ "" DO # for each 512-bit (64 byte) chunk of message # []CHAR chunk = text[1:64]; text := text[65:]; # break chunk into sixteen 32-bit words M[j], 0 <= j <= 15 # [0:15]BITS m; FOR j FROM 0 TO 15 DO m[j] := BIN (ABS chunk[j*4+1]) OR BIN (ABS chunk[j*4+2]) SHL 8 OR BIN (ABS chunk[j*4+3]) SHL 16 OR BIN (ABS chunk[j*4+4]) SHL 24 OD; INT g; BITS a, b, c, d, f, dtemp;   # Initialize hash value for this chunk # a := a0; b := a1; c := a2; d := a3; FOR i FROM 0 TO 63 DO IF 0 <= i AND i <= 15 THEN f := (b AND c) OR ((NOT b) AND d); g := i ELIF 16 <= i AND i <= 31 THEN f := (d AND b) OR ((NOT d) AND c); g := (5×i + 1) MOD 16 ELIF 32 <= i AND i <= 47 THEN f := b XOR c XOR d; g := (3×i + 5) MOD 16 ELIF 48 <= i AND i <= 63 THEN f := c XOR (b OR (NOT d)); g := (7×i) MOD 16 FI; dtemp := d; d := c; c := b; b := b + leftrotate ((a + f + k[1+i] + m[g]), s[1+i]); a := dtemp OD; # Add this chunk's hash to result so far # a0 := a0 + a; a1 := a1 + b; a2 := a2 + c; a3 := a3 + d OD; revhex (a0) + revhex (a1) + revhex (a2) + revhex (a3) END;   PROC leftrotate = (BITS x, INT c) BITS: (x SHL c) OR (x SHR (32-c));   # dec2asc: dec to 8 byte asc # PROC dec2asc = (INT nn)STRING: BEGIN STRING h := ""; INT n := nn; FOR i TO 8 DO h +:= REPR (n MOD 256); n ÷:= 256 OD; h END;   PROC revhex = (BITS x) STRING : BEGIN # Convert to lowercase hexadecimal STRING # PROC hexdig = (BITS x) CHAR: (REPR (ABS(x) <= 9 | ABS(x) + ABS("0") | ABS(x) - 10 + ABS("a"))); hexdig (x SHR 4 AND 16rf) + hexdig (x AND 16rf) + hexdig (x SHR 12 AND 16rf) + hexdig (x SHR 8 AND 16rf) + hexdig (x SHR 20 AND 16rf) + hexdig (x SHR 16 AND 16rf) + hexdig (x SHR 28 AND 16rf) + hexdig (x SHR 24 AND 16rf) END;   STRING testmsg = "The quick brown fox jumps over the lazy dog"; STRING checksum = "9e107d9d372bb6826bd81d3542a419d6";   print ((testmsg, new line)); print ((checksum, new line));   STRING test = md5 (testmsg);   IF test = checksum THEN print (("passed", new line)); print ((test, new line)) ELSE print (("failed")) FI  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Sidef
Sidef
func menu (prompt, arr) { arr.len > 0 || return '' loop { for i in ^arr { say " #{i}: #{arr[i]}" } var n = Sys.scanln(prompt) \\ return() n ~~ /^[0-9]+\z/ ? Num(n) : next arr.exists(n) && return arr[n] } }   var list = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] var prompt = 'Please choose an item number: '   var answer = menu(prompt, list) say "You choose: #{answer}"
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Factor
Factor
USING: backtrack kernel math.ranges prettyprint sequences sets ; 101 <iota> [ 0 6 9 20 [ 100 swap <range> amb-lazy ] tri@ ] bag-of diff last .
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#AutoHotkey
AutoHotkey
Width := 10, Height := 10 ; set grid size SleepTime := 0   gosub, Startup   Gui, +AlwaysOnTop Gui, font, s12, consolas Gui, add, edit, vEditGrid x10, % maze Gui, add, button, xs gStartup Default, Generate maze Gui, add, button, x+10 gSolve, Solve Gui, show,, maze GuiControl,, EditGrid, % maze ; show maze return   ;----------------------------------------------------------------------- ^Esc:: GuiEscape: GuiClose: ExitApp return   ;----------------------------------------------------------------------- Startup: oMaze := [] ; initialize Solved := false loop, % Height { row := A_Index loop, % Width ; create oMaze[row,column] borders col := A_Index, oMaze[row,col] := "LRTB" ; i.e. oMaze[2,5] := LRTB (add all borders) } Random, row, 1, % Height ; random row Random, col, 1, % Width ; random col grid := maze2text(oMaze) ; object to text GuiControl,, EditGrid, % Grid ; show Grid row := col := 1 ; reset to 1,1 oMaze := Generate_maze(row, col, oMaze) ; generate maze starting from random row/column oMaze[1,1] .= "X" ; start from 1,1 maze := maze2text(oMaze) ; object to text GuiControl,, EditGrid, % maze ; show maze GuiControl,, EditRoute ; clear route GuiControl, Enable, Solve return   ;----------------------------------------------------------------------- Solve: GuiControl, Disable, Generate maze GuiControl, Disable, Solve loop % oRoute.MaxIndex() oRoute.pop()   oSolution := Solve(1, 1, oMaze) ; solve starting from 1,1 oMaze := oSolution.1 oRoute := oSolution.2 Update(oMaze, oRoute) Solved := true GuiControl, Enable, Generate maze return   ;----------------------------------------------------------------------- Update(oMaze, oRoute){ global SleepTime GuiControl,, EditGrid, % maze2text(oMaze) Sleep, % SleepTime }   ;----------------------------------------------------------------------- maze2text(oMaze){ width := oMaze.1.MaxIndex() BLK := "█" for row, objRow in oMaze { for col, val in objRow ; add ceiling { ceiling := InStr(oMaze[row, col] , "x") && InStr(oMaze[row-1, col] , "x") ? "+ " BLK " " : "+ " grid .= (InStr(val, "T") ? "+---" : ceiling) (col = Width ? "+`n" : "") } for col, val in objRow ; add left wall { wall := SubStr(val, 0) = "X" ? BLK : " " grid .= (InStr(val, "L") ? "| " : " ") wall " " (col = Width ? "|`n" : "") ; add left wall if needed then outer right border } } Loop % Width Grid .= "+---" ; add bottom floor Grid .= "+" ; add right bottom corner return RegExReplace(grid , BLK " (?=" BLK ")" , BLK BLK BLK BLK) ; fill gaps }   ;----------------------------------------------------------------------- Generate_maze(row, col, oMaze) { neighbors := row+1 "," col "`n" row-1 "," col "`n" row "," col+1 "`n" row "," col-1 Sort, neighbors, random ; randomize neighbors list Loop, parse, neighbors, `n ; for each neighbor { rowX := StrSplit(A_LoopField, ",").1 ; this neighbor row colX := StrSplit(A_LoopField, ",").2 ; this neighbor column if !instr(oMaze[rowX,colX], "LRTB") || !oMaze[rowX, colX] ; if visited (has a missing border) or out of bounds continue ; skip   ; remove borders if (row > rowX) ; Cell is below this neighbor oMaze[row,col] := StrReplace(oMaze[row,col], "T") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "B") else if (row < rowX) ; Cell is above this neighbor oMaze[row,col] := StrReplace(oMaze[row,col], "B") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "T") else if (col > colX) ; Cell is right of this neighbor oMaze[row,col] := StrReplace(oMaze[row,col], "L") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "R") else if (col < colX) ; Cell is left of this neighbor oMaze[row,col] := StrReplace(oMaze[row,col], "R") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "L")   Generate_maze(rowX, colX, oMaze) ; recurse for this neighbor } return, oMaze }   ;----------------------------------------------------------------------- Solve(row, col, oMaze){ static oRoute := [] oNeighbor := [], targetrow := oMaze.MaxIndex(), targetCol := oMaze.1.MaxIndex()   ;~ Update(oMaze, oRoute) oRoute.push(row ":" col) ; push current cell address to oRoute oMaze[row, col] .= "X" ; mark it visited "X"   if (row = targetrow) && (Col = targetCol) ; if solved return true ; return ture   ; create list of Neighbors oNeighbor[row, col] := [] if !InStr(oMaze[row, col], "R") ; if no Right border oNeighbor[row, col].push(row "," col+1) ; add neighbor if !InStr(oMaze[row, col], "B") ; if no Bottom border oNeighbor[row, col].push(row+1 "," col) ; add neighbor if !InStr(oMaze[row, col], "T") ; if no Top border oNeighbor[row, col].push(row-1 "," col) ; add neighbor if !InStr(oMaze[row, col], "L") ; if no Left border oNeighbor[row, col].push(row "," col-1) ; add neighbor   ; recurese for each oNeighbor for each, neighbor in oNeighbor[row, col] ; for each neighbor { Update(oMaze, oRoute) startrow := StrSplit(neighbor, ",").1 ; this neighbor startCol := StrSplit(neighbor, ",").2 ; becomes starting point   if !InStr(oMaze[startrow, startCol], "X") ; if it was not visited if Solve(startrow, startCol, oMaze) ; recurse for current neighbor return [oMaze, oRoute] ; return solution if solved } oRoute.pop() ; no solution found, back track oMaze[row, Col] := StrReplace(oMaze[row, Col], "X") ; no solution found, back track ;~ Update(oMaze, oRoute) }   ;----------------------------------------------------------------------- #IfWinActive, maze Right:: Left:: Up:: Down:: if Solved return   if (A_ThisHotkey="Right") && (!InStr(oMaze[row,col], "R")) oMaze[row, col] := StrReplace(oMaze[row, col], "X") , col++ if (A_ThisHotkey="Left") && (!InStr(oMaze[row,col], "L")) oMaze[row, col] := StrReplace(oMaze[row, col], "X") , col-- if (A_ThisHotkey="Up") && (!InStr(oMaze[row,col], "T")) oMaze[row, col] := StrReplace(oMaze[row, col], "X") , row-- if (A_ThisHotkey="Down") && (!InStr(oMaze[row,col], "B")) oMaze[row, col] := StrReplace(oMaze[row, col], "X") , row++   oMaze[row, col] .= "X" GuiControl,, EditGrid, % maze2text(oMaze)   if (col = Width) && (row = Height) { Solved := true oMaze[height, width] := StrReplace(oMaze[height, width], "X") SleepTime := 0 gosub, solve return } return #IfWinActive
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Astro
Astro
fun maxpathsum(t): #: Array{Array{I}} let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1]   let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, 26, 06], [18, 72, 79, 46, 59, 79, 29, 90], [20, 76, 87, 11, 32, 07, 07, 49, 18], [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] ]   @print maxpathsum test  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Erlang
Erlang
  -module(md4). -export([md4/0]).   md4() -> <<MD4:128>> = crypto:md4("Rosetta Code"), io:fwrite("Rosetta Code => ~.16B~n",[MD4]).  
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Prolog
Prolog
  middle_3_digits(Number, [D1,D2,D3]) :- verify_middle_3_able(Number, Digits), append(FrontDigits, [D1,D2,D3| BackDigits], Digits), same_length(FrontDigits, BackDigits).   verify_middle_3_able(Number, Digits) :- must_be(number, Number), AbsNumber is abs(Number), number_chars(AbsNumber, Digits), length(Digits, NumDigits), ( 3 > NumDigits -> domain_error('at least 3 digits', Number) ; 0 is NumDigits mod 2 -> domain_error('odd number of digits', Number) ; true ).  
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#APL
APL
  md5←{ ⍝ index origin zero ⎕IO←0 ⍝ decoding UTF-8 & padding M←(⊢,(0⍴⍨512|448-512|≢))1,⍨l←,⍉(8⍴2)⊤'UTF-8'⎕UCS ⍵ ⍝ add length M,←,⍉(8⍴2)⊤⌽(8⍴256)⊤≢l ⍝ init registers A←16⊥6 7 4 5 2 3 0 1 B←16⊥14 15 12 13 10 11 8 9 C←16⊥9 8 11 10 13 12 15 14 D←16⊥1 0 3 2 5 4 7 6 ⍝ T table T←⌊(2*32)×|1○1+⍳64 ⍝ index table K←16|i,(1+5×i),(5+3×i),7×i←⍳16 ⍝ rot table S←,1 0 2⍉4 4 4⍴7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21 ⍝ truncate ⍵ to 32 bit & rot left ⍺ rot←{2⊥⍺⌽(32⍴2)⊤⍵} proc←{ ⍝ pack 512 bits into 32 bit words & ⍝ precompute X[k] + T[i] l←T+(⊂K)⌷256⊥⍉⌽16 4⍴2⊥⍉64 8⍴⍺ fn←{ ⍝ a b c d to binary a b c d←↓⍉(32⍴2)⊤⍵ ⍝ a + F(b,c,d) ⍺<16:S[⍺]rot l[⍺]+2⊥a+d≠b∧c≠d ⍺<32:S[⍺]rot l[⍺]+2⊥a+(b∧d)∨(c∧~d) ⍺<48:S[⍺]rot l[⍺]+2⊥a+b≠c≠d S[⍺]rot l[⍺]+2⊥a+c≠b∨~d } (2*32)|⍵+⊃{¯1⌽((⍵[1]+⍺ fn ⍵)@0)⍵}/(⌽⍳64),⊂⍵ } ⍝ process each 512 bits loop←{⍬≡⍺:⍵ ⋄ (512↓⍺)∇(512↑⍺)proc ⍵} ⍝ output registers (⎕D,⎕A)[,⍉(2⍴16)⊤,⍉⊖(4⍴256)⊤M loop A B C D] }  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Swift
Swift
func getMenuInput(selections: [String]) -> String { guard !selections.isEmpty else { return "" }   func printMenu() { for (i, str) in selections.enumerated() { print("\(i + 1)) \(str)") }   print("Selection: ", terminator: "") }   while true { printMenu()   guard let input = readLine(strippingNewline: true), !input.isEmpty else { return "" }   guard let n = Int(input), n > 0, n <= selections.count else { continue }   return selections[n - 1] } }   let selected = getMenuInput(selections: [ "fee fie", "huff and puff", "mirror mirror", "tick tock" ])   print("You chose: \(selected)")
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#FOCAL
FOCAL
01.10 F N=0,100;S T(N)=0 01.20 F A=0,6,100;F B=A,9,100;F C=B,20,100;S T(C)=-1 01.30 S N=101 01.40 S N=N-1 01.50 I (T(N))1.4 01.60 T %3,N,! 01.70 Q
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#BBC_BASIC
BBC BASIC
MazeWidth% = 11 MazeHeight% = 9 MazeCell% = 50   VDU 23,22,MazeWidth%*MazeCell%/2+3;MazeHeight%*MazeCell%/2+3;8,16,16,128 VDU 23,23,3;0;0;0; : REM Line thickness OFF PROCgeneratemaze(Maze&(), MazeWidth%, MazeHeight%, MazeCell%) PROCsolvemaze(Path{()}, Maze&(), 0, MazeHeight%-1, MazeWidth%-1, 0, MazeCell%) END   DEF PROCsolvemaze(RETURN s{()}, m&(), x%, y%, dstx%, dsty%, s%) LOCAL h%, i%, n%, p%, q%, w% w% = DIM(m&(),1) h% = DIM(m&(),2) DIM s{(w%*h%) x%,y%} GCOL 3,14 m&(x%,y%) OR= &80 REPEAT FOR i% = 0 TO 3 CASE i% OF WHEN 0: p% = x%-1 : q% = y% WHEN 1: p% = x%+1 : q% = y% WHEN 2: p% = x% : q% = y%-1 WHEN 3: p% = x% : q% = y%+1 ENDCASE IF p% >= 0 IF p% < w% IF q% >= 0 IF q% < h% IF m&(p%,q%) < &80 THEN IF p% > x% IF m&(p%,q%) AND 1 EXIT FOR IF q% > y% IF m&(p%,q%) AND 2 EXIT FOR IF x% > p% IF m&(x%,y%) AND 1 EXIT FOR IF y% > q% IF m&(x%,y%) AND 2 EXIT FOR ENDIF NEXT IF i% < 4 THEN m&(p%,q%) OR= &80 s{(n%)}.x% = x% s{(n%)}.y% = y% n% += 1 ELSE IF n% > 0 THEN n% -= 1 p% = s{(n%)}.x% q% = s{(n%)}.y% ENDIF ENDIF LINE (x%+0.5)*s%,(y%+0.5)*s%,(p%+0.5)*s%,(q%+0.5)*s% x% = p% y% = q% UNTIL x%=dstx% AND y%=dsty% s{(n%)}.x% = x% s{(n%)}.y% = y% ENDPROC   DEF PROCgeneratemaze(RETURN m&(), w%, h%, s%) LOCAL x%, y% DIM m&(w%, h%) FOR y% = 0 TO h% LINE 0,y%*s%,w%*s%,y%*s% NEXT FOR x% = 0 TO w% LINE x%*s%,0,x%*s%,h%*s% NEXT GCOL 15 PROCcell(m&(), RND(w%)-1, y% = RND(h%)-1, w%, h%, s%) ENDPROC   DEF PROCcell(m&(), x%, y%, w%, h%, s%) LOCAL i%, p%, q%, r% m&(x%,y%) OR= &40 : REM Mark visited r% = RND(4) FOR i% = r% TO r%+3 CASE i% MOD 4 OF WHEN 0: p% = x%-1 : q% = y% WHEN 1: p% = x%+1 : q% = y% WHEN 2: p% = x% : q% = y%-1 WHEN 3: p% = x% : q% = y%+1 ENDCASE IF p% >= 0 IF p% < w% IF q% >= 0 IF q% < h% IF m&(p%,q%) < &40 THEN IF p% > x% m&(p%,q%) OR= 1 : LINE p%*s%,y%*s%+4,p%*s%,(y%+1)*s%-4 IF q% > y% m&(p%,q%) OR= 2 : LINE x%*s%+4,q%*s%,(x%+1)*s%-4,q%*s% IF x% > p% m&(x%,y%) OR= 1 : LINE x%*s%,y%*s%+4,x%*s%,(y%+1)*s%-4 IF y% > q% m&(x%,y%) OR= 2 : LINE x%*s%+4,y%*s%,(x%+1)*s%-4,y%*s% PROCcell(m&(), p%, q%, w%, h%, s%) ENDIF NEXT ENDPROC
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#AutoHotkey
AutoHotkey
 
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#FreeBASIC
FreeBASIC
' version 19-10-2016 ' translation of the (pseudo) code in RFC 1320 ' compile with: fbc -s console   Function MD4(test_str As String) As String   Dim As String message = test_str ' string are passed as ByRef   ' some macro's #Macro F(X, Y, Z) (((X) And (Y)) Or ((Not(X)) And (Z))) #EndMacro   #Macro G(X, Y, Z) (((X) And (Y)) Or (((X) And (Z)) Or ((Y) And (Z)))) #EndMacro   #Macro H(X, Y, Z) ((X) Xor (Y) Xor (Z)) #EndMacro   ' a little piece of inline asm to do a rotate left on a 32bit variable #Macro ROtate_Left(x, n) ' rotate left Asm rol dword Ptr [x], n End Asm #EndMacro   ' #Macro ROtate_left(x, n) ' x = x Shl n + x Shr (32 - n) ' #EndMacro   Dim As Long i Dim As String answer, s1   Dim As ULongInt l = Len(message) ' set the first bit after the message to 1 message = message + Chr(1 Shl 7) ' add one char to the length Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.   ' check if we have enough room for inserting the length If padding < 8 Then padding = padding + 64   message = message + String(padding, Chr(0)) ' adjust length Dim As ULong l1 = Len(message) ' new length   l = l * 8 ' orignal length in bits ' create ubyte ptr to point to l ( = length in bits) Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)   For i = 0 To 7 'copy length of message to the last 8 bytes message[l1 -8 + i] = ub_ptr[i] Next   ' unsigned 32bit integers only Dim As UInteger<32> AA, A = &H67452301 Dim As UInteger<32> BB, B = &Hefcdab89 Dim As UInteger<32> CC, C = &H98badcfe Dim As UInteger<32> DD, D = &H10325476   For i = 0 To (l1 -1) \ 64 ' split into 64 byte block   AA = A : BB = B : CC = C : DD = D   ' x point to 64 byte block inside the string message Dim As UInteger<32> Ptr x = Cast(UInteger<32> Ptr, @message[i*64])   ' round 1 A = A + F(B, C, D) + x[ 0] : ROtate_Left(A, 3) D = D + F(A, B, C) + x[ 1] : ROtate_Left(D, 7) C = C + F(D, A, B) + x[ 2] : ROtate_Left(C, 11) B = B + F(C, D, A) + x[ 3] : ROtate_Left(B, 19) A = A + F(B, C, D) + x[ 4] : ROtate_Left(A, 3) D = D + F(A, B, C) + x[ 5] : ROtate_Left(D, 7) C = C + F(D, A, B) + x[ 6] : ROtate_Left(C, 11) B = B + F(C, D, A) + x[ 7] : ROtate_Left(B, 19) A = A + F(B, C, D) + x[ 8] : ROtate_Left(A, 3) D = D + F(A, B, C) + x[ 9] : ROtate_Left(D, 7) C = C + F(D, A, B) + x[10] : ROtate_Left(C, 11) B = B + F(C, D, A) + x[11] : ROtate_Left(B, 19) A = A + F(B, C, D) + x[12] : ROtate_Left(A, 3) D = D + F(A, B, C) + x[13] : ROtate_Left(D, 7) C = C + F(D, A, B) + x[14] : ROtate_Left(C, 11) B = B + F(C, D, A) + x[15] : ROtate_Left(B, 19)   ' round 2 A = A + G(B, C, D) + x[ 0] + &H5A827999 : ROtate_Left(A, 3) D = D + G(A, B, C) + x[ 4] + &H5A827999 : ROtate_Left(D, 5) C = C + G(D, A, B) + x[ 8] + &H5A827999 : ROtate_Left(C, 9) B = B + G(C, D, A) + x[12] + &H5A827999 : ROtate_Left(B, 13) A = A + G(B, C, D) + x[ 1] + &H5A827999 : ROtate_Left(A, 3) D = D + G(A, B, C) + x[ 5] + &H5A827999 : ROtate_Left(D, 5) C = C + G(D, A, B) + x[ 9] + &H5A827999 : ROtate_Left(C, 9) B = B + G(C, D, A) + x[13] + &H5A827999 : ROtate_Left(B, 13) A = A + G(B, C, D) + x[ 2] + &H5A827999 : ROtate_Left(A, 3) D = D + G(A, B, C) + x[ 6] + &H5A827999 : ROtate_Left(D, 5) C = C + G(D, A, B) + x[10] + &H5A827999 : ROtate_Left(C, 9) B = B + G(C, D, A) + x[14] + &H5A827999 : ROtate_Left(B, 13) A = A + G(B, C, D) + x[ 3] + &H5A827999 : ROtate_Left(A, 3) D = D + G(A, B, C) + x[ 7] + &H5A827999 : ROtate_Left(D, 5) C = C + G(D, A, B) + x[11] + &H5A827999 : ROtate_Left(C, 9) B = B + G(C, D, A) + x[15] + &H5A827999 : ROtate_Left(B, 13)   ' round 3 A = A + H(B, C, D) + x[ 0] + &H6ED9EBA1 : ROtate_Left(A, 3) D = D + H(A, B, C) + x[ 8] + &H6ED9EBA1 : ROtate_Left(D, 9) C = C + H(D, A, B) + x[ 4] + &H6ED9EBA1 : ROtate_Left(C, 11) B = B + H(C, D, A) + x[12] + &H6ED9EBA1 : ROtate_Left(B, 15) A = A + H(B, C, D) + x[ 2] + &H6ED9EBA1 : ROtate_Left(A, 3) D = D + H(A, B, C) + x[10] + &H6ED9EBA1 : ROtate_Left(D, 9) C = C + H(D, A, B) + x[ 6] + &H6ED9EBA1 : ROtate_Left(C, 11) B = B + H(C, D, A) + x[14] + &H6ED9EBA1 : ROtate_Left(B, 15) A = A + H(B, C, D) + x[ 1] + &H6ED9EBA1 : ROtate_Left(A, 3) D = D + H(A, B, C) + x[ 9] + &H6ED9EBA1 : ROtate_Left(D, 9) C = C + H(D, A, B) + x[ 5] + &H6ED9EBA1 : ROtate_Left(C, 11) B = B + H(C, D, A) + x[13] + &H6ED9EBA1 : ROtate_Left(B, 15) A = A + H(B, C, D) + x[ 3] + &H6ED9EBA1 : ROtate_Left(A, 3) D = D + H(A, B, C) + x[11] + &H6ED9EBA1 : ROtate_Left(D, 9) C = C + H(D, A, B) + x[ 7] + &H6ED9EBA1 : ROtate_Left(C, 11) B = B + H(C, D, A) + x[15] + &H6ED9EBA1 : ROtate_Left(B, 15)   A += AA : B += BB : C += CC : D += DD   Next   ' convert A, B, C and D in hex, then add low order first s1 = Hex(A, 8) For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next s1 = Hex(B, 8) For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next s1 = Hex(C, 8) For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next s1 = Hex(D, 8) For i = 7 To 1 Step -2 : answer +=Mid(s1, i, 2) : Next   Return LCase(answer)   End Function   ' ------=< MAIN >=------   Dim As String test = "Rosetta Code" Print Print test; " => "; MD4(test)     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Python
Python
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2]   >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer))     middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#Arturo
Arturo
print digest "The quick brown fox jumped over the lazy dog's back"
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#Tcl
Tcl
proc select {prompt choices} { set nc [llength $choices] if {!$nc} { return "" } set numWidth [string length $nc] while true { set i 0 foreach s $choices { puts [format "  %-*d: %s" $numWidth [incr i] $s] } puts -nonewline "$prompt: " flush stdout gets stdin num if {[string is int -strict $num] && $num >= 1 && $num <= $nc} { incr num -1 return [lindex $choices $num] } } }
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#FreeBASIC
FreeBASIC
  Dim As Integer l(100), a, b, c, n For a = 0 To 100/6 For b = 0 To 100/9 For c = 0 To 100/20 n = a*6 + b*9 + c*20 If n <= 100 Then l(n) = true Next c Next b Next a For n = 100 To 1 Step -1 If l(n) = false Then Print "El mayor número que no sea McNugget es:"; n: Exit For Next n End  
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#11l
11l
-V UL = ‘╔’ UC = ‘╦’ UR = ‘╗’ LL = ‘╚’ LC = ‘╩’ LR = ‘╝’ HB = ‘═’ VB = ‘║’   Mayan = [‘ ’, ‘ ∙ ’, ‘ ∙∙ ’, ‘∙∙∙ ’, ‘∙∙∙∙’]   M0 = ‘ @ ’ M5 = ‘────’   F toBase20(=n) V result = [n % 20] n I/= 20 L n != 0 result [+]= n % 20 n I/= 20 R reversed(result)   F toMayanNumeral(=d) V result = [Mayan[0], Mayan[0], Mayan[0], Mayan[0]] I d == 0 result[3] = :M0 R result   L(i) (3..0).step(-1) I d >= 5 result[i] = :M5 d -= 5 E result[i] = Mayan[d] L.break   R result   F draw(mayans) V idx = mayans.len - 1   print(:UL, end' ‘’) L(i) 0 .. idx print(:HB * 4, end' ‘’) I i < idx print(:UC, end' ‘’) E print(:UR)   L(i) 1..4 print(:VB, end' ‘’) L(j) 0 .. idx print(mayans[j][i - 1]‘’:VB, end' ‘’) print()   print(:LL, end' ‘’) L(i) 0 .. idx print(:HB * 4, end' ‘’) I i < idx print(:LC, end' ‘’) E print(:LR)   L(n) [4005, 8017, 326205, 886205, 1081439556] print(‘Converting ’n‘ to Mayan:’) V digits = toBase20(n) V mayans = digits.map(d -> toMayanNumeral(d)) draw(mayans) print()
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#C
C
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512, CELL_SIZE = 8;   //-------------------------------------------------------------------------------------------------- enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 };   //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h;   return true; }   void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); }   void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap );   DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; //-------------------------------------------------------------------------------------------------- class mazeGenerator { public: mazeGenerator() { _world = 0; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.setPenColor( RGB( 0, 255, 0 ) ); }   ~mazeGenerator() { killArray(); }   BYTE* getMaze() const { return _world; }   void create( int side ) { _s = side; generate(); }   private: void generate() { killArray(); _world = new BYTE[_s * _s]; ZeroMemory( _world, _s * _s ); _ptX = rand() % _s; _ptY = rand() % _s; carve(); }   void carve() { while( true ) { int d = getDirection(); if( d < NOR ) return;   switch( d ) { case NOR: _world[_ptX + _s * _ptY] |= NOR; _ptY--; _world[_ptX + _s * _ptY] = SOU | SOU << 4; break; case EAS: _world[_ptX + _s * _ptY] |= EAS; _ptX++; _world[_ptX + _s * _ptY] = WES | WES << 4; break; case SOU: _world[_ptX + _s * _ptY] |= SOU; _ptY++; _world[_ptX + _s * _ptY] = NOR | NOR << 4; break; case WES: _world[_ptX + _s * _ptY] |= WES; _ptX--; _world[_ptX + _s * _ptY] = EAS | EAS << 4; } } }   int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDir( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; } d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; if( !d ) return -1; switch( d ) { case NOR: _ptY--; break; case EAS: _ptX++; break; case SOU: _ptY++; break; case WES: _ptX--; break; }   d = 1 << rand() % 4; } }   bool testDir( int d ) { switch( d ) { case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); } return false; }   void killArray() { if( _world ) delete [] _world; }   BYTE* _world; int _s, _ptX, _ptY; myBitmap _bmp; }; //-------------------------------------------------------------------------------------------------- class mazeSolver { public: mazeSolver() { _bmp.create( BMP_SIZE, BMP_SIZE ); _pts = 0; }   ~mazeSolver() { killPoints(); }   void solveIt( BYTE* maze, int size, int sX, int sY, int eX, int eY ) { _lastDir = NONE; _world = maze; _s = size; _sx = sX; _sy = sY; _ex = eX; _ey = eY;   for( int y = 0; y < _s; y++ ) for( int x = 0; x < _s; x++ ) _world[x + _s * y] &= 0x0f;   _world[_sx + _s * _sy] |= NOR << 4;   killPoints(); _pts = new BYTE[_s * _s]; ZeroMemory( _pts, _s * _s );   findTheWay();   _sx = sX; _sy = sY; display(); }   private: int invert( int d ) { switch( d ) { case NOR: return SOU; case SOU: return NOR; case WES: return EAS; case EAS: return WES; } return NONE; }   void updatePosition( int d ) { switch( d ) { case NOR: _sy--; break; case EAS: _sx++; break; case SOU: _sy++; break; case WES: _sx--; } }   void findTheWay() { while( true ) { int d = getDirection(); if( d < NOR ) return; _lastDir = invert( d ); _world[_sx + _s * _sy] |= d; _pts[_sx + _s * _sy] = d; updatePosition( d ); if( _sx == _ex && _sy == _ey ) return; _world[_sx + _s * _sy] |= _lastDir << 4; } }   int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDirection( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; }   d = ( _world[_sx + _s * _sy] & 0xf0 ) >> 4; if( !d ) return -1; _pts[_sx + _s * _sy] = 0; updatePosition( d ); _lastDir = invert( d ); d = 1 << rand() % 4; } }   bool testDirection( int d ) { if( d == _lastDir || !( _world[_sx + _s * _sy] & d ) ) return false; switch( d ) { case NOR: return _sy - 1 > -1 && !( _world[_sx + _s * ( _sy - 1 )] & 0xf0 ); case EAS: return _sx + 1 < _s && !( _world[_sx + 1 + _s * _sy] & 0xf0 ); case SOU: return _sy + 1 < _s && !( _world[_sx + _s * ( _sy + 1 )] & 0xf0 ); case WES: return _sx - 1 > -1 && !( _world[_sx - 1 + _s * _sy] & 0xf0 ); } return false; }   void display() { _bmp.setPenColor( RGB( 0, 255, 0 ) ); _bmp.clear(); HDC dc = _bmp.getDC(); for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE b = _world[x + yy]; int nx = x * CELL_SIZE, ny = y * CELL_SIZE;   if( !( b & NOR ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny ); } if( !( b & EAS ) ) { MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); } if( !( b & SOU ) ) { MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); } if( !( b & WES ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx, ny + CELL_SIZE + 1 ); } } }   drawEndPoints( dc ); _bmp.setPenColor( RGB( 255, 0, 0 ) );   for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE d = _pts[x + yy]; if( !d ) continue;   int nx = x * CELL_SIZE + 4, ny = y * CELL_SIZE + 4;   MoveToEx( dc, nx, ny, NULL ); switch( d ) { case NOR: LineTo( dc, nx, ny - CELL_SIZE - 1 ); break; case EAS: LineTo( dc, nx + CELL_SIZE + 1, ny ); break; case SOU: LineTo( dc, nx, ny + CELL_SIZE + 1 ); break; case WES: LineTo( dc, nx - CELL_SIZE - 1, ny ); break; } } }   _bmp.saveBitmap( "f:\\rc\\maze_s.bmp" ); BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); }   void drawEndPoints( HDC dc ) { RECT rc; int x = 1 + _sx * CELL_SIZE, y = 1 + _sy * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); x = 1 + _ex * CELL_SIZE, y = 1 + _ey * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); }   void killPoints() { if( _pts ) delete [] _pts; }   BYTE* _world, *_pts; int _s, _sx, _sy, _ex, _ey, _lastDir; myBitmap _bmp; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() );   mazeGenerator mg; mazeSolver ms; int s; while( true ) { cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( !( s & 1 ) ) s++; if( s >= 3 ) { mg.create( s ); int sx, sy, ex, ey; while( true ) { sx = rand() % s; sy = rand() % s; ex = rand() % s; ey = rand() % s; if( ex != sx || ey != sy ) break; } ms.solveIt( mg.getMaze(), s, sx, sy, ex, ey ); cout << endl; } system( "pause" ); system( "cls" ); } return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#AWK
AWK
  # syntax: GAWK -f MAXIMUM_TRIANGLE_PATH_SUM.AWK filename(s) { printf("%s\n",$0) cols[FNR] = NF for (i=1; i<=NF; i++) { arr[FNR][i] = $i } } ENDFILE { for (row=FNR-1; row>0; row--) { for (col=1; col<=cols[row]; col++) { arr[row][col] += max(arr[row+1][col],arr[row+1][col+1]) } } printf("%d using %s\n\n",arr[1][1],FILENAME) delete arr delete cols } END { exit(0) } function max(x,y) { return((x > y) ? x : y) }  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Go
Go
package main   import ( "golang.org/x/crypto/md4" "fmt" )   func main() { h := md4.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Quackery
Quackery
[ 1 & not ] is even ( n --> b )   [ over size - space swap of swap join ] is justify ( $ n --> $ )   [ abs number$ dup size dup 3 < iff [ 2drop $ "too few digits" ] done dup even iff [ 2drop $ "even digit count" ] done dup 3 = iff drop done 3 - 2 / tuck split nip swap negate split drop ] is middle3 ( n --> $ )   ' [ 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 ]   witheach [ dup number$ 9 justify echo$ say " --> " middle3 echo$ cr ]
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program MD5.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ LGHASH, 16 // result length .equ ZWORKSIZE, 1000 // work area size   /*******************************************/ /* Structures */ /********************************************/ /* example structure variables */ .struct 0 var_a: // a .struct var_a + 4 var_b: // b .struct var_b + 4 var_c: // c .struct var_c + 4 var_d: // d .struct var_d + 4 /*********************************/ /* Initialized data */ /*********************************/ .data szMessTest1: .asciz "abc" szMessTest4: .asciz "12345678901234567890123456789012345678901234567890123456789012345678901234567890" szMessTest2: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" szMessTest3: .asciz "abcdefghijklmnopqrstuvwxyz" szMessFinPgm: .asciz "Program End ok.\n" szMessResult: .asciz "Result for " szMessResult1: .asciz " => " szMessSizeError: .asciz "\033[31mWork area too small !! \033[0m \n" szCarriageReturn: .asciz "\n"   .align 4 /* array constantes K */ tbConstK: .int 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee .int 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501 .int 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be .int 0x6b901122,0xfd987193,0xa679438e,0x49b40821 .int 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa .int 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8 .int 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed .int 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a .int 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c .int 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70 .int 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05 .int 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665 .int 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039 .int 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1 .int 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1 .int 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391   /* array rotation coef R */ tbRotaR: .int 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22 .int 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20 .int 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23 .int 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21   tbConstH: .int 0x67452301 // H0 .int 0xEFCDAB89 // H1 .int 0x98BADCFE // H2 .int 0x10325476 // H3   /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 sZoneConv: .skip 24 tbH: .skip 4 * 4 @ 4 variables H tbabcd: .skip 4 * 4 @ 4 variables a b c d sZoneTrav: .skip 1000 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   ldr r0,iAdrszMessTest1 bl computeExemple   ldr r0,iAdrszMessTest2 bl computeExemple   ldr r0,iAdrszMessTest3 bl computeExemple   ldr r0,iAdrszMessTest4 bl computeExemple   ldr r0,iAdrszMessFinPgm bl affichageMess @ display message     100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrszMessResult: .int szMessResult iAdrszMessResult1: .int szMessResult1 iAdrszMessTest1: .int szMessTest1 iAdrszMessTest2: .int szMessTest2 iAdrszMessTest3: .int szMessTest3 iAdrszMessTest4: .int szMessTest4 iAdrsZoneTrav: .int sZoneTrav iAdrsZoneConv: .int sZoneConv iAdrszMessFinPgm: .int szMessFinPgm iAdrszMessSizeError: .int szMessSizeError /***********************************************/ /* compute exemple */ /***********************************************/ /* r0 contains the address of the message */ computeExemple: push {r1,lr} @ save registres mov r1,r0 bl computeMD5 @ call routine MD5   ldr r0,iAdrszMessResult bl affichageMess mov r0,r1 bl affichageMess ldr r0,iAdrszMessResult1 bl affichageMess ldr r0, iAdrtbH bl displayMD5   100: pop {r1,pc} @ restaur registers   /******************************************************************/ /* compute MD5 */ /******************************************************************/ /* r0 contains the address of the message */ computeMD5: push {r1-r12,lr} @ save registres ldr r1,iAdrsZoneTrav mov r2,#0 @ counter length 1: @ copy string in work area cmp r2,#ZWORKSIZE @ maxi ? bge 99f @ error ldrb r3,[r0,r2] strb r3,[r1,r2] cmp r3,#0 addne r2,r2,#1 bne 1b lsl r6,r2,#3 @ initial message length in bits mov r3,#0b10000000 @ add bit 1 at end of string strb r3,[r1,r2] add r2,r2,#1 @ length in bytes lsl r4,r2,#3 @ length in bits mov r3,#0 2: lsr r5,r2,#6 lsl r5,r5,#6 sub r5,r2,r5 cmp r5,#56 beq 3f @ yes -> end add strb r3,[r1,r2] @ add zero at message end add r2,#1 @ increment lenght bytes add r4,#8 @ increment length in bits b 2b 3: str r6,[r1,r2] @ and store length at end add r5,r2,#4 str r3,[r1,r5] @ store zero in hight bits for 64 bits   ldr r7,iAdrtbConstH @ constantes H address ldr r4,iAdrtbH @ start area H mov r5,#0 4: @ init array H with start constantes ldr r6,[r7,r5,lsl #2] @ load constante str r6,[r4,r5,lsl #2] @ and store add r5,r5,#1 cmp r5,#4 blt 4b @ split into block of 64 bytes add r2,#4 @ TODO : à revoir lsr r4,r2,#6 @ blocks number   ldr r0,iAdrtbH @ variables H ldr r1,iAdrsZoneTrav ldr r5,iAdrtbConstK ldr r3,iAdrtbRotaR ldr r8,iAdrtbabcd mov r7,#0 @ n° de block et r1 contient l adresse zone de travail 5: @ begin loop of each block of 64 bytes add r2,r1,r7,lsl #6 @ compute block begin indice * 4 * 16 mov r6,#0 @ indice t /* COMPUTING THE MESSAGE DIGEST */ /* r0 variables H address */ /* r1 work area */ /* r2 block work area begin address */ /* r3 address constantes rotate */ /* r4 block number */ /* r5 constance K address */ /* r6 counter t */ /* r7 block counter */ /* r8 addresse variables a b c d */ @ init variable a b c d with variables H mov r10,#0 6: @ loop init ldr r9,[r0,r10,lsl #2] @ variables H str r9,[r8,r10,lsl #2] @ variables a b c d add r10,r10,#1 cmp r10,#4 blt 6b   7: @ loop begin cmp r6,#15 bgt 8f @ cas 1 f := (b et c) ou ((non b) et d) @ g := i ldr r9,[r8,#var_b] ldr r10,[r8,#var_c] and r12,r10,r9 mvn r9,r9 ldr r10,[r8,#var_d] and r11,r9,r10 orr r12,r12,r11 @ f mov r9,r6 @ g b 11f 8: cmp r6,#31 bgt 9f @ f := (d et b) ou ((non d) et c) @ g := (5×i + 1) mod 16 ldr r9,[r8,#var_b] ldr r10,[r8,#var_d] and r12,r10,r9 mvn r10,r10 ldr r9,[r8,#var_c] and r11,r9,r10 orr r12,r12,r11 @ f mov r9,#5 mul r9,r6,r9 add r9,r9,#1 lsr r10,r9,#4 lsl r10,r10,#4 sub r9,r9,r10 @ g   b 11f 9: cmp r6,#47 bgt 10f @ f := b xor c xor d @ g := (3×i + 5) mod 16 ldr r9,[r8,#var_b] ldr r10,[r8,#var_c] eor r12,r10,r9 ldr r10,[r8,#var_d] eor r12,r12,r10 @ f mov r9,#3 mul r9,r6,r9 add r9,r9,#5 lsr r10,r9,#4 lsl r10,r10,#4 sub r9,r9,r10 @ g b 11f 10: @ f := c xor (b ou (non d)) @ g := (7×i) mod 16 ldr r10,[r8,#var_d] mvn r12,r10 ldr r10,[r8,#var_b] orr r12,r12,r10 ldr r10,[r8,#var_c] eor r12,r12,r10 @ f mov r9,#7 mul r9,r6,r9 lsr r10,r9,#4 lsl r10,r10,#4 sub r9,r9,r10 @ g   11: ldr r10,[r8,#var_d] mov r11,r10 @ save old d ldr r10,[r8,#var_c] str r10,[r8,#var_d] @ new d = c ldr r10,[r8,#var_b] str r10,[r8,#var_c] @ new c = b ldr r10,[r8,#var_a] add r12,r12,r10 @ a + f ldr r10,[r2,r9,lsl #2] add r12,r12,r10 @ + valeur bloc g ldr r10,[r5,r6,lsl #2] add r12,r12,r10 @ + valeur constante K de i ldr r10,[r3,r6,lsl #2] @ rotate left value rsb r10,r10,#32 @ compute right rotate ror r12,r12,r10 ldr r10,[r8,#var_b] add r12,r12,r10 str r12,[r8,#var_b] @ new b str r11,[r8,#var_a] @ new a = old d   add r6,r6,#1 cmp r6,#63 ble 7b @ maj area H ldr r10,[r0] @ H0 ldr r11,[r8,#var_a] add r10,r10,r11 @ + a str r10,[r0] ldr r10,[r0,#4] @ H1 ldr r11,[r8,#var_b] add r10,r10,r11 @ + b str r10,[r0,#4] ldr r10,[r0,#8] @ H2 ldr r11,[r8,#var_c] add r10,r10,r11 @ + c str r10,[r0,#8] ldr r10,[r0,#12] @ H3 ldr r11,[r8,#var_d] add r10,r10,r11 @ + d str r10,[r0,#12]   @ loop other block add r7,r7,#1 @ increment block cmp r7,r4 @ maxi ? ble 5b   mov r9,#0 @ reverse bytes loop 12: ldr r10,[r0,r9,lsl #2] rev r10,r10 @ reverse bytes str r10,[r0,r9,lsl #2] add r9,r9,#1 cmp r9,#LGHASH / 4 blt 12b mov r0,#0 @ routine OK b 100f 99: @ size error ldr r0,iAdrszMessSizeError bl affichageMess mov r0,#-1 @ error routine   100: pop {r1-r12,pc} @ restaur registers iAdrtbConstH: .int tbConstH iAdrtbConstK: .int tbConstK iAdrtbRotaR: .int tbRotaR iAdrtbH: .int tbH iAdrtbabcd: .int tbabcd   /*************************************************/ /* display hash MD5 */ /*************************************************/ /* r0 contains the address of hash */ displayMD5: push {r1-r3,lr} @ save registres mov r3,r0 mov r2,#0 1: ldr r0,[r3,r2,lsl #2] @ load 4 bytes ldr r1,iAdrsZoneConv bl conversion16 @ conversion hexa ldr r0,iAdrsZoneConv bl affichageMess add r2,r2,#1 cmp r2,#LGHASH / 4 blt 1b @ and loop ldr r0,iAdrszCarriageReturn bl affichageMess @ display message 100: pop {r1-r3,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#TI-83_BASIC
TI-83 BASIC
Input "",Str1 //input as ITEM 1:ITEM 2:ITEM 3... ":"+Str1+":→Str1 Σ(sub(Str1,X,1)=":",X,1,length(Str1→X 0→dim(L₁ For(Z,2,length(Str1 inString(Str1,":",Z-1 1+Ans+.01inString(Str1,":",Ans+1→L₁(1+dim(L₁ ᴇ2fPart(Ans→Z End seq(iPart(L₁(X))+.01(ᴇ2fPart(L₁(X))-iPart(L₁(X))),X,1,dim(L₁→L₁ Repeat A>0 and A<X ClrHome For(Z,1,dim(L₁ Disp "  :"+sub(Str1,iPart(L₁(Z)),ᴇ2fPart(L₁(Z Output(min(7,Z),1+(Z≤7),Z End Input A End Disp sub(Str1,iPart(L₁(A)),ᴇ2fPart(L₁(A
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Go
Go
package main   import "fmt"   func mcnugget(limit int) { sv := make([]bool, limit+1) // all false by default for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } }   func main() { mcnugget(100) }
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#8080_Assembly
8080 Assembly
putch: equ 2 puts: equ 9 org 100h lxi h,80h ; Get length of command line input mov a,m cpi 2 rc ; If no input, stop add l mov l,a ; Go to end of numbers mov c,l ; C = end of numbers inx h mvi m,0FFh ; Terminate digit sequence with FFh dcx h sub0: mov a,m cpi 32 ; When space reached, we're at the beginning jz to20 sui '0' ; Subtract '0' from each digit and make sure rc ; they are all valid cpi 10 rnc mov m,a dcx h jmp sub0 to20: mov a,c ; Calculate amount of numbers sui 81h mov c,a to20l: mov e,c ; E = digit counter mvi l,82h ; Start at beginning div2: mov a,m ; Grab digit jnc $+5 ; If carry, add ten adi 10 rar ; Divide by two mov m,a ; Write back inx h dcr e jnz div2 ; Keep going dcx h ; For the last number we want ral ; to keep the carry mov m,a ; This digit is now base-20 dcr c ; One fewer digit left to do jnz to20l mvi l,81h ; Find start and end of numbers start: inx h mov a,m ana a jz start mov b,l ; B = start inr a ; If number is zero, output nothing rz nend: inx h mov a,m inr a jnz nend mov a,l ; A = end sub b mov c,a ; C = amount call edge mvi d,3 ; D=line line: push b ; Save start and amount mov l,b ; HL = first digit mvi h,0 num: call dline ; Print line for digit inx h ; Next digit dcr c jnz num push d ; Save line number lxi d,dn ; Print end of line call print pop d ; Restore variables pop b dcr d jp line ; Print next line edge: push b ; Print edge (top or bottom) edge_l: push b ; Keep counter lxi d,edges call print pop b dcr c jnz edge_l lxi d,edgen call print pop b ret dline: push h ; Print line for digit (D'th from bottom) push d push b mov a,m ora d ; Line and number both 0? jnz $+9 lxi d,dz ; Then print line with @ jmp dnum mov a,d ; 5 * line add a add a add d mov e,a mov a,m ; A -= 5 * line sub e lxi d,d0 ; If <0, empty jm dnum cpi 5 jc $+9 lxi d,d5 ; If >=5, ---- jmp dnum add a ; Otherwise, d[n] mov l,a add a add l mov l,a mvi h,0 dad d xchg dnum: call print pop b pop d pop h ret print: mvi c,puts jmp 5 edges: db '+----$' edgen: db '+',13,10,'$' dz: db '| @ $' d0: db '| $| . $| .. $|... $|....$' d5: db '|----$' dn: db '|',13,10,'$'
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#APL
APL
mayan←{ ds←6 4⍴' . .. ... ....────' d←{ ⍵=0:4 4⍴¯14↑'Θ' ds[1+5⌊0⌈⍵-15 10 5 0;] }¨20(⊥⍣¯1)⍵ top←'╔',(1↓∊(≢d)⍴⊂'╦════'),'╗' btm←'╚',(1↓∊(≢d)⍴⊂'╩════'),'╝' top⍪((⊃,/'║',¨d),'║')⍪btm }
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512, CELL_SIZE = 8;   //-------------------------------------------------------------------------------------------------- enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 };   //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h;   return true; }   void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); }   void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap );   DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; //-------------------------------------------------------------------------------------------------- class mazeGenerator { public: mazeGenerator() { _world = 0; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.setPenColor( RGB( 0, 255, 0 ) ); }   ~mazeGenerator() { killArray(); }   BYTE* getMaze() const { return _world; }   void create( int side ) { _s = side; generate(); }   private: void generate() { killArray(); _world = new BYTE[_s * _s]; ZeroMemory( _world, _s * _s ); _ptX = rand() % _s; _ptY = rand() % _s; carve(); }   void carve() { while( true ) { int d = getDirection(); if( d < NOR ) return;   switch( d ) { case NOR: _world[_ptX + _s * _ptY] |= NOR; _ptY--; _world[_ptX + _s * _ptY] = SOU | SOU << 4; break; case EAS: _world[_ptX + _s * _ptY] |= EAS; _ptX++; _world[_ptX + _s * _ptY] = WES | WES << 4; break; case SOU: _world[_ptX + _s * _ptY] |= SOU; _ptY++; _world[_ptX + _s * _ptY] = NOR | NOR << 4; break; case WES: _world[_ptX + _s * _ptY] |= WES; _ptX--; _world[_ptX + _s * _ptY] = EAS | EAS << 4; } } }   int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDir( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; } d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; if( !d ) return -1; switch( d ) { case NOR: _ptY--; break; case EAS: _ptX++; break; case SOU: _ptY++; break; case WES: _ptX--; break; }   d = 1 << rand() % 4; } }   bool testDir( int d ) { switch( d ) { case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); } return false; }   void killArray() { if( _world ) delete [] _world; }   BYTE* _world; int _s, _ptX, _ptY; myBitmap _bmp; }; //-------------------------------------------------------------------------------------------------- class mazeSolver { public: mazeSolver() { _bmp.create( BMP_SIZE, BMP_SIZE ); _pts = 0; }   ~mazeSolver() { killPoints(); }   void solveIt( BYTE* maze, int size, int sX, int sY, int eX, int eY ) { _lastDir = NONE; _world = maze; _s = size; _sx = sX; _sy = sY; _ex = eX; _ey = eY;   for( int y = 0; y < _s; y++ ) for( int x = 0; x < _s; x++ ) _world[x + _s * y] &= 0x0f;   _world[_sx + _s * _sy] |= NOR << 4;   killPoints(); _pts = new BYTE[_s * _s]; ZeroMemory( _pts, _s * _s );   findTheWay();   _sx = sX; _sy = sY; display(); }   private: int invert( int d ) { switch( d ) { case NOR: return SOU; case SOU: return NOR; case WES: return EAS; case EAS: return WES; } return NONE; }   void updatePosition( int d ) { switch( d ) { case NOR: _sy--; break; case EAS: _sx++; break; case SOU: _sy++; break; case WES: _sx--; } }   void findTheWay() { while( true ) { int d = getDirection(); if( d < NOR ) return; _lastDir = invert( d ); _world[_sx + _s * _sy] |= d; _pts[_sx + _s * _sy] = d; updatePosition( d ); if( _sx == _ex && _sy == _ey ) return; _world[_sx + _s * _sy] |= _lastDir << 4; } }   int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDirection( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; }   d = ( _world[_sx + _s * _sy] & 0xf0 ) >> 4; if( !d ) return -1; _pts[_sx + _s * _sy] = 0; updatePosition( d ); _lastDir = invert( d ); d = 1 << rand() % 4; } }   bool testDirection( int d ) { if( d == _lastDir || !( _world[_sx + _s * _sy] & d ) ) return false; switch( d ) { case NOR: return _sy - 1 > -1 && !( _world[_sx + _s * ( _sy - 1 )] & 0xf0 ); case EAS: return _sx + 1 < _s && !( _world[_sx + 1 + _s * _sy] & 0xf0 ); case SOU: return _sy + 1 < _s && !( _world[_sx + _s * ( _sy + 1 )] & 0xf0 ); case WES: return _sx - 1 > -1 && !( _world[_sx - 1 + _s * _sy] & 0xf0 ); } return false; }   void display() { _bmp.setPenColor( RGB( 0, 255, 0 ) ); _bmp.clear(); HDC dc = _bmp.getDC(); for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE b = _world[x + yy]; int nx = x * CELL_SIZE, ny = y * CELL_SIZE;   if( !( b & NOR ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny ); } if( !( b & EAS ) ) { MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); } if( !( b & SOU ) ) { MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); } if( !( b & WES ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx, ny + CELL_SIZE + 1 ); } } }   drawEndPoints( dc ); _bmp.setPenColor( RGB( 255, 0, 0 ) );   for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE d = _pts[x + yy]; if( !d ) continue;   int nx = x * CELL_SIZE + 4, ny = y * CELL_SIZE + 4;   MoveToEx( dc, nx, ny, NULL ); switch( d ) { case NOR: LineTo( dc, nx, ny - CELL_SIZE - 1 ); break; case EAS: LineTo( dc, nx + CELL_SIZE + 1, ny ); break; case SOU: LineTo( dc, nx, ny + CELL_SIZE + 1 ); break; case WES: LineTo( dc, nx - CELL_SIZE - 1, ny ); break; } } }   _bmp.saveBitmap( "f:\\rc\\maze_s.bmp" ); BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); }   void drawEndPoints( HDC dc ) { RECT rc; int x = 1 + _sx * CELL_SIZE, y = 1 + _sy * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); x = 1 + _ex * CELL_SIZE, y = 1 + _ey * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); }   void killPoints() { if( _pts ) delete [] _pts; }   BYTE* _world, *_pts; int _s, _sx, _sy, _ex, _ey, _lastDir; myBitmap _bmp; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() );   mazeGenerator mg; mazeSolver ms; int s; while( true ) { cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( !( s & 1 ) ) s++; if( s >= 3 ) { mg.create( s ); int sx, sy, ex, ey; while( true ) { sx = rand() % s; sy = rand() % s; ex = rand() % s; ey = rand() % s; if( ex != sx || ey != sy ) break; } ms.solveIt( mg.getMaze(), s, sx, sy, ex, ey ); cout << endl; } system( "pause" ); system( "cls" ); } return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#Bracmat
Bracmat
( " 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 "  : ?triangle & ( max = a b . !arg:(?a.?b)&(!a:>!b|!b) ) & 0:?accumulator & whl ' ( @(!triangle:?row (\n|\r) ?triangle) & :?newaccumulator & 0:?first & whl ' ( @(!row:? #%?n (" " ?row|:?row)) & !accumulator:#%?second ?accumulator & !newaccumulator max$(!first.!second)+!n:?newaccumulator & !second:?first ) & !newaccumulator 0:?accumulator ) & ( -1:?Max &  !accumulator  : ? (%@:>!Max:?Max&~) ? | out$!Max ) )
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#Haskell
Haskell
#!/usr/bin/env runhaskell   import Data.ByteString.Char8 (pack) import System.Environment (getArgs) import Crypto.Hash   main :: IO () main = print . md4 . pack . unwords =<< getArgs where md4 x = hash x :: Digest MD4
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Racket
Racket
#lang racket (define (middle x) (cond [(negative? x) (middle (- x))] [(< x 100) "error: number too small"] [else (define s (number->string x)) (define l (string-length s)) (cond [(even? l) "error: number has even length"] [else (define i (quotient l 2)) (substring s (- i 1) (+ i 2))])]))   (map middle (list 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345)) (map middle (list 1 2 -1 -10 2002 -2002 0))
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#AutoHotkey
AutoHotkey
data := "abc" MsgBox % MD5(data,StrLen(data)) ; 900150983cd24fb0d6963f7d28e17f72   MD5( ByRef V, L=0 ) { VarSetCapacity( MD5_CTX,104,0 ), DllCall( "advapi32\MD5Init", Str,MD5_CTX ) DllCall( "advapi32\MD5Update", Str,MD5_CTX, Str,V, UInt,L ? L : VarSetCapacity(V) ) DllCall( "advapi32\MD5Final", Str,MD5_CTX ) Loop % StrLen( Hex:="123456789ABCDEF0" ) N := NumGet( MD5_CTX,87+A_Index,"Char"), MD5 .= SubStr(Hex,N>>4,1) . SubStr(Hex,N&15,1) Return MD5 }  
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#True_BASIC
True BASIC
DIM menu$(4) MAT READ menu$ DATA "fee fie", "huff and puff", "mirror mirror", "tick tock"   FUNCTION sel$(choices$()) IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN LET sel$ = "" LET ret$ = "" DO FOR i = LBOUND(choices$) TO UBOUND(choices$) PRINT i; ": "; choices$(i) NEXT i PRINT prompt$; INPUT index IF index <= UBOUND(choices$) AND index >= LBOUND(choices$) THEN LET ret$ = choices$(index) LOOP WHILE ret$ = "" LET sel$ = ret$ END FUNCTION   PRINT sel$(menu$()) END
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#Haskell
Haskell
import Data.Set (Set, fromList, member)   gaps :: [Int] gaps = dropWhile (`member` mcNuggets) [100,99 .. 1]   mcNuggets :: Set Int mcNuggets = let size = enumFromTo 0 . quot 100 in fromList $ size 6 >>= \x -> size 9 >>= \y -> size 20 >>= \z -> let v = sum [6 * x, 9 * y, 20 * z] in [ v | 101 > v ]   main :: IO () main = print $ case gaps of x:_ -> show x [] -> "No unreachable quantities found ..."
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and readability,   and to conserve screen space (when showing the output) on this task page. Mayan numerals Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this task will be using the "vertical" format   (as displayed below).   Using the vertical format makes it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (.) and hyphen (-);     (however, round bullets (•) and long dashes (─) make a better presentation on Rosetta Code). Furthermore, each Mayan numeral   (for this task)   is to be displayed as a cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers. Mayan numerals added to Unicode Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code task will be constructing the glyphs with "simple" characters and/or ASCII art. The "zero" glyph The Mayan numbering system has the concept of   zero,   and should be shown by a glyph that represents an upside─down (sea) shell,   or an egg.   The Greek letter theta   (Θ)   can be used   (which more─or─less, looks like an egg).   A   commercial at   symbol   (@)   could make a poor substitute. Mayan glyphs (constructed) The Mayan numbering system is a   [vigesimal (base 20)]   positional numeral system. The Mayan numerals   (and some random numbers)   shown in the   vertical   format would be shown as ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙ ║ ║ ║ ║ 1──► ║ ║ 11──► ║────║ 21──► ║ ║ ║ ║ ∙ ║ ║────║ ║ ∙ ║ ∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ∙∙ ║ ║ ║ ║ 2──► ║ ║ 12──► ║────║ 22──► ║ ║ ║ ║ ∙∙ ║ ║────║ ║ ∙ ║ ∙∙ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙ ║ ║ ║ ║ 3──► ║ ║ 13──► ║────║ 40──► ║ ║ ║ ║∙∙∙ ║ ║────║ ║ ∙∙ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║∙∙∙∙║ ║ ║ ║ 4──► ║ ║ 14──► ║────║ 80──► ║ ║ ║ ║∙∙∙∙║ ║────║ ║∙∙∙∙║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 5──► ║ ║ 15──► ║────║ 90──► ║ ║────║ ║────║ ║────║ ║∙∙∙∙║────║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 6──► ║ ∙ ║ 16──► ║────║ 100──► ║ ║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║ ∙∙ ║ ║ ║ ║ ║ ║ ║────║ ║ ║ ║ 7──► ║ ∙∙ ║ 17──► ║────║ 200──► ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╗ ║ ║ ║∙∙∙ ║ ║ ║ ║ ║ ║ ║────║ 300──► ║────║ ║ 8──► ║∙∙∙ ║ 18──► ║────║ ║────║ ║ ║────║ ║────║ ║────║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╝ ╔════╗ ╔════╗ ╔════╦════╦════╗ ║ ║ ║∙∙∙∙║ ║ ║ ║ ║ ║ ║ ║────║ 400──► ║ ║ ║ ║ 9──► ║∙∙∙∙║ 19──► ║────║ ║ ║ ║ ║ ║────║ ║────║ ║ ∙ ║ Θ ║ Θ ║ ╚════╝ ╚════╝ ╚════╩════╩════╝ ╔════╗ ╔════╦════╗ ╔════╦════╦════╦════╗ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ 10──► ║────║ 20──► ║ ║ ║ 16,000──► ║ ║ ║ ║ ║ ║────║ ║ ∙ ║ Θ ║ ║ ∙∙ ║ Θ ║ Θ ║ Θ ║ ╚════╝ ╚════╩════╝ ╚════╩════╩════╩════╝ Note that the Mayan numeral   13   in   horizontal   format would be shown as: ╔════╗ ║ ││║ ║ ∙││║ 13──► ║ ∙││║ ◄─── this glyph form won't be used in this Rosetta Code task. ║ ∙││║ ╚════╝ Other forms of cartouches (boxes) can be used for this task. Task requirements   convert the following decimal numbers to Mayan numbers:       4,005       8,017   326,205   886,205   show a   unique   interesting/pretty/unusual/intriguing/odd/amusing/weird   Mayan number   show all output here Related tasks   Roman numerals/Encode   ─── convert numeric values into Roman numerals   Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers See also   The Wikipedia entry:   [Mayan numerals]
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   -- MAYAN NUMBERS ------------------------------------------   -- mayanNumber:: Int -> [[String]] on mayanNumber(n) showIntAtBase(20, my mayanDigit, n, {}) end mayanNumber   -- mayanDigit :: Int -> String on mayanDigit(n) if 0 < n then set r to n mod 5 bool({}, {concat(replicate(r, "●"))}, 0 < r) & ¬ replicate(n div 5, "━━") else {"Θ"} end if end mayanDigit   -- mayanFrame :: Int -> String on mayanFrame(n) "Mayan " & (n as string) & ":\n" & wikiTable({|class|:¬ "wikitable", colwidth:¬ "3em", cell:¬ "vertical-align:bottom;", |style|:¬ "text-align:center;background-color:#F0EDDE;" & ¬ "color:#605B4B;border:2px solid silver"})'s ¬ |λ|({map(intercalateS("<br>"), mayanNumber(n))}) & "\n" end mayanFrame   -- TEST ---------------------------------------------------   on run set str to unlines(map(mayanFrame, ¬ {4005, 8017, 326205, 886205, 2978480}))   set the clipboard to (str) return str end run   -- GENERIC ------------------------------------------------   -- Just :: a -> Maybe a on Just(x) {type:"Maybe", Nothing:false, Just:x} end Just   -- Nothing :: Maybe a on Nothing() {type:"Maybe", Nothing:true} end Nothing   -- Tuple (,) :: a -> b -> (a, b) on Tuple(a, b) {type:"Tuple", |1|:a, |2|:b, length:2} end Tuple   -- bool :: a -> a -> Bool -> a on bool(f, t, p) if p then t else f end if end bool   -- concat :: [[a]] -> [a] -- concat :: [String] -> String on concat(xs) set lng to length of xs if 0 < lng and string is class of (item 1 of xs) then set acc to "" else set acc to {} end if repeat with i from 1 to lng set acc to acc & item i of xs end repeat acc end concat   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- intercalateS :: String -> [String] -> String on intercalateS(sep) script on |λ|(xs) set {dlm, my text item delimiters} to {my text item delimiters, sep} set s to xs as text set my text item delimiters to dlm return s end |λ| end script end intercalateS   -- lookupDict :: a -> Dict -> Maybe b on lookupDict(k, dct) set ca to current application set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k if missing value ≠ v then Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list)) else Nothing() end if end lookupDict   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- | The 'maybe' function takes a default value, a function, and a 'Maybe' -- value. If the 'Maybe' value is 'Nothing', the function returns the -- default value. Otherwise, it applies the function to the value inside -- the 'Just' and returns the result. -- maybe :: b -> (a -> b) -> Maybe a -> b on maybe(v, f, mb) if Nothing of mb then v else tell mReturn(f) to |λ|(Just of mb) end if end maybe   -- quotRem :: Int -> Int -> (Int, Int) on quotRem(m, n) Tuple(m div n, m mod n) end quotRem   -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if n < 1 then return out set dbl to {a}   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- showIntAtBase :: Int -> (Int -> [String]) -> Int -> String -> String on showIntAtBase(base, toDigit, n, rs) script showIt property f : mReturn(toDigit) on |λ|(nd_, r) set {n, d} to ({|1|, |2|} of nd_) set r_ to {f's |λ|(d)} & r if n > 0 then |λ|(quotRem(n, base), r_) else r_ end if end |λ| end script showIt's |λ|(quotRem(n, base), rs) end showIntAtBase   -- unlines :: [String] -> String on unlines(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines   -- unwords :: [String] -> String on unwords(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, space} set s to xs as text set my text item delimiters to dlm return s end unwords   -- wikiTable :: Dict -> [[String]] -> String on wikiTable(opts) script ksv on |λ|(k) script on |λ|(s) script on |λ|(v) k & v & s end |λ| end script end |λ| end script end |λ| end script script on |λ|(rows) script boxStyle on |λ|(a, k) maybe(a, ksv's |λ|(a & k & "=\"")'s |λ|("\" "), ¬ lookupDict(k, opts)) end |λ| end script script rowText on |λ|(row, iRow) script cellText on |λ|(cell) if 1 = iRow then set w to maybe("", ksv's |λ|("width:")'s |λ|(";"), ¬ lookupDict("colwidth", opts)) else set w to "" end if set s to maybe(w, ksv's |λ|(w)'s |λ|(""), ¬ lookupDict("cell", opts)) if 0 < length of s then "style=\"" & s & "\"|" & cell else cell end if end |λ| end script intercalateS("\n|")'s |λ|(map(cellText, row)) end |λ| end script "{| " & unwords(foldl(boxStyle, "", {"class", "style"})) & "\n|" & ¬ intercalateS("\n|-\n")'s |λ|(map(rowText, rows)) & "\n|}" end |λ| end script end wikiTable
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Clojure
Clojure
(ns small-projects.find-shortest-way (:require [clojure.string :as str]))   ;Misk functions (defn cell-empty? [maze coords] (= :empty (get-in maze coords)))   (defn wall? [maze coords] (= :wall (get-in maze coords)))   (defn track? [maze coords] (= :track (get-in maze coords)))   (defn get-neighbours [maze [y x cell]] [[y (dec x)] [(inc y) x] [y (inc x)] [(dec y) x]])   (defn get-difference [coll1 filter-coll] (filter #(not (contains? filter-coll %)) coll1))   (defn get-empties [maze cell] (->> (get-neighbours maze cell) (filter (partial cell-empty? maze))))   (defn possible-ways [maze cell filter-coll] (-> (get-empties maze cell) (get-difference filter-coll)))   (defn replace-cells [maze coords v] (if (empty? coords) maze (recur (assoc-in maze (first coords) v) (rest coords) v)))   ;Print and parse functions (def cell-code->str [" " " " " " " " "· " "╵ " "╴ " "┘ " " " " " " " " " "╶─" "└─" "──" "┴─" " " " " " " " " "╷ " "│ " "┐ " "┤ " " " " " " " " " "┌─" "├─" "┬─" "┼─" " " " " " " " " "■ " "╹ " "╸ " "┛ " " " " " " " " " "╺━" "┗━" "━━" "┻━" " " " " " " " " "╻ " "┃ " "┓ " "┫ " " " " " " " " " "┏━" "┣━" "┳━" "╋━" " "])   (defn get-cell-code [maze coords] (let [mode (if (track? maze coords) 1 0) check (if (zero? mode) wall? track?)] (transduce (comp (map (partial check maze)) (keep-indexed (fn [idx test] (when test idx))) (map (partial bit-shift-left 1))) (completing bit-or) (bit-shift-left mode 5) (sort (conj (get-neighbours maze coords) coords)))))   (defn code->str [cell-code] (nth cell-code->str cell-code))   (defn maze->str-symbols [maze] (for [y (range (count maze))] (for [x (range (count (nth maze y)))] (code->str (get-cell-code maze [y x])))))   (defn maze->str [maze] (->> (maze->str-symbols maze) (map str/join) (str/join "\n")))   (defn parse-pretty-maze [maze-str] (->> (str/split-lines maze-str) (map (partial take-nth 2)) (map (partial map #(if (= \space %) :empty :wall))) (map vec) (vec)))   ;Core (defn find-new-border [maze border old-border] (apply conj (map (fn [cell] (zipmap (possible-ways maze cell (conj border old-border)) (repeat cell))) (keys border))))   (defn backtrack [visited route] (let [cur-cell (get visited (first route))] (if (= cur-cell :start) route (recur visited (conj route cur-cell)))))   (defn breadth-first-search [maze start-cell end-cell] (loop [visited {start-cell :start} border {start-cell :start} old-border {start-cell :start}] (if (contains? old-border end-cell) (backtrack visited (list end-cell)) (recur (conj visited border) (find-new-border maze border old-border) border))))   (def maze (parse-pretty-maze maze-str))   (def solved-maze (replace-cells maze (breadth-first-search maze [1 1] [19 19]) :track))   (println (maze->str solved-maze))
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. Task Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
#C
C
  #include <stdio.h> #include <math.h>   #define max(x,y) ((x) > (y) ? (x) : (y))   int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 };   int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0;   int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } }   printf("%d\n", tri[0]); return 0; }  
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
#J
J
require 'ide/qt' gethash_jqtide_ 'MD4';'Rosetta Code' a52bcfc6a0d0d300cdc5ddbfbefe478b
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#Raku
Raku
sub middle-three($n) { given $n.abs { when .chars < 3 { "$n is too short" } when .chars %% 2 { "$n has an even number of digits" } default { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 } } }   say middle-three($_) for < 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 >;
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:   MD5 has known weaknesses, including collisions and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.
#BaCon
BaCon
  PRAGMA INCLUDE <stdio.h> PRAGMA INCLUDE <stdlib.h> PRAGMA INCLUDE <string.h> PRAGMA INCLUDE <openssl/md5.h> PRAGMA LDFLAGS -lcrypto -lm -w   DECLARE result TYPE unsigned char * DECLARE string TYPE const char *   string = "Rosetta code" strlenght = LEN(string)   result = MD5( string, strlenght , 0)   FOR i = 0 TO MD5_DIGEST_LENGTH-1 PRINT result[i] FORMAT "%02x" NEXT
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selected index number. The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: fee fie huff and puff mirror mirror tick tock Note This task is fashioned after the action of the Bash select statement.
#UNIX_Shell
UNIX Shell
# choose 'choice 1' 'choice 2' ... # Prints menu to standard error. Prompts with PS3. # Reads REPLY from standard input. Sets CHOICE. choose() { CHOICE= # Default CHOICE is empty string. [[ $# -gt 0 ]] || return # Return if "$@" is empty. select CHOICE; do # Select from "$@". if [[ -n $CHOICE ]]; then break else echo Invalid choice. fi done }   PS3='Which is from the three pigs: ' choose 'fee fie' 'huff and puff' 'mirror mirror' 'tick tock' [[ -n $CHOICE ]] && echo You chose: $CHOICE [[ -z $CHOICE ]] && echo No input.
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. Task Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number n which cannot be expressed with 6x + 9y + 20z = n where x, y and z are natural numbers).
#J
J
>./(i.100)-.,+/&>{(* i.@>.@%~&101)&.>6 9 20 43