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.
#BBC_BASIC
BBC BASIC
DIM list$(4) list$() = "fee fie", "huff and puff", "mirror mirror", "tick tock" selected$ = FNmenu(list$(), "Please make a selection: ") PRINT selected$ END   DEF FNmenu(list$(), prompt$) LOCAL index%, select$ IF SUM(list$()) = "" THEN = "" REPEAT CLS FOR index% = 0 TO DIM(list$() ,1) IF list$(index%)<>"" PRINT ; index% ":", list$(index%) NEXT PRINT prompt$ ; INPUT "" select$ index% = VAL(select$) IF select$<>STR$(index%) index% = -1 IF index%>=0 IF index%<=DIM(list$() ,1) IF list$(index%)="" index% = -1 UNTIL index%>=0 AND index%<=DIM(list$(), 1) = list$(index%)
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#Ada
Ada
package MD5 is   type Int32 is mod 2 ** 32; type MD5_Hash is array (1 .. 4) of Int32; function MD5 (Input : String) return MD5_Hash;   -- 32 hexadecimal characters + '0x' prefix subtype MD5_String is String (1 .. 34); function To_String (Item : MD5_Hash) return MD5_String;   end MD5;
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Delphi
Delphi
? <elib:tables.makeFlexList>.fromType(<type:java.lang.Byte>, 128) # value: [].diverge()
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#E
E
? <elib:tables.makeFlexList>.fromType(<type:java.lang.Byte>, 128) # value: [].diverge()
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#Mercury
Mercury
:- module rosetta.   :- interface. :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module list, int, float, string, maybe, solutions.   :- pred patient(int::out, string::out) is multi. patient(1001, "Hopper"). patient(4004, "Wirth"). patient(3003, "Kemeny"). patient(2002, "Gosling"). patient(5005, "Kurtz").   :- func nan = float. nan = det_to_float("NaN").   :- type maybe_date ---> date(year::int, month::int, day::int); no.   :- pred visit(int::out, maybe_date::out, float::out) is multi. visit(2002, date(2020,09,10), 6.8). visit(1001, date(2020,09,17), 5.5). visit(4004, date(2020,09,24), 8.4). visit(2002, date(2020,10,08), nan). visit(1001, no, 6.6). visit(3003, date(2020,11,12), nan). visit(4004, date(2020,11,05), 7.0). visit(1001, date(2020,11,19), 5.3).   %% Utilities :- pred bag_count(pred(T)::(pred(out) is nondet), int::out) is det. :- pred bag_sum(pred(float)::(pred(out) is nondet), float::out) is det. :- pred bag_avg(pred(float)::(pred(out) is nondet), float::out) is det. :- pred bag_max(pred(T)::(pred(out) is nondet), T::in, T::out) is det. bag_count(Predicate, Count) :- promise_equivalent_solutions[Count] ( unsorted_aggregate(Predicate, (pred(_X::in,Y::in,Z::out) is det :- Z is Y+1), 0, Count)). bag_sum(Predicate, Sum) :- promise_equivalent_solutions[Sum] ( unsorted_aggregate(Predicate, (pred(X::in,Y::in,Z::out) is det :- Z is X+Y), 0.0, Sum)). bag_avg(Predicate, Avg) :- bag_count(Predicate, N), bag_sum(Predicate, Sum), (if N = 0 then Avg = nan else Avg is Sum/float(N)). bag_max(Predicate, Initial, Max) :- promise_equivalent_solutions [Max] ( unsorted_aggregate(Predicate, (pred(X::in,Y::in,Z::out) is det :- compare(R,X,Y), (if R = (>) then Z = X else Z = Y)), Initial, Max)).   main(!IO) :- io.write_string("{Id, Lastname, SumScores, AvgScores, MaxDate}:\n", !IO), solutions((pred({Id,Lastname,Sum,Avg,MaxDate}::out) is nondet :- patient(Id,Lastname), Scores = (pred(Score::out) is nondet :- visit(Id,_,Score), \+is_nan(Score)), bag_avg(Scores, Avg), bag_sum(Scores, Sum), Dates = (pred(Date::out) is nondet :- visit(Id,Date,_), Date=date(_,_,_)), bag_max(Dates, date(0,0,0), MaxDate1), (if MaxDate1 = date(0,0,0) then MaxDate = no else MaxDate = MaxDate1)), Solutions), foldl(io.write_line, Solutions, !IO).
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Racket
Racket
  #lang racket   (require ffi/unsafe)   (define (_autobitmask l) (_bitmask (append* (for/list ([x l] [i (in-naturals)]) `(,x = ,(expt 2 i))))))   (define _rs232 (_autobitmask '(CD RD TD DTR SG DSR RTS CTS RI )))   ;; Usually it will get used when using foreign functions automatically, but ;; this demonstrates the conversions explicitly (require (only-in '#%foreign ctype-scheme->c ctype-c->scheme)) ((ctype-scheme->c _rs232) '(SG TD RI)) ; -> 276 ((ctype-c->scheme _rs232) 276)  ; -> '(TD SG RI)  
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Raku
Raku
enum T_RS232 < carrier_detect received_data transmitted_data data_terminal_ready signal_ground data_set_ready request_to_send clear_to_send ring_indicator >;   my bit @signal[T_RS232];   @signal[signal_ground] = 1;
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#REXX
REXX
/* REXX *************************************************************** * Decode Memory structure of RS-232 Plug Definition * Not sure if I understood it completely :-) Open for corrections * You never stop learning (as long as you live) * 03.08.2012 Walter Pachl **********************************************************************/ Call decode 'ABC' Call decode 'XY' Exit   decode: Parse Arg c cb=c2b(c) If length(cb)=24 Then Do Parse Var cb, /* 1 - PG */ Protective ground +1, /* 3 2 - TD */ Transmitted_data +1, /* 2 3 - RD */ Received_data +1, /* 7 4 - RTS */ Request_to_send +1, /* 8 5 - CTS */ Clear_to_send +1, /* 6 6 - DSR */ Data_set_ready +1, /* 5 7 - SG */ Signal_ground +1, /* 1 8 - CD */ Carrier_detect +1, /* 9 - + */ plus_voltage +1, /* 10 - - */ minus_voltage +1, /* 11 - */ . +1, /* 12 - SCD */ Secondary_CD +1, /* 13 - SCS */ Secondary_CTS +1, /* 14 - STD */ Secondary_TD +1, /* 15 - TC */ Transmit_clock +1, /* 16 - SRD */ Secondary_RD +1, /* 17 - RC */ Receiver_clock +1, /* 18 - */ . +1, /* 19 - SRS */ Secondary_RTS +1, /* 4 20 - DTR */ Data_terminal_ready +1, /* 21 - SQD */ Signal_quality_detector+1, /* 9 22 - RI */ Ring_indicator +1, /* 23 - DRS */ Data_rate_select +1, /* 24 - XTC */ External_clock +1 Say '24 bins:' cb Say ' 1 - PG Protective ground ='Protective ground Say ' 2 - TD Transmitted data ='Transmitted_data Say ' 3 - RD Received data ='Received_data Say ' 4 - RTS Request to send ='Request_to_send Say ' 5 - CTS Clear to send ='Clear_to_send Say ' 6 - DSR Data set ready ='Data_set_ready Say ' 7 - SG Signal ground ='Signal_ground Say ' 8 - CD Carrier detect ='Carrier_detect Say ' 9 - + plus voltage ='plus_voltage Say '10 - - minus voltage ='minus_voltage Say ' ' Say '12 - SCD Secondary CD ='Secondary_CD Say '13 - SCS Secondary CTS ='Secondary_CTS Say '14 - STD Secondary TD ='Secondary_TD Say '15 - TC Transmit clock ='Transmit_clock Say '16 - SRD Secondary RD ='Secondary_RD Say '17 - RC Receiver clock ='Receiver_clock Say ' ' Say '19 - SRS Secondary RTS ='Secondary_RTS Say '20 - DTR Data terminal ready ='Data_terminal_ready Say '21 - SQD Signal quality detector ='Signal_quality_detector Say '22 - RI Ring indicator ='Ring_indicator Say '23 - DRS Data rate select ='Data_rate_select Say '24 - XTC External hlock ='External_clock End Else Do Parse Var cb, /* 1 8 - CD */ Carrier_detect +1, /* 2 3 - RD */ Received_data +1, /* 3 2 - TD */ Transmitted_data +1, /* 4 20 - DTR */ Data_terminal_ready +1, /* 5 7 - SG */ Signal_ground +1, /* 6 6 - DSR */ Data_set_ready +1, /* 7 4 - RTS */ Request_to_send +1, /* 8 5 - CTS */ Clear_to_send +1, /* 9 22 - RI */ Ring_indicator +1 Say ' ' Say '9-bin:' left(cb,9) Say ' 1 CD Carrier detect ='Carrier_detect Say ' 2 RD Received data ='Received_data Say ' 3 TD Transmitted data ='Transmitted_data Say ' 4 DTR Data terminal ready ='Data_terminal_ready Say ' 5 SG Signal ground ='Signal_ground Say ' 6 DSR Data set ready ='Data_set_ready Say ' 7 RTS Request to send ='Request_to_send Say ' 8 CTS Clear to send ='Clear_to_send Say ' 9 RI Ring indicator ='Ring_indicator End Return c2b: Procedure /* REXX *************************************************************** * c2b Convert a character string to a bit string * 03.08.2012 Walter Pachl **********************************************************************/ Parse Arg c x=c2x(c) res='' Do While x<>'' Parse Var x hb +1 x Select When hb='0' Then bs='0000' When hb='1' Then bs='0001' When hb='2' Then bs='0010' When hb='3' Then bs='0011' When hb='4' Then bs='0100' When hb='5' Then bs='0101' When hb='6' Then bs='0110' When hb='7' Then bs='0111' When hb='8' Then bs='1000' When hb='9' Then bs='1001' When hb='A' Then bs='1010' When hb='B' Then bs='1011' When hb='C' Then bs='1100' When hb='D' Then bs='1101' When hb='E' Then bs='1110' When hb='F' Then bs='1111' End res=res||bs End Return res
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Ruby
Ruby
class Pixmap def median_filter(radius=3) radius += 1 if radius.even? filtered = self.class.new(@width, @height) pb = ProgressBar.new(@height) if $DEBUG @height.times do |y| @width.times do |x| window = [] (x - radius).upto(x + radius).each do |win_x| (y - radius).upto(y + radius).each do |win_y| win_x = 0 if win_x < 0 win_y = 0 if win_y < 0 win_x = @width-1 if win_x >= @width win_y = @height-1 if win_y >= @height window << self[win_x, win_y] end end # median filtered[x, y] = window.sort[window.length / 2] end pb.update(y) if $DEBUG end pb.close if $DEBUG filtered end end   class RGBColour # refactoring def luminosity Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue) end def to_grayscale l = luminosity self.class.new(l, l, l) end   # defines how to compare (and hence, sort) def <=>(other) self.luminosity <=> other.luminosity end end   class ProgressBar def initialize(max) $stdout.sync = true @progress_max = max @progress_pos = 0 @progress_view = 68 $stdout.print "[#{'-'*@progress_view}]\r[" end   def update(n) new_pos = n * @progress_view/@progress_max if new_pos > @progress_pos @progress_pos = new_pos $stdout.print '=' end end   def close $stdout.puts '=]' end end   bitmap = Pixmap.open('file') filtered = bitmap.median_filter
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.
#C_sharp
C_sharp
using System;   namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#Phix
Phix
constant help = """   Minesweeper ===========   Enter eg A1 to open a cell, FA1 to flag a cell, Q to quit.   The board is initially displayed with 10-20% of cells mined, as follows:   . - an unknown cell (unopened and not flagged) _ - an empty cell, with no surrounding mines 1..8 - an empty cell, with some nearby mines ? - a cell you have flagged as a mine (a flag can only be cleared by opening)   On completion: X - the mine you detonated (if any) * - a mine which was not flagged + - a mine which was correctly flagged """   string board = """   123456 A...... B...... C...... D...... """   sequence data = repeat(repeat(0,6),4) -- 0: empty, no nearby mines -- 1-8: empty, with surrounding mines -- 9: a mine   -- data[row][col] maps to board[row*8+4+col], lets quickly verify that: if find('.',board)!=13 then ?9/0 end if if rfind('.',board)!=42 then ?9/0 end if -- (above may trigger if copy/paste/dowload etc messed up whitespace)   constant prompt = "\nEnter eg A1 to open a cell, FA1 to flag a cell, Q to quit, or ? for help:"   integer mines = round((6*4)*0.10+rand(6*4)*0.10), -- 10-20% cleared = 0, flagged = 0, flag = false, row = 0, col   procedure plant_mines() for i=1 to mines do while 1 do row = rand(4) col = rand(6) if data[row][col]!=9 then data[row][col] = 9 for rx=row-1 to row+1 do if rx>=1 and rx<=4 then for cx=col-1 to col+1 do if cx>=1 and cx<=6 then if data[rx][cx]!=9 then data[rx][cx] += 1 end if end if end for end if end for exit end if end while end for printf(1,"%d mines planted\n",mines) row = 0 end procedure   procedure clear_cell(integer row, col, drc) board[row*8+4+col] = iff(drc?drc+'0':' ') cleared += 1 if drc=0 then for rx=row-1 to row+1 do if rx>=1 and rx<=4 then for cx=col-1 to col+1 do if cx>=1 and cx<=6 then drc = data[rx][cx] if drc!=9 and board[rx*8+4+cx]='.' then clear_cell(rx,cx,drc) end if end if end for end if end for end if end procedure   function make_move() integer brc = row*8+4+col if flag then if board[brc]='.' then board[brc] = '?' flagged += 1 end if else integer drc = data[row][col] if drc=9 then board[brc] = 'X' puts(1,"\n\n***BOOM!***") return true end if if find(board[brc],".?") then clear_cell(row,col,drc) end if end if row = 0 flag = false -- nb: flagged and cleared may be wrong following incorrect input. if flagged=mines or cleared=6*4-mines then puts(1,"\n\n***You Win!***") return true end if return false -- no "BOOM" yet! end function   procedure disclose() for row=1 to 4 do for col=1 to 6 do if data[row][col]=9 then integer bdx = row*8+4+col, bch = board[bdx] if bch='.' then bch = '*' elsif bch='?' then bch = '+' elsif bch!='X' then  ?9/0 end if board[bdx] = bch end if end for end for end procedure   plant_mines() while 1 do if not flag and row=0 then puts(1,board) puts(1,prompt) end if integer ch = upper(getc(0)) puts(1,ch) if ch='Q' then exit end if if ch='?' then puts(1,help) elsif ch='F' then flag = true elsif ch>='A' and ch<='D' then row = ch-'@' elsif ch>='1' and ch<='6' then col = ch-'0' if make_move() then exit end if else printf(1,"\n\nunrecognised:%c\n\n",ch) flag = false row = 0 end if end while disclose() puts(1,board&"game over\n\n") {} = wait_key()
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#Visual_Basic_.NET
Visual Basic .NET
Imports System, System.Linq, System.Collections.Generic, System.Console   Module Module1   Dim fmt As String = "{0,4} * {1,31:n0} = {2,-28}" & vbLf   Sub B10(ByVal n As Integer) If n <= 1 Then Return Dim pow As Integer() = New Integer(n) {}, val As Integer() = New Integer(n) {}, count As Integer = 0, ten As Integer = 1, x As Integer = 1 While x <= n : val(x) = ten : For j As Integer = 0 To n If pow(j) <> 0 AndAlso pow((j + ten) Mod n) = 0 AndAlso _ pow(j) <> x Then pow((j + ten) Mod n) = x Next : If pow(ten) = 0 Then pow(ten) = x ten = (10 * ten) Mod n : If pow(0) <> 0 Then x = n : Dim s As String = "" : While x <> 0 Dim p As Integer = pow(x Mod n) If count > p Then s += New String("0"c, count - p) count = p - 1 : s += "1" x = (n + x - val(p)) Mod n : End While If count > 0 Then s += New String("0"c, count) Write(fmt, n, Decimal.Parse(s) / n, s) : Return End If : x += 1 : End While : Write("Can't do it!") End Sub   Sub Main(ByVal args As String()) Dim st As DateTime = DateTime.Now Dim m As List(Of Integer) = New List(Of Integer) From _ {297,576,594,891,909,999,1998,2079,2251,2277,2439,2997,4878} Write(fmt, "n", "multiplier", "B10") WriteLine(New String("-"c, 69)) : Write(fmt, 1, 1, 1) For n As Integer = 1 To m.Last() If n <= 10 OrElse n >= 95 AndAlso n <= 105 OrElse m.Contains(n) Then B10(n) Next : WriteLine(vbLf & "Took {0}ms", (DateTime.Now - st).TotalMilliseconds) End Sub End Module
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#TXR
TXR
$ txr -p '(exptmod 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 (expt 10 40)))' 1527229998585248450016808958343740453059
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#Visual_Basic_.NET
Visual Basic .NET
' Modular exponentiation - VB.Net - 21/01/2019 Imports System.Numerics   Private Sub Main() Dim a, b, m, x As BigInteger a = BigInteger.Parse("2988348162058574136915891421498819466320163312926952423791023078876139") b = BigInteger.Parse("2351399303373464486466122544523690094744975233415544072992656881240319") m = BigInteger.Pow(10, 40) '=10^40 x = ModPowBig(a, b, m) Debug.Print("x=" & x.ToString) End Sub 'Main   Function ModPowBig(ByVal base As BigInteger, ByVal exponent As BigInteger, ByVal modulus As BigInteger) As BigInteger Dim result As BigInteger result = 1 Do While exponent > 0 If (exponent Mod 2) = 1 Then result = (result * base) Mod modulus End If exponent = exponent / 2 base = (base * base) Mod modulus Loop Return result End Function 'ModPowBig
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Python
Python
  #lang Python import time   def main(bpm = 72, bpb = 4): sleep = 60.0 / bpm counter = 0 while True: counter += 1 if counter % bpb: print 'tick' else: print 'TICK' time.sleep(sleep)       main()    
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Racket
Racket
  #lang racket   (require racket/gui)   (define msec 500) (define sounds '("hi.wav" "lo.wav")) (define colors '("red" "green"))   (define f (new frame% [label "Metronome"] [width 200] [height 200])) (define c (new (class canvas% (define brushes (map (λ(c) (new brush% [color c] [style 'solid])) colors)) (define cur 0) (define/override (on-paint) (send* (send this get-dc) (clear) (set-brush (list-ref brushes cur)) (draw-rectangle 0 0 200 200))) (define/public (flip!) (set! cur (modulo (add1 cur) (length sounds))) (play-sound (list-ref sounds cur) #f) (on-paint)) (super-new)) [parent f]))   (define (flip) (define init (current-inexact-milliseconds)) (define next (+ msec init)) (define ticks 1) (let loop () (when (> (current-inexact-milliseconds) next) (set! ticks (add1 ticks)) (set! next (+ init (* msec ticks))) (queue-callback (λ() (send c flip!)))) (sleep 0.01) (loop)))   (send* f (center) (show #t)) (void (thread flip))  
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#Scala
Scala
class CountingSemaphore(var maxCount: Int) { private var lockCount = 0   def acquire(): Unit = { while ( { lockCount >= maxCount }) wait() lockCount += 1 }   def release(): Unit = { if (lockCount > 0) { lockCount -= 1 notifyAll() } }   def getCount: Int = lockCount }   object Worker { def main(args: Array[String]): Unit = { val (lock, crew) = (new CountingSemaphore(3), new Array[Worker](5))   for { i <- 0 until 5} { crew(i) = new Worker(lock, i) crew(i).start() } } }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Simula
Simula
begin integer i, j; outtext( " " ); for i := 1 step 1 until 12 do outint( i, 4 ); outimage; outtext( " +" ); for i := 1 step 1 until 12 do outtext( "----" ); outimage; for i := 1 step 1 until 12 do begin outint( i, 3 ); outtext( "|" ); for j := 1 step 1 until i - 1 do outtext( " " ); for j := i step 1 until 12 do outint( i * j, 4 ); outimage end; end
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, for all i and j less than or equal to n. The Task Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence. Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence. Demonstrating working through the first few terms longhand: a1 = 1 1 + 1 = 2 Speculatively try a2 = 2 1 + 1 = 2 1 + 2 = 3 2 + 2 = 4 There are no repeated sums so 2 is the next number in the sequence. Speculatively try a3 = 3 1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 2 + 2 = 4 2 + 3 = 5 3 + 3 = 6 Sum of 4 is repeated so 3 is rejected. Speculatively try a3 = 4 1 + 1 = 2 1 + 2 = 3 1 + 4 = 5 2 + 2 = 4 2 + 4 = 6 4 + 4 = 8 There are no repeated sums so 4 is the next number in the sequence. And so on... See also OEIS:A005282 Mian-Chowla sequence
#Wren
Wren
var mianChowla = Fn.new { |n| var mc = List.filled(n, 0) var sums = {} var ts = {} mc[0] = 1 sums[2] = true for (i in 1...n) { var j = mc[i-1] + 1 while (true) { mc[i] = j for (k in 0..i) { var sum = mc[k] + j if (sums[sum]) { ts.clear() break } ts[sum] = true } if (ts.count > 0) { for (key in ts.keys) sums[key] = true break } j = j + 1 } } return mc }   var start = System.clock var mc = mianChowla.call(100) System.print("The first 30 terms of the Mian-Chowla sequence are:\n%(mc[0..29].join(" "))") System.print("\nTerms 91 to 100 of the Mian-Chowla sequence are:\n%(mc[90..99].join(" "))") System.print("\nTook %(((System.clock - start)*1000).round) milliseconds")
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Run_BASIC
Run BASIC
' --------------------------------------------------- ' create a file to be run ' RB can run the entire program ' or execute a function withing the RUNNED program ' --------------------------------------------------- open "runned.bas" for output as #f ' open runned.bas as output   print #f, "text$ = ""I'm rinning the complete program. ' print this program to the output Or you can run a function. The program or function within the RUNNED program can execute all Run BASIC commands."""   print #f, " x = displayText(text$)"   print #f, " ' besides RUNNING the entireprogram Function displayText(text$) ' we will execute this function only print text$ ' end function"   ' ---------------------------------------- ' Execute the entire RUNNED program ' ---------------------------------------- RUN "runned.bas",#handle ' setup run command to execute runned.bas and give it a handle render #handle ' render the handle will execute the program   ' ---------------------------------------- ' Execute a function in the RUNNED program ' ---------------------------------------- RUN "runned.bas",#handle ' setup run command to execute runned.bas and give it a handle #handle displayText("Welcome!") ' only execute the function withing the runned program render #handle ' render the handle will execute the program
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Rust
Rust
// dry.rs use std::ops::{Add, Mul, Sub};   macro_rules! assert_equal_len { // The `tt` (token tree) designator is used for // operators and tokens. ($a:ident, $b: ident, $func:ident, $op:tt) => ( assert!($a.len() == $b.len(), "{:?}: dimension mismatch: {:?} {:?} {:?}", stringify!($func), ($a.len(),), stringify!($op), ($b.len(),)); ) }   macro_rules! op { ($func:ident, $bound:ident, $op:tt, $method:ident) => ( fn $func<T: $bound<T, Output=T> + Copy>(xs: &mut Vec<T>, ys: &Vec<T>) { assert_equal_len!(xs, ys, $func, $op);   for (x, y) in xs.iter_mut().zip(ys.iter()) { *x = $bound::$method(*x, *y); // *x = x.$method(*y); } } ) }   // Implement `add_assign`, `mul_assign`, and `sub_assign` functions. op!(add_assign, Add, +=, add); op!(mul_assign, Mul, *=, mul); op!(sub_assign, Sub, -=, sub);   mod test { use std::iter; macro_rules! test { ($func: ident, $x:expr, $y:expr, $z:expr) => { #[test] fn $func() { for size in 0usize..10 { let mut x: Vec<_> = iter::repeat($x).take(size).collect(); let y: Vec<_> = iter::repeat($y).take(size).collect(); let z: Vec<_> = iter::repeat($z).take(size).collect();   super::$func(&mut x, &y);   assert_eq!(x, z); } } } }   // Test `add_assign`, `mul_assign` and `sub_assign` test!(add_assign, 1u32, 2u32, 3u32); test!(mul_assign, 2u32, 3u32, 6u32); test!(sub_assign, 3u32, 2u32, 1u32); }
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#Elixir
Elixir
  defmodule Prime do use Application alias :math, as: Math alias :rand, as: Rand   def start( _type, _args ) do primes = 5..1000 |> Enum.filter( fn( x ) -> (rem x, 2) == 1 end ) |> Enum.filter( fn( x ) -> miller_rabin?( x, 10) == True end ) IO.inspect( primes, label: "Primes: ", limit: :infinity )   { :ok, self() } end   def modular_exp( x, y, mod ) do with [ _ | bits ] = Integer.digits( y, 2 ) do Enum.reduce bits, x, fn( bit, acc ) -> acc * acc |> ( &( if bit == 1, do: &1 * x, else: &1 ) ).() |> rem( mod ) end end end   def miller_rabin( d, s ) when rem( d, 2 ) == 0, do: { s, d } def miller_rabin( d, s ), do: miller_rabin( div( d, 2 ), s + 1 )   def miller_rabin?( n, g ) do { s, d } = miller_rabin( n - 1, 0 ) miller_rabin( n, g, s, d ) end   def miller_rabin( n, 0, _, _ ), do: True def miller_rabin( n, g, s, d ) do a = 1 + Rand.uniform( n - 3 ) x = modular_exp( a, d, n ) if x == 1 or x == n - 1 do miller_rabin( n, g - 1, s, d ) else if miller_rabin( n, x, s - 1) == True, do: miller_rabin( n, g - 1, s, d ), else: False end end   def miller_rabin( n, x, r ) when r <= 0, do: False def miller_rabin( n, x, r ) do x = modular_exp( x, 2, n ) unless x == 1 do unless x == n - 1, do: miller_rabin( n, x, r - 1 ), else: True else False end end end  
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <vector>   std::vector<int> mertens_numbers(int max) { std::vector<int> m(max + 1, 1); for (int n = 2; n <= max; ++n) { for (int k = 2; k <= n; ++k) m[n] -= m[n / k]; } return m; }   int main() { const int max = 1000; auto m(mertens_numbers(max)); std::cout << "First 199 Mertens numbers:\n"; for (int i = 0, column = 0; i < 200; ++i) { if (column > 0) std::cout << ' '; if (i == 0) std::cout << " "; else std::cout << std::setw(2) << m[i]; ++column; if (column == 20) { std::cout << '\n'; column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { if (m[i] == 0) { ++zero; if (previous != 0) ++cross; } previous = m[i]; } std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n"; std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n"; return 0; }
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.
#Brat
Brat
menu = { prompt, choices | true? choices.empty? { "" } { choices.each_with_index { c, i | p "#{i}. #{c}" }   selection = ask prompt   true? selection.numeric? { selection = selection.to_i true? selection < 0 || { selection >= choices.length } { p "Selection is out of range"; menu prompt, choices } { choices[selection] } } { p "Selection must be a number"; menu prompt, choices } } }   p menu "Selection: " ["fee fie" "huff and puff" "mirror mirror" "tick tock"]
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#AutoHotkey
AutoHotkey
PRINT FN_MD5("") PRINT FN_MD5("a") PRINT FN_MD5("abc") PRINT FN_MD5("message digest") PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz") PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") PRINT FN_MD5(STRING$(8,"1234567890")) END   DEF FN_MD5(message$) LOCAL a%, b%, c%, d%, f%, g%, h0%, h1%, h2%, h3%, i%, bits%, chunk%, temp% LOCAL r&(), k%(), w%() DIM r&(63), k%(63), w%(15)   REM r specifies the per-round shift amounts: r&() = 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   REM Use binary integer part of the sines of integers (Radians) as constants: FOR i% = 0 TO 63 k%(i%) = FN32(INT(ABS(SIN(i% + 1.0#)) * 2^32)) NEXT   REM Initialize variables: h0% = &67452301 h1% = &EFCDAB89 h2% = &98BADCFE h3% = &10325476   bits% = LEN(message$)*8   REM Append '1' bit to message: message$ += CHR$&80   REM Append '0' bits until message length in bits = 448 (mod 512): WHILE (LEN(message$) MOD 64) <> 56 message$ += CHR$0 ENDWHILE   REM Append length of message (before pre-processing), in bits, as REM 64-bit little-endian integer: FOR i% = 0 TO 56 STEP 8 message$ += CHR$(bits% >>> i%) NEXT   REM Process the message in successive 512-bit chunks: FOR chunk% = 0 TO LEN(message$) DIV 64 - 1   REM Break chunk into sixteen 32-bit little-endian words: FOR i% = 0 TO 15 w%(i%) = !(PTR(message$) + 64*chunk% + 4*i%) NEXT i%   REM Initialize hash value for this chunk: a% = h0% b% = h1% c% = h2% d% = h3%   REM Main loop: FOR i% = 0 TO 63 CASE TRUE OF WHEN i% <= 15: f% = d% EOR (b% AND (c% EOR d%)) g% = i% WHEN 16 <= i% AND i% <= 31: f% = c% EOR (d% AND (b% EOR c%)) g% = (5 * i% + 1) MOD 16 WHEN 32 <= i% AND i% <= 47: f% = b% EOR c% EOR d% g% = (3 * i% + 5) MOD 16 OTHERWISE: f% = c% EOR (b% OR (NOT d%)) g% = (7 * i%) MOD 16 ENDCASE   temp% = d% d% = c% c% = b% b% = FN32(b% + FNlrot(FN32(a% + f%) + FN32(k%(i%) + w%(g%)), r&(i%))) a% = temp%   NEXT i%   REM Add this chunk's hash to result so far: h0% = FN32(h0% + a%) h1% = FN32(h1% + b%) h2% = FN32(h2% + c%) h3% = FN32(h3% + d%)   NEXT chunk%   = FNrevhex(h0%) + FNrevhex(h1%) + FNrevhex(h2%) + FNrevhex(h3%)   DEF FNrevhex(A%) SWAP ?(^A%+0),?(^A%+3) SWAP ?(^A%+1),?(^A%+2) = RIGHT$("0000000"+STR$~A%,8)   DEF FNlrot(n#, r%) n# = FN32(n#) = (n# << r%) OR (n# >>> (32 - r%))   DEF FN32(n#) WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE WHILE n# < &80000000 : n# += 2^32 : ENDWHILE = n#
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Erlang
Erlang
Pid = erlang:spawn_opt( Fun, [{min_heap_size, 1024}] ).
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Factor
Factor
2000 malloc (...do stuff..) free
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#Nim
Nim
import algorithm, parsecsv, strformat, strutils, tables   const NoValue = -1.0   type   Names = OrderedTable[Positive, string] # Mapping id -> last name.   Visit = tuple[date: string; score: float] Visits = Table[Positive, seq[Visit]] # Mapping id -> list of visits.     proc readNames(path: string): Names = ## Read the records (id, lastname) from the CSV file and fill a Names table. var parser: CsvParser parser.open(path) parser.readHeaderRow() while parser.readRow(): let id = parser.row[0].parseInt let name = parser.row[1] result[id] = name   proc readVisits(path: string): Visits = ## Read the records (id, date, score) from the CSV file and fill a Visits table. var parser: CsvParser parser.open(path) parser.readHeaderRow() while parser.readRow(): let id = parser.row[0].parseInt let date = parser.row[1] let score = if parser.row[2].len == 0: NoValue else: parser.row[2].parseFloat result.mgetOrPut(id, @[]).add (date, score)     var names = readNames("patients1.csv") visits = readVisits("patients2.csv")   names.sort(system.cmp)   echo "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |" for (id, name) in names.pairs: let visitList = visits.getOrDefault(id).sorted() let lastVisit = if visitList.len == 0: "" else: visitList[^1].date var sum = 0.0 var count = 0 for visit in visitList: if visit.score != NoValue: sum += visit.score inc count let scoreSum = if count == 0: "" else: &"{sum:>4.1f}" let scoreAvg = if count == 0: "" else: &"{sum / count.toFloat: >4.2f}" echo &"| {id:^10} | {name:^10} | {lastVisit:^10} | {scoreSum:>7} | {scoreAvg:>6} |"
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Ruby
Ruby
require 'bit-struct'   class RS232_9 < BitStruct unsigned :cd, 1, "Carrier detect" #1 unsigned :rd, 1, "Received data" #2 unsigned :td, 1, "Transmitted data" #3 unsigned :dtr, 1, "Data terminal ready" #4 unsigned :sg, 1, "Signal ground" #5 unsigned :dsr, 1, "Data set ready" #6 unsigned :rts, 1, "Request to send" #7 unsigned :cts, 1, "Clear to send" #8 unsigned :ri, 1, "Ring indicator" #9   def self.new_with_int(value) data = {} fields.each_with_index {|f, i| data[f.name] = value[i]} new(data) end end   num = rand(2**9 - 1) puts "num = #{num}"   sample1 = RS232_9.new([("%09d" % num.to_s(2)).reverse].pack("B*")) puts sample1.inspect_detailed   sample2 = RS232_9.new_with_int(num) puts sample2.inspect_detailed   puts "CD is #{sample2.cd == 1 ? 'on' : 'off'}"
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Tcl
Tcl
package require Tk   # Set the color of a pixel proc applyMedian {srcImage x y -> dstImage} { set x0 [expr {$x==0 ? 0 : $x-1}] set y0 [expr {$y==0 ? 0 : $y-1}] set x1 $x set y1 $y set x2 [expr {$x+1==[image width $srcImage] ? $x : $x+1}] set y2 [expr {$y+1==[image height $srcImage] ? $y : $y+1}]   set r [set g [set b {}]] foreach X [list $x0 $x1 $x2] { foreach Y [list $y0 $y1 $y2] { lassign [$srcImage get $X $Y] rPix gPix bPix lappend r $rPix lappend g $gPix lappend b $bPix } } set r [lindex [lsort -integer $r] 4] set g [lindex [lsort -integer $g] 4] set b [lindex [lsort -integer $b] 4] $dstImage put [format "#%02x%02x%02x" $r $g $b] -to $x $y } # Apply the filter to the whole image proc medianFilter {srcImage {dstImage ""}} { if {$dstImage eq ""} { set dstImage [image create photo] } set w [image width $srcImage] set h [image height $srcImage] for {set x 0} {$x < $w} {incr x} { for {set y 0} {$y < $h} {incr y} { applyMedian $srcImage $x $y -> $dstImage } } return $dstImage }   # Demonstration code using the Tk widget demo's teapot image image create photo teapot -file $tk_library/demos/images/teapot.ppm pack [labelframe .src -text Source] -side left pack [label .src.l -image teapot] update pack [labelframe .dst -text Median] -side left pack [label .dst.l -image [medianFilter teapot]]
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.
#Clojure
Clojure
  (defn middle3 [v] (let [no (Math/abs v) digits (str no) len (count digits)] (cond (< len 3) :too_short (even? len) :no_middle_in_even_no_of_digits  :else (let [mid (/ len 2) start (- mid 2)] (apply str (take 3 (nthnext digits start)))))))   (def passes '(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345)) (def fails '(1 2 -1 -10 2002 -2002 0))    
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#PHP
PHP
<?php define('MINEGRID_WIDTH', 6); define('MINEGRID_HEIGHT', 4);   define('MINESWEEPER_NOT_EXPLORED', -1); define('MINESWEEPER_MINE', -2); define('MINESWEEPER_FLAGGED', -3); define('MINESWEEPER_FLAGGED_MINE', -4); define('ACTIVATED_MINE', -5);   function check_field($field) { if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) { return true; } else { return false; } }   function explore_field($field) { if (!isset($_SESSION['minesweeper'][$field]) || !in_array($_SESSION['minesweeper'][$field], array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) { return; }   $mines = 0;   // Make reference to that long name $fields = &$_SESSION['minesweeper'];   // @ operator helps avoiding isset()... (it removes E_NOTICEs)   // left side options if ($field % MINEGRID_WIDTH !== 1) { $mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]); $mines += check_field(@$fields[$field - 1]); $mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]); }   // bottom and top $mines += check_field(@$fields[$field - MINEGRID_WIDTH]); $mines += check_field(@$fields[$field + MINEGRID_WIDTH]);   // right side options if ($field % MINEGRID_WIDTH !== 0) { $mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]); $mines += check_field(@$fields[$field + 1]); $mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]); }   $fields[$field] = $mines;   if ($mines === 0) { if ($field % MINEGRID_WIDTH !== 1) { explore_field($field - MINEGRID_WIDTH - 1); explore_field($field - 1); explore_field($field + MINEGRID_WIDTH - 1); }   explore_field($field - MINEGRID_WIDTH); explore_field($field + MINEGRID_WIDTH);   if ($field % MINEGRID_WIDTH !== 0) { explore_field($field - MINEGRID_WIDTH + 1); explore_field($field + 1); explore_field($field + MINEGRID_WIDTH + 1); } } }   session_start(); // will start session storage   if (!isset($_SESSION['minesweeper'])) { // Fill grid with not explored tiles $_SESSION['minesweeper'] = array_fill(1, MINEGRID_WIDTH * MINEGRID_HEIGHT, MINESWEEPER_NOT_EXPLORED);   // Generate random number of mines between 0.1 and 0.2 $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT, 0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);   // generate mines randomly $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);   foreach ($random_keys as $key) { $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE; }   // to make calculations shorter use SESSION variable to store the result $_SESSION['numberofmines'] = $number_of_mines; }   if (isset($_GET['explore'])) { if(isset($_SESSION['minesweeper'][$_GET['explore']])) { switch ($_SESSION['minesweeper'][$_GET['explore']]) { case MINESWEEPER_NOT_EXPLORED: explore_field($_GET['explore']); break; case MINESWEEPER_MINE: $lost = 1; $_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE; break; default: // The tile was discovered already. Ignore it. break; } } else { die('Tile doesn\'t exist.'); } } elseif (isset($_GET['flag'])) { if(isset($_SESSION['minesweeper'][$_GET['flag']])) { $tile = &$_SESSION['minesweeper'][$_GET['flag']]; switch ($tile) { case MINESWEEPER_NOT_EXPLORED: $tile = MINESWEEPER_FLAGGED; break; case MINESWEEPER_MINE: $tile = MINESWEEPER_FLAGGED_MINE; break; case MINESWEEPER_FLAGGED: $tile = MINESWEEPER_NOT_EXPLORED; break; case MINESWEEPER_FLAGGED_MINE: $tile = MINESWEEPER_MINE; break; default: // This tile shouldn't be flagged. Ignore it. break; } } else { die('Tile doesn\'t exist.'); } }   // Check if the player won... if (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper']) && !in_array(MINESWEEPER_FLAGGED, $_SESSION['minesweeper'])) { $won = true; } ?> <!DOCTYPE html> <title>Minesweeper</title> <style> table { border-collapse: collapse; }   td, a { text-align: center; width: 1em; height: 1em; }   a { display: block; color: black; text-decoration: none; font-size: 2em; } </style> <script> function flag(number, e) { if (e.which === 2 || e.which === 3) { location = '?flag=' + number; return false; } } </script> <?php echo "<p>This field contains $_SESSION[numberofmines] mines."; ?> <table border="1"> <?php // array_shift() affects array, so we need a copy $mine_copy = $_SESSION['minesweeper'];   for ($x = 1; $x <= MINEGRID_HEIGHT; $x++) { echo '<tr>'; for ($y = 1; $y <= MINEGRID_WIDTH; $y++) { echo '<td>';   $number = array_shift($mine_copy); switch ($number) { case MINESWEEPER_FLAGGED: case MINESWEEPER_FLAGGED_MINE: if (!empty($lost) || !empty($won)) { if ($number === MINESWEEPER_FLAGGED_MINE) { echo '<a>*</a>'; } else { echo '<a>.</a>'; } } else { echo '<a href=# onmousedown="return flag(', ($x - 1) * MINEGRID_WIDTH + $y, ',event)" oncontextmenu="return false">?</a>'; } break; case ACTIVATED_MINE: echo '<a>:(</a>'; break; case MINESWEEPER_MINE: case MINESWEEPER_NOT_EXPLORED: // oncontextmenu causes the menu to disappear in // Firefox, IE and Chrome   // In case of Opera, modifying location causes menu // to not appear.   if (!empty($lost)) { if ($number === MINESWEEPER_MINE) { echo '<a>*</a>'; } else { echo '<a>.</a>'; } } elseif (!empty($won)) { echo '<a>*</a>'; } else { echo '<a href="?explore=', ($x - 1) * MINEGRID_WIDTH + $y, '" onmousedown="return flag(', ($x - 1) * MINEGRID_WIDTH + $y, ',event)" oncontextmenu="return false">.</a>'; } break; case 0: echo '<a></a>'; break; default: echo '<a>', $number, '</a>'; break; } } } ?> </table> <?php if (!empty($lost)) { unset($_SESSION['minesweeper']); echo '<p>You lost :(. <a href="?">Reboot?</a>'; } elseif (!empty($won)) { unset($_SESSION['minesweeper']); echo '<p>Congratulations. You won :).'; }
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#Wren
Wren
import "/fmt" for Fmt import "/big" for BigInt   var b10 = Fn.new { |n| if (n == 1) { Fmt.print("$4d: $28s $-24d", 1, "1", 1) return } var n1 = n + 1 var pow = List.filled(n1, 0) var val = List.filled(n1, 0) var count = 0 var ten = 1 var x = 1 while (x < n1) { val[x] = ten for (j in 0...n1) { if (pow[j] != 0 && pow[(j+ten)%n] == 0 && pow[j] != x) pow[(j+ten)%n] = x } if (pow[ten] == 0) pow[ten] = x ten = (10*ten) % n if (pow[0] != 0) break x = x + 1 } x = n if (pow[0] != 0) { var s = "" while (x != 0) { var p = pow[x%n] if (count > p) s = s + ("0" * (count-p)) count = p - 1 s = s + "1" x = (n + x - val[p]) % n } if (count > 0) s = s + ("0" * count) var mpm = BigInt.new(s) var mul = mpm/n Fmt.print("$4d: $28s $-24i", n, s, mul) } else { System.print("Can't do it!") } }   var start = System.clock var tests = [ [1, 10], [95, 105], [297], [576], [594], [891], [909], [999], [1998], [2079], [2251], [2277], [2439], [2997], [4878] ] System.print(" n B10 multiplier") System.print("----------------------------------------------") for (test in tests) { var from = test[0] var to = from if (test.count == 2) to = test[1] for (n in from..to) b10.call(n) } System.print("\nTook %(System.clock-start) seconds.")
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#Wren
Wren
import "/big" for BigInt   var a = BigInt.new("2988348162058574136915891421498819466320163312926952423791023078876139") var b = BigInt.new("2351399303373464486466122544523690094744975233415544072992656881240319") var m = BigInt.ten.pow(40) System.print(a.modPow(b, m))
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464486466122544523690094744975233415544072992656881240319 {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319} A computer is too slow to find the entire value of   a b {\displaystyle a^{b}} . Instead, the program must use a fast algorithm for modular exponentiation:   a b mod m {\displaystyle a^{b}\mod m} . The algorithm must work for any integers   a , b , m {\displaystyle a,b,m} ,     where   b ≥ 0 {\displaystyle b\geq 0}   and   m > 0 {\displaystyle m>0} .
#zkl
zkl
var BN=Import("zklBigNum"); a:=BN("2988348162058574136915891421498819466320163312926952423791023078876139"); b:=BN("2351399303373464486466122544523690094744975233415544072992656881240319"); m:=BN(10).pow(40); a.powm(b,m).println(); a.powm(b,m) : "%,d".fmt(_).println();
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Raku
Raku
sub MAIN ($beats-per-minute = 72, $beats-per-bar = 4) { my $duration = 60 / $beats-per-minute; my $base-time = now + $duration; my $i;   for $base-time, $base-time + $duration ... * -> $next-time { if $i++ %% $beats-per-bar { print "\nTICK"; } else { print " tick"; } sleep $next-time - now; } }
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#REXX
REXX
/*REXX program simulates a visual (textual) metronome (with no sound). */ parse arg bpm bpb dur . /*obtain optional arguments from the CL*/ if bpm=='' | bpm=="," then bpm=72 /*the number of beats per minute. */ if bpb=='' | bpb=="," then bpb= 4 /* " " " " " bar. */ if dur=='' | dur=="," then dur= 5 /*duration of the run in seconds. */ call time 'Reset' /*reset the REXX elapsed timer. */ bt=1/bpb /*calculate a tock-time interval. */   do until et>=dur; et=time('Elasped') /*process tick-tocks for the duration*/ say; call charout ,'TICK' /*show the first tick for the period. */ es=et+1 /*bump the elapsed time "limiter". */ $t=et+bt do until e>=es; e=time('Elapsed') if e<$t then iterate /*time for tock? */ call charout , ' tock' /*show a "tock". */ $t=$t+bt /*bump the TOCK time.*/ end /*until e≥es*/ end /*until et≥dur*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#Tcl
Tcl
package require Tcl 8.6 package require Thread   # Create the global shared state of the semaphore set handle semaphore0 tsv::set $handle mutex [thread::mutex create] tsv::set $handle cv [thread::cond create] tsv::set $handle count 0 tsv::set $handle max 3   # Make five worker tasks for {set i 0} {$i<5} {incr i} { lappend threads [thread::create -preserved { # Not bothering to wrap this in an object for demonstration proc init {handle} { global mutex cv count max set mutex [tsv::object $handle mutex] set cv [tsv::object $handle cv] set count [tsv::object $handle count] set max [tsv::get $handle max] } proc acquire {} { global mutex cv count max thread::mutex lock [$mutex get] while {[$count get] >= $max} { thread::cond wait [$cv get] [$mutex get] } $count incr thread::mutex unlock [$mutex get] } proc release {} { global mutex cv count max thread::mutex lock [$mutex get] if {[$count get] > 0} { $count incr -1 thread::cond notify [$cv get] } thread::mutex unlock [$mutex get] }   # The core task of the worker proc run {handle id} { init $handle acquire puts "worker $id has acquired the lock" after 2000 release puts "worker $id is done" }   # Wait for further instructions from the main thread thread::wait }] }   # Start the workers doing useful work, giving each a unique id for pretty printing set i 0 foreach t $threads { puts "starting thread [incr i]" thread::send -async $t [list run $handle $i] }   # Wait for all the workers to finish foreach t $threads { thread::release -wait $t }
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Swift
Swift
import Foundation   let size = 12   func printRow(with:Int, upto:Int) {   print(String(repeating: " ", count: (with-1)*4), terminator: "")   for i in with...upto { print(String(format: "%l4d", i*with), terminator: "") } print() }   print(" ", terminator: ""); printRow( with: 1, upto: size) print( String(repeating: "–", count: (size+1)*4 )) for i in 1...size { print(String(format: "%l4d",i), terminator:"") printRow( with: i, upto: size) }  
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Scala
Scala
import scala.language.experimental.macros import scala.reflect.macros.Context   object Macros { def impl(c: Context) = { import c.universe._ c.Expr[Unit](q"""println("Hello World")""") }   def hello: Unit = macro impl }
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Shen
Shen
(define make-list [A|D] -> [cons (make-list A) (make-list D)] X -> X)   (defmacro info-macro [info Exp] -> [output "~A: ~A~%" (make-list Exp) Exp])   (info (* 5 6)) \\ outputs [* 5 6]: 30
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#Erlang
Erlang
  -module(miller_rabin).   -export([is_prime/1, power/2]).   is_prime(1) -> false; is_prime(2) -> true; is_prime(3) -> true; is_prime(N) when N > 3, ((N rem 2) == 0) -> false; is_prime(N) when ((N rem 2) ==1), N < 341550071728321 -> is_mr_prime(N, proving_bases(N)); is_prime(N) when ((N rem 2) == 1) -> is_mr_prime(N, random_bases(N, 100)).     proving_bases(N) when N < 1373653 -> [2, 3]; proving_bases(N) when N < 9080191 -> [31, 73]; proving_bases(N) when N < 25326001 -> [2, 3, 5]; proving_bases(N) when N < 3215031751 -> [2, 3, 5, 7]; proving_bases(N) when N < 4759123141 -> [2, 7, 61]; proving_bases(N) when N < 1122004669633 -> [2, 13, 23, 1662803]; proving_bases(N) when N < 2152302898747 -> [2, 3, 5, 7, 11]; proving_bases(N) when N < 3474749660383 -> [2, 3, 5, 7, 11, 13]; proving_bases(N) when N < 341550071728321 -> [2, 3, 5, 7, 11, 13, 17].     is_mr_prime(N, As) when N>2, N rem 2 == 1 -> {D, S} = find_ds(N), %% this is a test for compositeness; the two case patterns disprove %% compositeness. not lists:any(fun(A) -> case mr_series(N, A, D, S) of [1|_] -> false; % first elem of list = 1 L -> not lists:member(N-1, L) % some elem of list = N-1 end end, As).     find_ds(N) -> find_ds(N-1, 0).     find_ds(D, S) -> case D rem 2 == 0 of true -> find_ds(D div 2, S+1); false -> {D, S} end.     mr_series(N, A, D, S) when N rem 2 == 1 -> Js = lists:seq(0, S), lists:map(fun(J) -> pow_mod(A, power(2, J)*D, N) end, Js).     pow_mod(B, E, M) -> case E of 0 -> 1; _ -> case ((E rem 2) == 0) of true -> (power(pow_mod(B, (E div 2), M), 2)) rem M; false -> (B*pow_mod(B, E-1, M)) rem M end end.     random_bases(N, K) -> [basis(N) || _ <- lists:seq(1, K)].     basis(N) when N>2 -> 1 + random:uniform(N-3). % random:uniform returns a single random number in range 1 -> N-3, to which is added 1, shifting the range to 2 -> N-2     power(B, E) -> power(B, E, 1).   power(_, 0, Acc) -> Acc; power(B, E, Acc) -> power(B, E - 1, B * Acc).
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#CLU
CLU
% Generate Mertens numbers up to a given limit mertens = proc (limit: int) returns (array[int]) M: array[int] := array[int]$fill(1,limit,0) M[1] := 1 for n: int in int$from_to(2,limit) do M[n] := 1 for k: int in int$from_to(2,n) do M[n] := M[n] - M[n/k] end end return (M) end mertens   start_up = proc () max = 1000   po: stream := stream$primary_output() M: array[int] := mertens(max)   stream$putl(po, "The first 99 Mertens numbers are:") for y: int in int$from_to_by(0,90,10) do for x: int in int$from_to(0,9) do stream$putright(po, int$unparse(M[x+y]), 3) except when bounds: stream$putright(po, "", 3) end end stream$putl(po, "") end   eqz: int := 0 crossz: int := 0 for i: int in int$from_to(2,max) do if M[i]=0 then eqz := eqz + 1 if M[i-1]~=0 then crossz := crossz + 1 end end end   stream$putl(po, "M(N) is zero " || int$unparse(eqz) || " times.") stream$putl(po, "M(N) crosses zero " || int$unparse(crossz) || " times.") end start_up
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. MERTENS.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 M PIC S99 OCCURS 1000 TIMES. 03 N PIC 9(4). 03 K PIC 9(4). 03 V PIC 9(4). 03 IS-ZERO PIC 99 VALUE 0. 03 CROSS-ZERO PIC 99 VALUE 0.   01 OUTPUT-FORMAT. 03 OUT-ITEM. 05 OUT-NUM PIC -9. 05 FILLER PIC X VALUE SPACE. 03 OUT-LINE PIC X(30) VALUE SPACES. 03 OUT-PTR PIC 99 VALUE 4.   PROCEDURE DIVISION. BEGIN. PERFORM GENERATE-MERTENS. PERFORM WRITE-TABLE. PERFORM COUNT-ZEROES. STOP RUN.   GENERATE-MERTENS. MOVE 1 TO M(1). PERFORM MERTENS-OUTER-LOOP VARYING N FROM 2 BY 1 UNTIL N IS GREATER THAN 1000.   MERTENS-OUTER-LOOP. MOVE 1 TO M(N). PERFORM MERTENS-INNER-LOOP VARYING K FROM 2 BY 1 UNTIL K IS GREATER THAN N.   MERTENS-INNER-LOOP. DIVIDE N BY K GIVING V. SUBTRACT M(V) FROM M(N).   WRITE-TABLE. DISPLAY "The first 99 Mertens numbers are: " PERFORM WRITE-ITEM VARYING N FROM 1 BY 1 UNTIL N IS GREATER THAN 99.   WRITE-ITEM. MOVE M(N) TO OUT-NUM. STRING OUT-ITEM DELIMITED BY SIZE INTO OUT-LINE WITH POINTER OUT-PTR. IF OUT-PTR IS EQUAL TO 31, DISPLAY OUT-LINE, MOVE 1 TO OUT-PTR.   COUNT-ZEROES. PERFORM TEST-N-ZERO VARYING N FROM 2 BY 1 UNTIL N IS GREATER THAN 1000. DISPLAY "M(N) is zero " IS-ZERO " times.". DISPLAY "M(N) crosses zero " CROSS-ZERO " times.".   TEST-N-ZERO. IF M(N) IS EQUAL TO ZERO, ADD 1 TO IS-ZERO, SUBTRACT 1 FROM N GIVING K, IF M(K) IS NOT EQUAL TO ZERO, ADD 1 TO CROSS-ZERO.
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   const char *menu_select(const char *const *items, const char *prompt);   int main(void) { const char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL}; const char *prompt = "Which is from the three pigs?";   printf("You chose %s.\n", menu_select(items, prompt));   return EXIT_SUCCESS; }   const char * menu_select(const char *const *items, const char *prompt) { char buf[BUFSIZ]; int i; int choice; int choice_max;   if (items == NULL) return NULL;   do { for (i = 0; items[i] != NULL; i++) { printf("%d) %s\n", i + 1, items[i]); } choice_max = i; if (prompt != NULL) printf("%s ", prompt); else printf("Choice? "); if (fgets(buf, sizeof(buf), stdin) != NULL) { choice = atoi(buf); } } while (1 > choice || choice > choice_max);   return items[choice - 1]; }
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#BBC_BASIC
BBC BASIC
PRINT FN_MD5("") PRINT FN_MD5("a") PRINT FN_MD5("abc") PRINT FN_MD5("message digest") PRINT FN_MD5("abcdefghijklmnopqrstuvwxyz") PRINT FN_MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") PRINT FN_MD5(STRING$(8,"1234567890")) END   DEF FN_MD5(message$) LOCAL a%, b%, c%, d%, f%, g%, h0%, h1%, h2%, h3%, i%, bits%, chunk%, temp% LOCAL r&(), k%(), w%() DIM r&(63), k%(63), w%(15)   REM r specifies the per-round shift amounts: r&() = 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   REM Use binary integer part of the sines of integers (Radians) as constants: FOR i% = 0 TO 63 k%(i%) = FN32(INT(ABS(SIN(i% + 1.0#)) * 2^32)) NEXT   REM Initialize variables: h0% = &67452301 h1% = &EFCDAB89 h2% = &98BADCFE h3% = &10325476   bits% = LEN(message$)*8   REM Append '1' bit to message: message$ += CHR$&80   REM Append '0' bits until message length in bits = 448 (mod 512): WHILE (LEN(message$) MOD 64) <> 56 message$ += CHR$0 ENDWHILE   REM Append length of message (before pre-processing), in bits, as REM 64-bit little-endian integer: FOR i% = 0 TO 56 STEP 8 message$ += CHR$(bits% >>> i%) NEXT   REM Process the message in successive 512-bit chunks: FOR chunk% = 0 TO LEN(message$) DIV 64 - 1   REM Break chunk into sixteen 32-bit little-endian words: FOR i% = 0 TO 15 w%(i%) = !(PTR(message$) + 64*chunk% + 4*i%) NEXT i%   REM Initialize hash value for this chunk: a% = h0% b% = h1% c% = h2% d% = h3%   REM Main loop: FOR i% = 0 TO 63 CASE TRUE OF WHEN i% <= 15: f% = d% EOR (b% AND (c% EOR d%)) g% = i% WHEN 16 <= i% AND i% <= 31: f% = c% EOR (d% AND (b% EOR c%)) g% = (5 * i% + 1) MOD 16 WHEN 32 <= i% AND i% <= 47: f% = b% EOR c% EOR d% g% = (3 * i% + 5) MOD 16 OTHERWISE: f% = c% EOR (b% OR (NOT d%)) g% = (7 * i%) MOD 16 ENDCASE   temp% = d% d% = c% c% = b% b% = FN32(b% + FNlrot(FN32(a% + f%) + FN32(k%(i%) + w%(g%)), r&(i%))) a% = temp%   NEXT i%   REM Add this chunk's hash to result so far: h0% = FN32(h0% + a%) h1% = FN32(h1% + b%) h2% = FN32(h2% + c%) h3% = FN32(h3% + d%)   NEXT chunk%   = FNrevhex(h0%) + FNrevhex(h1%) + FNrevhex(h2%) + FNrevhex(h3%)   DEF FNrevhex(A%) SWAP ?(^A%+0),?(^A%+3) SWAP ?(^A%+1),?(^A%+2) = RIGHT$("0000000"+STR$~A%,8)   DEF FNlrot(n#, r%) n# = FN32(n#) = (n# << r%) OR (n# >>> (32 - r%))   DEF FN32(n#) WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE WHILE n# < &80000000 : n# += 2^32 : ENDWHILE = n#
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Forth
Forth
unused . \ memory available for use in dictionary here . \ current dictionary memory pointer : mem, ( addr len -- ) here over allot swap move ; : s, ( str len -- ) here over char+ allot place align ; \ built-in on some forths : ," [char] " parse s, ; variable num create array 60 cells allot create struct 0 , 10 , char A c, ," string" unused . here .
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Fortran
Fortran
program allocation_test implicit none real, dimension(:), allocatable :: vector real, dimension(:, :), allocatable :: matrix real, pointer :: ptr integer, parameter :: n = 100 ! Size to allocate   allocate(vector(n)) ! Allocate a vector allocate(matrix(n, n)) ! Allocate a matrix allocate(ptr) ! Allocate a pointer   deallocate(vector) ! Deallocate a vector deallocate(matrix) ! Deallocate a matrix deallocate(ptr) ! Deallocate a pointer end program allocation_test
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#Phix
Phix
constant patients_txt = split(""" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz""",'\n'), visits_txt = split(""" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3""",'\n') --or, assuming these files contain exactly the same actual raw text, -- and the use of GT_LF_STRIPPED is instead of above split('\n'): --constant patients_txt = get_text("patients.csv",GT_LF_STRIPPED), -- visits_txt = get_text("visits.csv",GT_LF_STRIPPED) function sap(string s) return split(s,',',false)&{"",0,0} end function function svp(string s) return split(s,',',false) end function sequence patient_data = sort(apply(patients_txt[2..$],sap)), visit_data = sort_columns(apply(visits_txt[2..$],svp),{1,-2}) visit_data = append(visit_data,{"","","0"}) -- (add a sentinel) string last_id = "",id,name,dt,scstr,avstr atom score,score_total,average integer visit_count = 0, pdx = 1 for i=1 to length(visit_data) do {id,dt,scstr} = visit_data[i] score = iff(scstr=""?0:scanf(scstr,"%f")[1][1]) if id!=last_id then if visit_count then average = score_total/visit_count patient_data[pdx][4..5] = {score_total,average} end if if i=length(visit_data) then exit end if -- (sentinel) score_total = score visit_count = (score!=0) while id!=patient_data[pdx][1] do pdx += 1 end while patient_data[pdx][3] = dt last_id = id elsif score!=0 then score_total += score visit_count += 1 end if end for printf(1,"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n") for i=1 to length(patient_data) do {id,name,dt,score,average} = patient_data[i] scstr = iff(score=0?"":sprintf("%4.1f",score)) avstr = iff(average=0?"":sprintf("%4.2f",average)) printf(1,"| %-10s |  %-7s | %10s |  %-9s | %-9s |\n", {id,name,dt,scstr,avstr}) end for
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Scala
Scala
object Rs232Pins9 extends App {   val (off: Boolean, on: Boolean) = (false, true) val plug = new Rs232Pins9(carrierDetect = on, receivedData = on) // set first two pins, say   def toOnOff(b: Boolean) = if (b) "on" else "off"   class Rs232Pins9( var carrierDetect: Boolean = off, var receivedData: Boolean = off, var transmittedData: Boolean = off, var dataTerminalReady: Boolean = off, var signalGround: Boolean = off, var dataSetReady: Boolean = off, var requestToSend: Boolean = off, var clearToSend: Boolean = off, var ringIndicator: Boolean = off ) { def setPin(n: Int, v: Boolean) { (n) match { case 1 => carrierDetect = v case 2 => receivedData = v case 3 => transmittedData = v case 4 => dataTerminalReady = v case 5 => signalGround = v case 6 => dataSetReady = v case 7 => requestToSend = v case 8 => clearToSend = v case 9 => ringIndicator = v } } }   // println(toOnOff(plug.component2())) // print value of pin 2 by number plug.transmittedData = on // set pin 3 by name plug.setPin(4, on) // set pin 4 by number // println(toOnOff(plug.component3())) // print value of pin 3 by number println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name }
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window   class MedianFilter { construct new(filename, filename2, windowWidth, windowHeight) { Window.title = "Median filter" var image = ImageData.loadFromFile(filename) Window.resize(image.width, image.height) Canvas.resize(image.width, image.height) _ww = windowWidth _wh = windowHeight // split off the left half _image = ImageData.create(filename2, image.width/2, image.height) _name = filename2 for (x in 0...image.width/2) { for (y in 0...image.height) _image.pset(x, y, image.pget(x, y)) } // display it on the left before filtering _image.draw(0, 0) }   luminance(c) { 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b }   medianFilter(windowWidth, windowHeight) { var window = List.filled(windowWidth * windowHeight, Color.black) var edgeX = (windowWidth / 2).floor var edgeY = (windowHeight / 2).floor var comparer = Fn.new { |a, b| luminance(a) < luminance(b) } for (x in edgeX..._image.width - edgeX) { for (y in edgeY..._image.height - edgeY) { var i = 0 for (fx in 0...windowWidth) { for (fy in 0...windowHeight) { window[i] = _image.pget(x + fx - edgeX, y + fy - edgeY) i = i + 1 } } window.sort(comparer) _image.pset(x, y, window[((windowWidth * windowHeight)/2).floor]) } } }   init() { medianFilter(_ww, _wh) // display it on the right after filtering _image.draw(_image.width, 0) // save it to a file _image.saveToFile(_name) }   update() {}   draw(alpha) {} }   var Game = MedianFilter.new("Medianfilterp.png", "Medianfilterp2.png", 3, 3)
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.
#CLU
CLU
middle_three_digits = proc (n: int) returns (string) signals (too_small, even_length) s: string := int$unparse(int$abs(n)) if string$size(s) < 3 then signal too_small end if string$size(s) // 2 = 0 then signal even_length end return(string$substr(s, string$size(s)/2, 3)) end middle_three_digits   start_up = proc () po: stream := stream$primary_output() tests: sequence[int] := sequence[int]$ [123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345, 1,2,-1,-10,2002,-2002,0]   for test: int in sequence[int]$elements(tests) do stream$putright(po, int$unparse(test) || ": ", 11)   stream$putl(po, middle_three_digits(test)) except when too_small: stream$putl(po, "Too small") when even_length: stream$putl(po, "Even length") end end end start_up
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#PicoLisp
PicoLisp
# NIL Hidden: Empty field # T Hidden: Mine # 0-8 Marked: Empty field # ? Marked: Mine   (de minesweeper (DX DY Density) (default Density 20) (setq *Field (make (do DY (link (need DX))))) (use (X Y) (do (prinl "Number of mines: " (*/ DX DY Density 100)) (while (get *Field (setq Y (rand 1 DY)) (setq X (rand 1 DX)) ) ) (set (nth *Field Y X) T) ) ) (showMines) )   (de showMines () (for L *Field (for F L (prin (if (flg? F) "." F)) ) (prinl) ) )   (de *NeighborX -1 0 +1 -1 +1 -1 0 +1) (de *NeighborY -1 -1 -1 0 0 +1 +1 +1)   (de c (X Y) (if (=T (get *Field Y X)) "KLABOOM!! You hit a mine." (let Visit NIL (recur (X Y) (when (=0 (set (nth *Field Y X) (cnt '((DX DY) (=T (get *Field (+ Y DY) (+ X DX))) ) *NeighborX *NeighborY ) ) ) (mapc '((DX DY) (and (get *Field (inc 'DY Y)) (nth @ (inc 'DX X)) (not (member (cons DX DY) Visit)) (push 'Visit (cons DX DY)) (recurse DX DY) ) ) *NeighborX *NeighborY ) ) ) ) (showMines) ) )   (de m (X Y) (set (nth *Field Y X) '?) (showMines) (unless (fish =T *Field) "Congratulations! You won!!" ) )
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10". Task Write a routine to find the B10 of a given integer. E.G. n B10 n × multiplier 1 1 ( 1 × 1 ) 2 10 ( 2 × 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the B10 value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find B10 for: 1998, 2079, 2251, 2277 Stretch goal; find B10 for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation. See also OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. How to find Minimum Positive Multiple in base 10 using only 0 and 1
#zkl
zkl
var [const] B10_4=10*10*10*10, HexB10=T(0000,0001,0010,0011,0100,0101,0110,0111, 1000,1001,1010,1011,1100,1101,1110,1111);   // Convert n from binary as if it is Base 10 // limited for Uint64 to 2^20-1= 1048575 ala 19 digits // for int64, limited to 2^19-1= 524287, conv2B10()-->1111111111111111111 const B10_MAX=(2).pow(19) - 1;   fcn conv2B10(n){ facB10,result := 1,0; while(n>0){ result=facB10*HexB10[n.bitAnd(15)] + result; n=n/16; facB10*=B10_4; } result } fcn findB10(n){ // --> -1 if overflow signed 64 bit int i:=0; while(i<B10_MAX){ if(conv2B10( i+=1 )%n == 0) return(conv2B10(i)); } return(-1); // overflow 64 bit signed int }
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Ruby
Ruby
  #!/usr/bin/ruby   bpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided msr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided i = 0   loop do (msr-1).times do puts "\a" sleep(60.0/bpm) end puts "\aAND #{i += 1}" sleep(60.0/bpm) end  
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Scala
Scala
def metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MaxValue) { val delay = 60000L / bpm var beats = 0 do { Thread.sleep(delay) if (beats % bpb == 0) print("\nTICK ") else print("tick ") beats+=1 } while (beats < maxBeats) println() }   metronome(120, 4, 20) // limit to 20
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#UnixPipes
UnixPipes
rm -f sem ; mkfifo sem   acquire() { x='';while test -z "$x"; do read x; done; }   release() { echo '1' }   job() { n=$1; echo "Job $n acquired Semaphore">&2 ; sleep 2; echo "Job $n released Semaphore">&2 ; }   ( acquire < sem ; job 1 ; release > sem ) & ( acquire < sem ; job 2 ; release > sem ) & ( acquire < sem ; job 3 ; release > sem ) &   echo 'Initialize Jobs' >&2 ; echo '1' > sem
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#Visual_Basic_.NET
Visual Basic .NET
Dim sem As New Semaphore(5, 5) 'Indicates that up to 5 resources can be aquired sem.WaitOne() 'Blocks until a resouce can be aquired Dim oldCount = sem.Release() 'Returns a resource to the pool 'oldCount has the Semaphore's count before Release was called
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Tailspin
Tailspin
  templates formatN&{width:} [ 1..$width -> ' ', '$;'... ] -> '$(last-$width+1..last)...;' ! end formatN   ' |$:1..12 -> formatN&{width: 4}; ' -> !OUT::write '--+$:1..12*4 -> '-'; ' -> !OUT::write 1..12 -> \( def row: $; '$ -> formatN&{width:2};|$:1..($-1)*4 -> ' ';$:$..12 -> $*$row -> formatN&{width:4}; ' ! \) -> !OUT::write  
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Sidef
Sidef
class Number { method ⊕(arg) { self + arg } }   say (21 ⊕ 42)
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Smalltalk
Smalltalk
apiSyslog:priority format:format message:message <cdecl: int 'syslog' (int char* char*) > ^ self primitiveFailed.  
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#SNOBOL4
SNOBOL4
  OPSYN('SAME','IDENT') OPSYN('$','*',1)  
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#F.23
F#
  // Miller primality test for n<3317044064679887385961981. Nigel Galloway: April 1st., 2021 let a=[(2047I,[2I]);(1373653I,[2I;3I]);(9080191I,[31I;73I]);(25326001I,[2I;3I;5I]);(3215031751I,[2I;3I;5I;7I]);(4759123141I,[2I;7I;61I]);(1122004669633I,[2I;13I;23I;1662803I]); (2152302898747I,[2I;3I;5I;7I;11I]);(3474749660383I,[2I;3I;5I;7I;11I;13I]);(341550071728321I,[2I;3I;5I;7I;11I;13I;17I]);(3825123056546413051I,[2I;3I;5I;7I;11I;13I;17I;19I;23I]); (18446744073709551616I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I]);(318665857834031151167461I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I]);(3317044064679887385961981I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I;41I])] let rec fN g=function (n:bigint) when n.IsEven->fN(g+1)(n/2I) |n->(n,g) let rec fG n d r=function a::t->match bigint.ModPow(a,d,n) with g when g=1I || g=n-1I->fG n d r t |g->fL(bigint.ModPow(g,2I,n)) n d t r |_->true and fL x n d a=function 1->false |r when x=n-1I->fG n d r a |r->fL(bigint.ModPow(x,2I,n)) n d a (r-1) let mrP n=let (d,r)=fN 0 (n-1I) in fG n d r (snd(a|>List.find(fst>>(<)n)))   printfn "%A %A" (mrP 2147483647I)(mrP 844674407370955389I)  
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#Cowgol
Cowgol
include "cowgol.coh";   const MAX := 1000;   # Table output sub printtab(n: int8) is if n<0 then print_char('-'); n := -n; else print_char(' '); end if; print_char(n as uint8 + '0'); print_char(' '); end sub;   # Generate Merten numbers var M: int8[MAX+1]; M[0] := 0; M[1] := 1;   var n: @indexof M := 2; while n < @sizeof M loop M[n] := 1; var k: @indexof M := 2; while k <= n loop M[n] := M[n] - M[n/k]; k := k + 1; end loop; n := n + 1; end loop;   # Find zeroes and crossings var zero: uint8 := 0; var cross: uint8 := 0; n := 1; while n < @sizeof M loop if M[n] == 0 then zero := zero + 1; if M[n-1] != 0 then cross := cross + 1; end if; end if; n := n + 1; end loop;   # Print table print("The first 99 Mertens numbers are:\n"); print(" "); n := 1; var col: uint8 := 9; while n < 100 loop printtab(M[n]); col := col - 1; if col == 0 then print_nl(); col := 10; end if; n := n + 1; end loop;   print("M(n) is zero "); print_i8(zero); print(" times\n"); print("M(n) crosses zero "); print_i8(cross); print(" times\n");
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#Delphi
Delphi
  program Mertens_function;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TMertens = record merts: TArray<Integer>; zeros, crosses: Integer; class function Mertens(_to: Integer): TMertens; static; end;   { TMertens }   class function TMertens.Mertens(_to: Integer): TMertens; var sum, zeros, crosses: Integer; begin if _to < 1 then _to := 1;   sum := 0; zeros := 0; crosses := 0;   SetLength(Result.merts, _to + 1); var primes := [2]; for var i := 1 to _to do begin var j := i; var cp := 0; var spf := false; for var p in primes do begin if p > j then Break; if j mod p = 0 then begin j := j div p; inc(cp); end;   if j mod p = 0 then begin spf := true; Break; end; end; if (cp = 0) and (i > 2) then begin cp := 1; SetLength(primes, Length(primes) + 1); primes[High(primes)] := i; end;   if not spf then begin if cp mod 2 = 0 then inc(sum) else dec(sum); end;   Result.merts[i] := sum; if sum = 0 then begin inc(zeros); if (i > 1) and (Result.merts[i - 1] <> 0) then inc(crosses); end; end; Result.zeros := zeros; Result.crosses := crosses; end;   begin var m := TMertens.mertens(1000); writeln('Mertens sequence - First 199 terms:'); for var i := 0 to 199 do begin if i = 0 then begin write(' '); Continue; end; if i mod 20 = 0 then writeln; write(format(' %3d', [m.merts[i]])); end; writeln(#10#10'Equals zero ', m.zeros, ' times between 1 and 1000'); writeln(#10'Crosses zero ', m.crosses, ' times between 1 and 1000'); {$IFNDEF UNIX} readln; {$ENDIF} 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.
#C.23
C#
  using System; using System.Collections.Generic;   public class Menu { static void Main(string[] args) { List<string> menu_items = new List<string>() { "fee fie", "huff and puff", "mirror mirror", "tick tock" }; //List<string> menu_items = new List<string>(); Console.WriteLine(PrintMenu(menu_items)); Console.ReadLine(); } private static string PrintMenu(List<string> items) { if (items.Count == 0) return "";   string input = ""; int i = -1; do { for (int j = 0; j < items.Count; j++) Console.WriteLine("{0}) {1}", j, items[j]);   Console.WriteLine("What number?"); input = Console.ReadLine();   } while (!int.TryParse(input, out i) || i >= items.Count || i < 0); return items[i]; } }  
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#C
C
  /// Represent digest with ABCD sealed public class Digest { public uint A; public uint B; public uint C; public uint D;   public Digest() { A=(uint)MD5InitializerConstant.A; B=(uint)MD5InitializerConstant.B; C=(uint)MD5InitializerConstant.C; D=(uint)MD5InitializerConstant.D; }   public override string ToString() { string st ; st= MD5Helper.ReverseByte(A).ToString("X8")+ MD5Helper.ReverseByte(B).ToString("X8")+ MD5Helper.ReverseByte(C).ToString("X8")+ MD5Helper.ReverseByte(D).ToString("X8"); return st;   } }   public class MD5 { /***********************VARIABLES************************************/     /***********************Statics**************************************/ /// <summary> /// lookup table 4294967296*sin(i) /// </summary> protected readonly static uint [] T =new uint[64] { 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391};   /*****instance variables**************/ /// <summary> /// X used to proces data in /// 512 bits chunks as 16 32 bit word /// </summary> protected uint [] X = new uint [16];   /// <summary> /// the finger print obtained. /// </summary> protected Digest dgFingerPrint;   /// <summary> /// the input bytes /// </summary> protected byte [] m_byteInput;       /**********************EVENTS AND DELEGATES*******************************************/   public delegate void ValueChanging (object sender,MD5ChangingEventArgs Changing); public delegate void ValueChanged (object sender,MD5ChangedEventArgs Changed);     public event ValueChanging OnValueChanging; public event ValueChanged OnValueChanged;       /********************************************************************/ /***********************PROPERTIES ***********************/ /// <summary> ///gets or sets as string /// </summary> public string Value { get { string st ; char [] tempCharArray= new Char[m_byteInput.Length];   for(int i =0; i<m_byteInput.Length;i++) tempCharArray[i]=(char)m_byteInput[i];   st= new String(tempCharArray); return st; } set { /// raise the event to notify the changing if (this.OnValueChanging !=null) this.OnValueChanging(this,new MD5ChangingEventArgs(value));     m_byteInput=new byte[value.Length]; for (int i =0; i<value.Length;i++) m_byteInput[i]=(byte)value[i]; dgFingerPrint=CalculateMD5Value();   /// raise the event to notify the change if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString()));   } }   /// <summary> /// get/sets as byte array /// </summary> public byte [] ValueAsByte { get { byte [] bt = new byte[m_byteInput.Length]; for (int i =0; i<m_byteInput.Length;i++) bt[i]=m_byteInput[i]; return bt; } set { /// raise the event to notify the changing if (this.OnValueChanging !=null) this.OnValueChanging(this,new MD5ChangingEventArgs(value));   m_byteInput=new byte[value.Length]; for (int i =0; i<value.Length;i++) m_byteInput[i]=value[i]; dgFingerPrint=CalculateMD5Value();     /// notify the changed value if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString())); } }   //gets the signature/figner print as string public string FingerPrint { get { return dgFingerPrint.ToString(); } }     /*************************************************************************/ /// <summary> /// Constructor /// </summary> public MD5() { Value=""; }     /******************************************************************************/ /*********************METHODS**************************/   /// <summary> /// calculat md5 signature of the string in Input /// </summary> /// <returns> Digest: the finger print of msg</returns> protected Digest CalculateMD5Value() { /***********vairable declaration**************/ byte [] bMsg; //buffer to hold bits uint N; //N is the size of msg as word (32 bit) Digest dg =new Digest(); // the value to be returned   // create a buffer with bits padded and length is alos padded bMsg=CreatePaddedBuffer();   N=(uint)(bMsg.Length*8)/32; //no of 32 bit blocks   for (uint i=0; i<N/16;i++) { CopyBlock(bMsg,i); PerformTransformation(ref dg.A,ref dg.B,ref dg.C,ref dg.D); } return dg; }   /******************************************************** * TRANSFORMATIONS : FF , GG , HH , II acc to RFC 1321 * where each Each letter represnets the aux function used *********************************************************/       /// <summary> /// perform transformatio using f(((b&c) | (~(b)&d)) /// </summary> protected void TransF(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + ((b&c) | (~(b)&d)) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using g((b&d) | (c & ~d) ) /// </summary> protected void TransG(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + ((b&d) | (c & ~d) ) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using h(b^c^d) /// </summary> protected void TransH(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + (b^c^d) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using i (c^(b|~d)) /// </summary> protected void TransI(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + (c^(b|~d))+ X[k] + T[i-1]), s); }       /// <summary> /// Perform All the transformation on the data /// </summary> /// <param name="A">A</param> /// <param name="B">B </param> /// <param name="C">C</param> /// <param name="D">D</param> protected void PerformTransformation(ref uint A,ref uint B,ref uint C, ref uint D) { //// saving ABCD to be used in end of loop   uint AA,BB,CC,DD;   AA=A; BB=B; CC=C; DD=D;   /* Round 1 * [ABCD 0 7 1] [DABC 1 12 2] [CDAB 2 17 3] [BCDA 3 22 4] * [ABCD 4 7 5] [DABC 5 12 6] [CDAB 6 17 7] [BCDA 7 22 8] * [ABCD 8 7 9] [DABC 9 12 10] [CDAB 10 17 11] [BCDA 11 22 12] * [ABCD 12 7 13] [DABC 13 12 14] [CDAB 14 17 15] [BCDA 15 22 16] * * */ TransF(ref A,B,C,D,0,7,1);TransF(ref D,A,B,C,1,12,2);TransF(ref C,D,A,B,2,17,3);TransF(ref B,C,D,A,3,22,4); TransF(ref A,B,C,D,4,7,5);TransF(ref D,A,B,C,5,12,6);TransF(ref C,D,A,B,6,17,7);TransF(ref B,C,D,A,7,22,8); TransF(ref A,B,C,D,8,7,9);TransF(ref D,A,B,C,9,12,10);TransF(ref C,D,A,B,10,17,11);TransF(ref B,C,D,A,11,22,12); TransF(ref A,B,C,D,12,7,13);TransF(ref D,A,B,C,13,12,14);TransF(ref C,D,A,B,14,17,15);TransF(ref B,C,D,A,15,22,16); /** rOUND 2 **[ABCD 1 5 17] [DABC 6 9 18] [CDAB 11 14 19] [BCDA 0 20 20] *[ABCD 5 5 21] [DABC 10 9 22] [CDAB 15 14 23] [BCDA 4 20 24] *[ABCD 9 5 25] [DABC 14 9 26] [CDAB 3 14 27] [BCDA 8 20 28] *[ABCD 13 5 29] [DABC 2 9 30] [CDAB 7 14 31] [BCDA 12 20 32] */ TransG(ref A,B,C,D,1,5,17);TransG(ref D,A,B,C,6,9,18);TransG(ref C,D,A,B,11,14,19);TransG(ref B,C,D,A,0,20,20); TransG(ref A,B,C,D,5,5,21);TransG(ref D,A,B,C,10,9,22);TransG(ref C,D,A,B,15,14,23);TransG(ref B,C,D,A,4,20,24); TransG(ref A,B,C,D,9,5,25);TransG(ref D,A,B,C,14,9,26);TransG(ref C,D,A,B,3,14,27);TransG(ref B,C,D,A,8,20,28); TransG(ref A,B,C,D,13,5,29);TransG(ref D,A,B,C,2,9,30);TransG(ref C,D,A,B,7,14,31);TransG(ref B,C,D,A,12,20,32); /* rOUND 3 * [ABCD 5 4 33] [DABC 8 11 34] [CDAB 11 16 35] [BCDA 14 23 36] * [ABCD 1 4 37] [DABC 4 11 38] [CDAB 7 16 39] [BCDA 10 23 40] * [ABCD 13 4 41] [DABC 0 11 42] [CDAB 3 16 43] [BCDA 6 23 44] * [ABCD 9 4 45] [DABC 12 11 46] [CDAB 15 16 47] [BCDA 2 23 48] * */ TransH(ref A,B,C,D,5,4,33);TransH(ref D,A,B,C,8,11,34);TransH(ref C,D,A,B,11,16,35);TransH(ref B,C,D,A,14,23,36); TransH(ref A,B,C,D,1,4,37);TransH(ref D,A,B,C,4,11,38);TransH(ref C,D,A,B,7,16,39);TransH(ref B,C,D,A,10,23,40); TransH(ref A,B,C,D,13,4,41);TransH(ref D,A,B,C,0,11,42);TransH(ref C,D,A,B,3,16,43);TransH(ref B,C,D,A,6,23,44); TransH(ref A,B,C,D,9,4,45);TransH(ref D,A,B,C,12,11,46);TransH(ref C,D,A,B,15,16,47);TransH(ref B,C,D,A,2,23,48); /*ORUNF 4 *[ABCD 0 6 49] [DABC 7 10 50] [CDAB 14 15 51] [BCDA 5 21 52] *[ABCD 12 6 53] [DABC 3 10 54] [CDAB 10 15 55] [BCDA 1 21 56] *[ABCD 8 6 57] [DABC 15 10 58] [CDAB 6 15 59] [BCDA 13 21 60] *[ABCD 4 6 61] [DABC 11 10 62] [CDAB 2 15 63] [BCDA 9 21 64] * */ TransI(ref A,B,C,D,0,6,49);TransI(ref D,A,B,C,7,10,50);TransI(ref C,D,A,B,14,15,51);TransI(ref B,C,D,A,5,21,52); TransI(ref A,B,C,D,12,6,53);TransI(ref D,A,B,C,3,10,54);TransI(ref C,D,A,B,10,15,55);TransI(ref B,C,D,A,1,21,56); TransI(ref A,B,C,D,8,6,57);TransI(ref D,A,B,C,15,10,58);TransI(ref C,D,A,B,6,15,59);TransI(ref B,C,D,A,13,21,60); TransI(ref A,B,C,D,4,6,61);TransI(ref D,A,B,C,11,10,62);TransI(ref C,D,A,B,2,15,63);TransI(ref B,C,D,A,9,21,64);     A=A+AA; B=B+BB; C=C+CC; D=D+DD;     }     /// <summary> /// Create Padded buffer for processing , buffer is padded with 0 along /// with the size in the end /// </summary> /// <returns>the padded buffer as byte array</returns> protected byte[] CreatePaddedBuffer() { uint pad; //no of padding bits for 448 mod 512 byte [] bMsg; //buffer to hold bits ulong sizeMsg; //64 bit size pad uint sizeMsgBuff; //buffer size in multiple of bytes int temp=(448-((m_byteInput.Length*8)%512)); //temporary     pad = (uint )((temp+512)%512); //getting no of bits to be pad if (pad==0) ///pad is in bits pad=512; //at least 1 or max 512 can be added   sizeMsgBuff= (uint) ((m_byteInput.Length)+ (pad/8)+8); sizeMsg=(ulong)m_byteInput.Length*8; bMsg=new byte[sizeMsgBuff]; ///no need to pad with 0 coz new bytes // are already initialize to 0 :)         ////copying string to buffer for (int i =0; i<m_byteInput.Length;i++) bMsg[i]=m_byteInput[i];   bMsg[m_byteInput.Length]|=0x80; ///making first bit of padding 1,   //wrting the size value for (int i =8; i >0;i--) bMsg[sizeMsgBuff-i]=(byte) (sizeMsg>>((8-i)*8) & 0x00000000000000ff);   return bMsg; }     /// <summary> /// Copies a 512 bit block into X as 16 32 bit words /// </summary> /// <param name="bMsg"> source buffer</param> /// <param name="block">no of block to copy starting from 0</param> protected void CopyBlock(byte[] bMsg,uint block) {   block=block<<6; for (uint j=0; j<61;j+=4) { X[j>>2]=(((uint) bMsg[block+(j+3)]) <<24 ) | (((uint) bMsg[block+(j+2)]) <<16 ) | (((uint) bMsg[block+(j+1)]) <<8 ) | (((uint) bMsg[block+(j)]) ) ;   } } }    
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#FreeBASIC
FreeBASIC
Dim As Integer size = 12345 Dim As Integer mem = size-1 Print size; " bytes of heap allocated at " ; mem Clear (mem, , 10) Print size; " bytes of heap allocated at " ; mem
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Go
Go
func inc(n int) { x := n + 1 println(x) }
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#Perl
Perl
#!/usr/bin/perl my $fmt = '| %-11s' x 5 . "|\n"; printf $fmt, qw( PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG); my ($names, $visits) = do { local $/; split /^\n/m, <DATA> }; my %score; for ( $visits =~ /^\d.*/gm ) { my ($id, undef, $score) = split /,/; $score{$id} //= ['', '']; $score and $score{$id}[0]++, $score{$id}[1] += $score; } for ( sort $names =~ /^\d.*/gm ) { my ($id, $name) = split /,/; printf $fmt, $id, $name, ( sort $visits =~ /^$id,(.*?),/gm, '' )[-1], $score{$id}[0] ? ( $score{$id}[1], $score{$id}[1] / $score{$id}[0]) : ('', ''); }   __DATA__ PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz   PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Tcl
Tcl
set rs232_bits {CD RD TD DTR SG DSR RTS CTS RI}   proc rs232_encode args { set res 0 foreach arg $args { set pos [lsearch $::rs232_bits $arg] if {$pos >=0} {set res [expr {$res | 1<<$pos}]} } return $res } proc rs232_decode int { set res {} set i -1 foreach bit $::rs232_bits { incr i if {$int & 1<<$i} {lappend res $bit} } return $res } #------------------------------ Test suite foreach {test => expected} { {rs232_encode CD} -> 1 {rs232_decode 1} -> CD {rs232_encode CD RD TD} -> 7 {rs232_decode 7} -> {CD RD TD} } { catch $test res if {$res ne $expected} {puts "$test -> $res, expected $expected"} }
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Wren
Wren
import "/seq" for Lst import "/fmt" for Fmt   var ON = true var OFF = false   // Converts "ON"/"OFF" string to true/false. var AsBool = Fn.new { |s| s == "ON" }   class RS232_9 { static names { ["CD", "RD", "TD", "DTR", "SG", "DSR", "RTS", "CTS", "RI"] }   construct new() { _settings = [OFF] * 9 } // all pins OFF   // get pin setting as an ON/OFF string by pin name or number; returns null if invalid [p] { if (p is String) { var ix = Lst.indexOf(RS232_9.names, p) return (ix >= 0 && ix < 9) ? (_settings[ix] ? "ON" : "OFF") : null } if (p is Num) { return (p.isInteger && p >= 1 && p <= 9) ? (_settings[p-1] ? "ON" : "OFF") : null } return null }   // set pin by pin name or number; does nothing if invalid [p] = (v) { if (v.type == String && (v == "ON" || v == "OFF")) v = AsBool.call(v) if (v.type != Bool) return if (p is String) { var ix = Lst.indexOf(RS232_9.names, p) if (ix >= 0 && ix < 9) _settings[ix] = v } if (p is Num && p.isInteger && p >= 1 && p <= 9) _settings[p-1] = v }   // prints all pin settings toString { (1..9).map { |i| "%(i) %(Fmt.s(-3, RS232_9.names[i-1])) = %(this[i])" }.join("\n") } }   var plug = RS232_9.new() plug["CD"] = ON // set pin 1 by name plug[3] = ON // set pin 3 by number plug["DSR"] = "ON" // set pin 6 by name and using a string System.print(plug) // print the state of the pins
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#zkl
zkl
fcn medianFilter(img){ //-->new image var [const] window=[-2..2].walk(), edge=(window.len()/2); // 5x5 window   MX,MY,new := img.w,img.h,PPM(MX,MY); pixel,pixels:=List(),List(); foreach x,y in ([edge..MX-edge-1],[edge..MY-edge-1]){ pixels.clear(); foreach ox,oy in (window,window){ // construct sorted list as pixels are read. pixels.merge(pixel.clear(img[x+ox, y+oy])); // merge sort two lists } new[x,y]=pixels[4]; // median value } new }
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.
#COBOL
COBOL
identification division. program-id. middle3. environment division. data division. working-storage section. 01 num pic 9(9). 88 num-too-small values are -99 thru 99. 01 num-disp pic ---------9.   01 div pic 9(9). 01 mod pic 9(9). 01 mod-disp pic 9(3).   01 digit-counter pic 999. 01 digit-div pic 9(9). 88 no-more-digits value 0. 01 digit-mod pic 9(9). 88 is-even value 0.   01 multiplier pic 9(9).   01 value-items. 05 filler pic s9(9) value 123. 05 filler pic s9(9) value 12345. 05 filler pic s9(9) value 1234567. 05 filler pic s9(9) value 987654321. 05 filler pic s9(9) value 10001. 05 filler pic s9(9) value -10001. 05 filler pic s9(9) value -123. 05 filler pic s9(9) value -100. 05 filler pic s9(9) value 100. 05 filler pic s9(9) value -12345. 05 filler pic s9(9) value 1. 05 filler pic s9(9) value 2. 05 filler pic s9(9) value -1. 05 filler pic s9(9) value -10. 05 filler pic s9(9) value 2002. 05 filler pic s9(9) value -2002. 05 filler pic s9(9) value 0.   01 value-array redefines value-items. 05 items pic s9(9) occurs 17 times indexed by item.   01 result pic x(20).   procedure division. 10-main. perform with test after varying item from 1 by 1 until items(item) = 0 move items(item) to num move items(item) to num-disp perform 20-check display num-disp " --> " result end-perform. stop run.   20-check. if num-too-small move "Number too small" to result exit paragraph end-if.   perform 30-count-digits. divide digit-counter by 2 giving digit-div remainder digit-mod. if is-even move "Even number of digits" to result exit paragraph end-if.   *> if digit-counter is 5, mul by 10 *> if digit-counter is 7, mul by 100 *> if digit-counter is 9, mul by 1000   if digit-counter > 3 compute multiplier rounded = 10 ** (((digit-counter - 5) / 2) + 1) divide num by multiplier giving num divide num by 1000 giving div remainder mod move mod to mod-disp else move num to mod-disp end-if. move mod-disp to result. exit paragraph.   30-count-digits. move zeroes to digit-counter. move num to digit-div. perform with test before until no-more-digits divide digit-div by 10 giving digit-div remainder digit-mod add 1 to digit-counter end-perform. exit paragraph.
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#Prolog
Prolog
:- use_module(library(clpfd)).   % Play - run the minesweeper game with a specified width and height play(W,H) :- format(' Welcome to prolog minesweeper! : o X Y exposes a cell of the grid : m X Y marks bombs   Any else to quit. '),   make_grid(W, H, Grid), !, play(Grid), !.   play(Grid) :- % win condition is true map_grid(won, Grid), map_grid(print_cell, Grid), writeln('you won!').   play(Grid) :- % lose condition is true \+ map_grid(still_playing, Grid), map_grid(print_cell, Grid), writeln('you hit a bomb!').   play(Grid) :- % stil playing map_grid(print_cell, Grid), parse_input(Op, X, Y), do_op(Op, p(X,Y), Grid, Grid2), !, play(Grid2).   /* Create a new Grid * * The grid is created initially as a flat list, and after everything * has been populated is converted into a 2 dimensional array. */ make_grid(W, H, grid(W,H,MappedCells)) :- % create a flat list Len is W * H, length(Cells, Len),   % create a list of bombs that is 20% of the grid list NBombs is W * H / 5, floor(NBombs, NBint), format('There are ~w bombs on the grid~n', NBint), length(AllBombs, NBint), maplist(=('?'), AllBombs), % add the bombs to the start of the grid list map_bombs_to_cells(Cells, AllBombs, NewC),   % randomise and convert to a 2D array random_permutation(NewC, RCells), convert_col(RCells, W, H, CreatedCells),   % populate the hidden part of the grid with number of bombs next to each cell map_grid(adj_bomb(grid(W,H,CreatedCells)), grid(W,H,CreatedCells), grid(W,H,MappedCells)).   % puts the bombs at the start of the flat list before shuffling. map_bombs_to_cells(C, [], C). map_bombs_to_cells([_|Ct], [B|Bt], [B|R]) :- map_bombs_to_cells(Ct, Bt, R).   convert_row(T, 0, [], T). convert_row([H|T], W, [H|R], Rem) :- dif(W, 0), succ(W1, W), convert_row(T, W1, R, Rem).   convert_col([], _, 0, []). convert_col(C, W, H, [Row|MoreCells]) :- dif(H, 0), succ(H1, H), convert_row(C, W, Row, Rem), convert_col(Rem, W, H1, MoreCells).   % determine the number of bombs next to a cell (use mapgrid) adj_bomb(_, _, _, C, cell('.',C)) :- C =@= '?'. adj_bomb(Grid, p(X,Y), D, Cell, cell('.',NBombs)) :- dif(Cell, '?'), findall(p(Ax,Ay), ( adj(p(X,Y), D, p(Ax,Ay)), indomain(Ax), indomain(Ay), grid_val_xy(Grid, p(Ax,Ay), Val), Val =@= '?' ), Bombs), length(Bombs, NBombs).   % Print the grid (use mapgrid) print_cell(p(X,_), dim(X,_), cell(C,A), cell(C,A)) :- format("~w~n", C). print_cell(p(X,_), dim(W,_), cell(C,A), cell(C,A)) :- dif(X,W), format("~w ", C).   % determine if we have lost yet or not (use mapgrid). still_playing(_,_,cell(A,_),_) :- A \= '*'.   % determine if we have won yet or not (use mapgrid). won(_,_,cell(N,N),_) :- integer(N). won(_,_,cell('?','?'),_).   % Operate on all cells in a grid, this is a meta predicate that is % applied several times throughout the code map_grid(Goal, G) :- map_grid(Goal, G, G).   map_grid(Goal, grid(W,H,Cells), grid(W,H,OutCells)) :- map_grid_col(Cells, 1, dim(W,H), Goal, OutCells).   map_grid_col([], _, _, _, []). map_grid_col([H|T], Y, D, Goal, [NRow|NCol]) :- map_grid_row(H, p(1, Y), D, Goal, NRow), succ(Y, Y1), map_grid_col(T, Y1, D, Goal, NCol).   map_grid_row([], _, _, _, []). map_grid_row([H|T], p(X, Y), D, Goal, [Cell|R]) :- call(Goal, p(X, Y), D, H, Cell), succ(X, X1), map_grid_row(T, p(X1, Y), D, Goal, R).   % Get a value from the grid by X Y grid_val_xy(grid(_,_,Cells), p(X,Y), Val) :- nth1(Y, Cells, Row), nth1(X, Row, Val).   % Set a value on the grid by X Y grid_set_xy(grid(W,H,Cells), p(X,Y), Val, grid(W,H,NewCells)) :- grid_set_col(Cells, X, Y, Val, NewCells). grid_set_col([H|T], X, 1, Val, [Row|T]) :- grid_set_row(H, X, Val, Row). grid_set_col([H|T], X, Y, Val, [H|New]) :- dif(Y, 0), succ(Y1, Y), grid_set_col(T, X, Y1, Val, New). grid_set_row([_|T], 1, Val, [Val|T]). grid_set_row([H|T], X, Val, [H|New]) :- dif(X, 0), succ(X1, X), grid_set_row(T, X1, Val, New).   % All coordinates adjacent to an x,y position adj(p(X,Y), dim(W,H), p(Ax,Ay)) :-   dif(p(X,Y),p(Ax,Ay)),   % adjacent X Ax in 1..W, Xmin #= X-1, Xmax #= X+1, Ax in Xmin..Xmax,   % adjacent Y Ay in 1..H, Ymin #= Y-1, Ymax #= Y+1, Ay in Ymin..Ymax.   % get user operation from input parse_input(Op, X, Y) :- read_line_to_codes(user_input, In), maplist(char_code, InChars, In), phrase(mine_op(Op, X, Y), InChars, []).   mine_op(mark, X, Y) --> [m], [' '], coords(X, Y). mine_op(open, X, Y) --> [o], [' '], coords(X, Y). coords(Xi, Yi) --> number_(X), { number_chars(Xi, X) }, [' '], number_(Y), { number_chars(Yi, Y) }.   number_([D|T]) --> digit(D), number_(T). number_([D]) --> digit(D). digit(D) --> [D], { char_type(D, digit) }.     % Do mark operation do_op(mark, P, G, Ng) :- grid_val_xy(G, P, cell(_,A)), grid_set_xy(G, P, cell('?',A), Ng).   % Do open operation, opening a bomb do_op(open, P, G, Ng) :- grid_val_xy(G, P, cell(_,'?')), grid_set_xy(G, P, cell('*','?'), Ng).   % Do open operation, not a bomb do_op(open, P, G, Ng) :- grid_val_xy(G, P, cell(_,A)), dif(A, '?'), grid_set_xy(G, P, cell(A,A), Ng1), expose_grid(P, Ng1, Ng).   % expose the grid by checking all the adjacent cells and operating % appropriately expose_grid(p(X,Y), grid(W,H,Cells), Ng2) :- findall(p(Ax,Ay), ( adj(p(X,Y), dim(W,H), p(Ax,Ay)), indomain(Ax), indomain(Ay) ), Coords), expose_grid_(Coords, grid(W,H,Cells), Ng2).   expose_grid_([], G, G).   expose_grid_([H|T], G, Ng) :- % this cell has already been exposed, continue grid_val_xy(G, H, cell(A,B)), member(A, [B,'?']), expose_grid_(T, G, Ng).   expose_grid_([H|T], G, Ng) :- % ignore bombs grid_val_xy(G, H, cell(_,'?')), expose_grid_(T, G, Ng).   expose_grid_([H|T], G, Ng) :- % is an integer, expose and continue grid_val_xy(G, H, cell(_,N)), integer(N), N #> 0, grid_set_xy(G, H, cell(N,N), Ng1), expose_grid_(T, Ng1, Ng).   expose_grid_([H|T], G, Ng) :- % is a space, recurse grid_val_xy(G, H, cell('.',0)), grid_set_xy(G, H, cell(0,0), Ng1), expose_grid(H, Ng1, Ng2), expose_grid_(T, Ng2, Ng).
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Sidef
Sidef
func metronome (beats_per_minute = 72, beats_per_bar = 4) {   var counter = 0 var duration = 60/beats_per_minute var base_time = Time.micro+duration   STDOUT.autoflush(true)   for next_time in (base_time..Inf `by` duration) { if (counter++ %% beats_per_bar) { print "\nTICK" } else { print " tick" } Sys.sleep(next_time - Time.micro) } }   say metronome(ARGV.map{ Num(_) }...)
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Tcl
Tcl
package require Tcl 8.5   lassign $argv bpm bpb if {$argc < 2} {set bpb 4} if {$argc < 1} {set bpm 60}   fconfigure stdout -buffering none set intervalMS [expr {round(60000.0 / $bpm)}] set ctr 0   proc beat {} { global intervalMS ctr bpb after $intervalMS beat ;# Reschedule first, to encourage minimal drift if {[incr ctr] == 1} { puts -nonewline "\r\a[string repeat { } [expr {$bpb+4}]]\rTICK" } else { puts -nonewline "\rtick[string repeat . [expr {$ctr-1}]]" } if {$ctr >= $bpb} { set ctr 0 } }   # Run the metronome until the user uses Ctrl+C... beat vwait forever
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#Wren
Wren
import "scheduler" for Scheduler import "timer" for Timer import "/queue" for Queue   class CountingSemaphore { construct new(numRes) { _count = numRes _queue = Queue.new() }   count { _count }   acquire(task) { if (_count > 0) { _count = _count - 1 return true } _queue.push(task) return false }   release() { if (!_queue.isEmpty) { var task = _queue.pop() task.transfer() } else { _count = _count + 1 } } }   var numRes = 3 var numTasks = 6 var tasks = List.filled(6, null) var cs = CountingSemaphore.new(numRes) var main = Fiber.current   var duty = Fn.new { |n| System.print("Task %(n) started when count = %(cs.count).") var acquired = cs.acquire(Fiber.current) if (!acquired) { System.print("Task %(n) waiting for semaphore.") Fiber.yield() // return to calling fiber in the meantime } System.print("Task %(n) has acquired the semaphore.") Scheduler.add { // whilst this fiber is sleeping, start the next task if there is one var next = n + 1 if (next <= numTasks) { tasks[next-1].call(next) } } Timer.sleep(2000) System.print("Task %(n) has released the semaphore.") cs.release() if (n == numTasks) main.transfer() // on completion of last task, return to main fiber }   // create fibers for tasks for (i in 0..5) tasks[i] = Fiber.new(duty)   // call the first one tasks[0].call(1) System.print("\nAll %(numTasks) tasks completed!")
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Tcl
Tcl
puts " x\u2502 1 2 3 4 5 6 7 8 9 10 11 12" puts \u0020\u2500\u2500\u253c[string repeat \u2500 48] for {set i 1} {$i <= 12} {incr i} { puts -nonewline [format "%3d" $i]\u2502[string repeat " " [expr {$i*4-4}]] for {set j 1} {$j <= 12} {incr j} { if {$j >= $i} { puts -nonewline [format "%4d" [expr {$i*$j}]] } } puts "" }
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Standard_ML
Standard ML
  fun to (a, b) = List.tabulate (b-a,fn i => a+i ) ; infix 5 to ;  
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Tcl
Tcl
proc loopVar {var from lower to upper script} { if {$from ne "from" || $to ne "to"} {error "syntax error"} upvar 1 $var v if {$lower <= $upper} { for {set v $lower} {$v <= $upper} {incr v} { uplevel 1 $script } } else { # $upper and $lower really the other way round here for {set v $lower} {$v >= $upper} {incr v -1} { uplevel 1 $script } } }
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#Forth
Forth
  \ modular multiplication and exponentiation \ : 3rd s" 2 pick" evaluate ; immediate   : mod* ( a b m -- a*b {mod m} ) >r um* r> ud/mod 2drop ;   : mod^ ( x n m -- x^n {mod m} ) >r 1 swap begin ?dup while dup 1 and 1 = if swap 3rd r@ mod* swap 1- then dup 0> if rot dup r@ mod* -rot 2/ then repeat nip rdrop ;   \ small divisor check: true => possibly prime; false => definitely not prime. \ 31 constant π-128 create maybe-prime? 2 c, 3 c, 5 c, 7 c, 11 c, 13 c, 17 c, 19 c, 23 c, 29 c, 31 c, 37 c, 41 c, 43 c, 47 c, 53 c, 59 c, 61 c, 67 c, 71 c, 73 c, 79 c, 83 c, 89 c, 97 c, 101 c, 103 c, 107 c, 109 c, 113 c, 127 c, does> true -rot π-128 bounds do i c@ dup * over > if leave then dup i c@ mod 0= if 2drop false unloop exit then loop drop ;   \ actual Miller-Rabin test \ : factor-2s ( n -- s d ) 0 swap begin dup 1 and 0= while swap 1+ swap 2/ repeat ;   : fermat-square-test ( n m s -- ? ) \ perform n = n^2 (mod m), s-1 times 1- 0 ?do 2dup - -1 = if leave then >r dup r@ mod* r> loop - -1 = ;   : strong-fermat-pseudoprime? ( n a -- ? ) over >r \ keep the modulus on the return stack >r 1- factor-2s r> \ -- s d a swap r@ mod^ \ s d a -- s, a^d (mod n) dup 1 = \ a^d == 1 (mod n) => Fermat pseudoprime if 2drop rdrop true else r> rot fermat-square-test then ;   4.759.123.141 drop constant mr-det-3 \ Deterministic threshold; 3 bases   create small-prime-bases 2 , 7 , 61 , \ deterministic up to mr-det-3 create large-prime-bases 2 , 325 , 9375 , 28178 , 450775 , 9780504 , 1795265022 , \ known to be deterministic for 64 bit integers.   : miler-rabin-bases ( n -- addr n ) mr-det-3 < if small-prime-bases 3 else large-prime-bases 7 then ;   : miller-rabin-primality-test ( n -- f ) dup miler-rabin-bases cells bounds do dup i @ strong-fermat-pseudoprime? invert if drop false unloop exit then cell +loop drop true ;   : prime? ( n -- f ) dup 2 < if drop false else dup maybe-prime? if dup [ 127 dup * 1+ ] literal < if drop true else miller-rabin-primality-test then else drop false then then ;  
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#Draco
Draco
proc nonrec mertens([*] short m) void: word n,k; m[1] := 1; for n from 2 upto dim(m,1)-1 do m[n] := 1; for k from 2 upto n do m[n] := m[n] - m[n/k] od od corp   proc nonrec main() void: [1001] short m; word x, y, eqz, crossz;   mertens(m); writeln("The first 99 Mertens numbers are:"); for y from 0 by 10 upto 90 do for x from 0 upto 9 do if x+y=0 then write(" ") else write(m[x+y]:3) fi od; writeln() od;   eqz := 0; crossz := 0; for x from 2 upto dim(m,1)-1 do if m[x]=0 then eqz := eqz + 1; if m[x-1]~=0 then crossz := crossz + 1 fi fi od; writeln("M(N) is zero ",eqz," times."); writeln("M(N) crosses zero ",crossz," times.") corp
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#Dyalect
Dyalect
func mertensNumbers(max) { let mertens = Array.Empty(max + 1, 1) for n in 2..max { for k in 2..n { mertens[n] -= mertens[n / k] } } mertens }   let max = 1000 let mertens = mertensNumbers(max)   let count = 200 let columns = 20 print("First \(count - 1) Mertens numbers:")   for i in 0..<count { if i % columns > 0 { print(" ", terminator: "") } print(i == 0 ? " " : mertens[i].ToString().PadLeft(2, ' ') + " ", terminator: "") if (i + 1) % columns == 0 { print() } }   var (zero, cross, previous) = (0, 0, 0) for i in 1..max { let m = mertens[i] if m == 0 { zero += 1 if previous != 0 { cross += 1 } } previous = m }   print("M(n) is zero \(zero) times for 1 <= n <= \(max).") print("M(n) crosses zero \(cross) times for 1 <= n <= \(max).")
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.
#C.2B.2B
C++
#include <iostream> #include <string> #include <vector>   void print_menu(const std::vector<std::string>& terms) { for (size_t i = 0; i < terms.size(); i++) { std::cout << i + 1 << ") " << terms[i] << '\n'; } }   int parse_entry(const std::string& entry, int max_number) { int number = std::stoi(entry); if (number < 1 || number > max_number) { throw std::invalid_argument(""); }   return number; }   std::string data_entry(const std::string& prompt, const std::vector<std::string>& terms) { if (terms.empty()) { return ""; }   int choice; while (true) { print_menu(terms); std::cout << prompt;   std::string entry; std::cin >> entry;   try { choice = parse_entry(entry, terms.size()); return terms[choice - 1]; } catch (std::invalid_argument&) { // std::cout << "Not a valid menu entry!" << std::endl; } } }   int main() { std::vector<std::string> terms = {"fee fie", "huff and puff", "mirror mirror", "tick tock"}; std::cout << "You chose: " << data_entry("> ", terms) << std::endl; }  
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls. In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution. Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task. The following are acceptable: An original implementation from the specification, reference implementation, or pseudo-code A translation of a correct implementation from another language A library routine in the same language; however, the source must be included here. The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure. RFC 1321 hash code <== string 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890" In addition, intermediate outputs to aid in developing an implementation can be found here. The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
#C.23
C#
  /// Represent digest with ABCD sealed public class Digest { public uint A; public uint B; public uint C; public uint D;   public Digest() { A=(uint)MD5InitializerConstant.A; B=(uint)MD5InitializerConstant.B; C=(uint)MD5InitializerConstant.C; D=(uint)MD5InitializerConstant.D; }   public override string ToString() { string st ; st= MD5Helper.ReverseByte(A).ToString("X8")+ MD5Helper.ReverseByte(B).ToString("X8")+ MD5Helper.ReverseByte(C).ToString("X8")+ MD5Helper.ReverseByte(D).ToString("X8"); return st;   } }   public class MD5 { /***********************VARIABLES************************************/     /***********************Statics**************************************/ /// <summary> /// lookup table 4294967296*sin(i) /// </summary> protected readonly static uint [] T =new uint[64] { 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391};   /*****instance variables**************/ /// <summary> /// X used to proces data in /// 512 bits chunks as 16 32 bit word /// </summary> protected uint [] X = new uint [16];   /// <summary> /// the finger print obtained. /// </summary> protected Digest dgFingerPrint;   /// <summary> /// the input bytes /// </summary> protected byte [] m_byteInput;       /**********************EVENTS AND DELEGATES*******************************************/   public delegate void ValueChanging (object sender,MD5ChangingEventArgs Changing); public delegate void ValueChanged (object sender,MD5ChangedEventArgs Changed);     public event ValueChanging OnValueChanging; public event ValueChanged OnValueChanged;       /********************************************************************/ /***********************PROPERTIES ***********************/ /// <summary> ///gets or sets as string /// </summary> public string Value { get { string st ; char [] tempCharArray= new Char[m_byteInput.Length];   for(int i =0; i<m_byteInput.Length;i++) tempCharArray[i]=(char)m_byteInput[i];   st= new String(tempCharArray); return st; } set { /// raise the event to notify the changing if (this.OnValueChanging !=null) this.OnValueChanging(this,new MD5ChangingEventArgs(value));     m_byteInput=new byte[value.Length]; for (int i =0; i<value.Length;i++) m_byteInput[i]=(byte)value[i]; dgFingerPrint=CalculateMD5Value();   /// raise the event to notify the change if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString()));   } }   /// <summary> /// get/sets as byte array /// </summary> public byte [] ValueAsByte { get { byte [] bt = new byte[m_byteInput.Length]; for (int i =0; i<m_byteInput.Length;i++) bt[i]=m_byteInput[i]; return bt; } set { /// raise the event to notify the changing if (this.OnValueChanging !=null) this.OnValueChanging(this,new MD5ChangingEventArgs(value));   m_byteInput=new byte[value.Length]; for (int i =0; i<value.Length;i++) m_byteInput[i]=value[i]; dgFingerPrint=CalculateMD5Value();     /// notify the changed value if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString())); } }   //gets the signature/figner print as string public string FingerPrint { get { return dgFingerPrint.ToString(); } }     /*************************************************************************/ /// <summary> /// Constructor /// </summary> public MD5() { Value=""; }     /******************************************************************************/ /*********************METHODS**************************/   /// <summary> /// calculat md5 signature of the string in Input /// </summary> /// <returns> Digest: the finger print of msg</returns> protected Digest CalculateMD5Value() { /***********vairable declaration**************/ byte [] bMsg; //buffer to hold bits uint N; //N is the size of msg as word (32 bit) Digest dg =new Digest(); // the value to be returned   // create a buffer with bits padded and length is alos padded bMsg=CreatePaddedBuffer();   N=(uint)(bMsg.Length*8)/32; //no of 32 bit blocks   for (uint i=0; i<N/16;i++) { CopyBlock(bMsg,i); PerformTransformation(ref dg.A,ref dg.B,ref dg.C,ref dg.D); } return dg; }   /******************************************************** * TRANSFORMATIONS : FF , GG , HH , II acc to RFC 1321 * where each Each letter represnets the aux function used *********************************************************/       /// <summary> /// perform transformatio using f(((b&c) | (~(b)&d)) /// </summary> protected void TransF(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + ((b&c) | (~(b)&d)) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using g((b&d) | (c & ~d) ) /// </summary> protected void TransG(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + ((b&d) | (c & ~d) ) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using h(b^c^d) /// </summary> protected void TransH(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + (b^c^d) + X[k] + T[i-1]), s); }   /// <summary> /// perform transformatio using i (c^(b|~d)) /// </summary> protected void TransI(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i ) { a = b + MD5Helper.RotateLeft((a + (c^(b|~d))+ X[k] + T[i-1]), s); }       /// <summary> /// Perform All the transformation on the data /// </summary> /// <param name="A">A</param> /// <param name="B">B </param> /// <param name="C">C</param> /// <param name="D">D</param> protected void PerformTransformation(ref uint A,ref uint B,ref uint C, ref uint D) { //// saving ABCD to be used in end of loop   uint AA,BB,CC,DD;   AA=A; BB=B; CC=C; DD=D;   /* Round 1 * [ABCD 0 7 1] [DABC 1 12 2] [CDAB 2 17 3] [BCDA 3 22 4] * [ABCD 4 7 5] [DABC 5 12 6] [CDAB 6 17 7] [BCDA 7 22 8] * [ABCD 8 7 9] [DABC 9 12 10] [CDAB 10 17 11] [BCDA 11 22 12] * [ABCD 12 7 13] [DABC 13 12 14] [CDAB 14 17 15] [BCDA 15 22 16] * * */ TransF(ref A,B,C,D,0,7,1);TransF(ref D,A,B,C,1,12,2);TransF(ref C,D,A,B,2,17,3);TransF(ref B,C,D,A,3,22,4); TransF(ref A,B,C,D,4,7,5);TransF(ref D,A,B,C,5,12,6);TransF(ref C,D,A,B,6,17,7);TransF(ref B,C,D,A,7,22,8); TransF(ref A,B,C,D,8,7,9);TransF(ref D,A,B,C,9,12,10);TransF(ref C,D,A,B,10,17,11);TransF(ref B,C,D,A,11,22,12); TransF(ref A,B,C,D,12,7,13);TransF(ref D,A,B,C,13,12,14);TransF(ref C,D,A,B,14,17,15);TransF(ref B,C,D,A,15,22,16); /** rOUND 2 **[ABCD 1 5 17] [DABC 6 9 18] [CDAB 11 14 19] [BCDA 0 20 20] *[ABCD 5 5 21] [DABC 10 9 22] [CDAB 15 14 23] [BCDA 4 20 24] *[ABCD 9 5 25] [DABC 14 9 26] [CDAB 3 14 27] [BCDA 8 20 28] *[ABCD 13 5 29] [DABC 2 9 30] [CDAB 7 14 31] [BCDA 12 20 32] */ TransG(ref A,B,C,D,1,5,17);TransG(ref D,A,B,C,6,9,18);TransG(ref C,D,A,B,11,14,19);TransG(ref B,C,D,A,0,20,20); TransG(ref A,B,C,D,5,5,21);TransG(ref D,A,B,C,10,9,22);TransG(ref C,D,A,B,15,14,23);TransG(ref B,C,D,A,4,20,24); TransG(ref A,B,C,D,9,5,25);TransG(ref D,A,B,C,14,9,26);TransG(ref C,D,A,B,3,14,27);TransG(ref B,C,D,A,8,20,28); TransG(ref A,B,C,D,13,5,29);TransG(ref D,A,B,C,2,9,30);TransG(ref C,D,A,B,7,14,31);TransG(ref B,C,D,A,12,20,32); /* rOUND 3 * [ABCD 5 4 33] [DABC 8 11 34] [CDAB 11 16 35] [BCDA 14 23 36] * [ABCD 1 4 37] [DABC 4 11 38] [CDAB 7 16 39] [BCDA 10 23 40] * [ABCD 13 4 41] [DABC 0 11 42] [CDAB 3 16 43] [BCDA 6 23 44] * [ABCD 9 4 45] [DABC 12 11 46] [CDAB 15 16 47] [BCDA 2 23 48] * */ TransH(ref A,B,C,D,5,4,33);TransH(ref D,A,B,C,8,11,34);TransH(ref C,D,A,B,11,16,35);TransH(ref B,C,D,A,14,23,36); TransH(ref A,B,C,D,1,4,37);TransH(ref D,A,B,C,4,11,38);TransH(ref C,D,A,B,7,16,39);TransH(ref B,C,D,A,10,23,40); TransH(ref A,B,C,D,13,4,41);TransH(ref D,A,B,C,0,11,42);TransH(ref C,D,A,B,3,16,43);TransH(ref B,C,D,A,6,23,44); TransH(ref A,B,C,D,9,4,45);TransH(ref D,A,B,C,12,11,46);TransH(ref C,D,A,B,15,16,47);TransH(ref B,C,D,A,2,23,48); /*ORUNF 4 *[ABCD 0 6 49] [DABC 7 10 50] [CDAB 14 15 51] [BCDA 5 21 52] *[ABCD 12 6 53] [DABC 3 10 54] [CDAB 10 15 55] [BCDA 1 21 56] *[ABCD 8 6 57] [DABC 15 10 58] [CDAB 6 15 59] [BCDA 13 21 60] *[ABCD 4 6 61] [DABC 11 10 62] [CDAB 2 15 63] [BCDA 9 21 64] * */ TransI(ref A,B,C,D,0,6,49);TransI(ref D,A,B,C,7,10,50);TransI(ref C,D,A,B,14,15,51);TransI(ref B,C,D,A,5,21,52); TransI(ref A,B,C,D,12,6,53);TransI(ref D,A,B,C,3,10,54);TransI(ref C,D,A,B,10,15,55);TransI(ref B,C,D,A,1,21,56); TransI(ref A,B,C,D,8,6,57);TransI(ref D,A,B,C,15,10,58);TransI(ref C,D,A,B,6,15,59);TransI(ref B,C,D,A,13,21,60); TransI(ref A,B,C,D,4,6,61);TransI(ref D,A,B,C,11,10,62);TransI(ref C,D,A,B,2,15,63);TransI(ref B,C,D,A,9,21,64);     A=A+AA; B=B+BB; C=C+CC; D=D+DD;     }     /// <summary> /// Create Padded buffer for processing , buffer is padded with 0 along /// with the size in the end /// </summary> /// <returns>the padded buffer as byte array</returns> protected byte[] CreatePaddedBuffer() { uint pad; //no of padding bits for 448 mod 512 byte [] bMsg; //buffer to hold bits ulong sizeMsg; //64 bit size pad uint sizeMsgBuff; //buffer size in multiple of bytes int temp=(448-((m_byteInput.Length*8)%512)); //temporary     pad = (uint )((temp+512)%512); //getting no of bits to be pad if (pad==0) ///pad is in bits pad=512; //at least 1 or max 512 can be added   sizeMsgBuff= (uint) ((m_byteInput.Length)+ (pad/8)+8); sizeMsg=(ulong)m_byteInput.Length*8; bMsg=new byte[sizeMsgBuff]; ///no need to pad with 0 coz new bytes // are already initialize to 0 :)         ////copying string to buffer for (int i =0; i<m_byteInput.Length;i++) bMsg[i]=m_byteInput[i];   bMsg[m_byteInput.Length]|=0x80; ///making first bit of padding 1,   //wrting the size value for (int i =8; i >0;i--) bMsg[sizeMsgBuff-i]=(byte) (sizeMsg>>((8-i)*8) & 0x00000000000000ff);   return bMsg; }     /// <summary> /// Copies a 512 bit block into X as 16 32 bit words /// </summary> /// <param name="bMsg"> source buffer</param> /// <param name="block">no of block to copy starting from 0</param> protected void CopyBlock(byte[] bMsg,uint block) {   block=block<<6; for (uint j=0; j<61;j+=4) { X[j>>2]=(((uint) bMsg[block+(j+3)]) <<24 ) | (((uint) bMsg[block+(j+2)]) <<16 ) | (((uint) bMsg[block+(j+1)]) <<8 ) | (((uint) bMsg[block+(j)]) ) ;   } } }    
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Haskell
Haskell
import Foreign   bytealloc :: IO () bytealloc = do a0 <- mallocBytes 100 -- Allocate 100 bytes free a0 -- Free them again allocaBytes 100 $ \a -> -- Allocate 100 bytes; automatically -- freed when closure finishes poke (a::Ptr Word32) 0
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Icon_and_Unicon
Icon and Unicon
  t := table() # The table's memory is allocated #... do things with t t := &null # The table's memory can be reclaimed  
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either load the data from the   .csv   files or create the required data structures hard-coded. patients.csv   file contents: PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz visits.csv   file contents: PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3 Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand. Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset. Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date. | PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG | | 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 | | 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 | | 3003 | Kemeny | 2020-11-12 | | | | 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 | | 5005 | Kurtz | | | | Note This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc. Related tasks CSV data manipulation CSV to HTML translation Read entire file Read a file line by line
#Prolog
Prolog
patient(1001,'Hopper'). patient(4004,'Wirth'). patient(3003,'Kemeny'). patient(2002,'Gosling'). patient(5005,'Kurtz').   visit(2002,'2020-09-10',6.8). visit(1001,'2020-09-17',5.5). visit(4004,'2020-09-24',8.4). visit(2002,'2020-10-08',nan). visit(1001,'',6.6). visit(3003,'2020-11-12',nan). visit(4004,'2020-11-05',7.0). visit(1001,'2020-11-19',5.3).   summaryDates(Id, Lastname, LastDate) :- aggregate(max(Ts), Score^Date^(visit(Id, Date, Score), Date \= '', parse_time(Date, iso_8601, Ts)), MaxTs), format_time(atom(LastDate), '%Y-%m-%d', MaxTs), patient(Id,Lastname).   summaryScores(Id, Lastname, Sum, Mean) :- aggregate(r(sum(Score),count), Date^(visit(Id, Date, Score), Score \= nan), r(Sum,Count)), patient(Id,Lastname), Mean is Sum/Count.   test :- summaryDates(Id, Lastname, LastDate), writeln(summaryDates(Id, Lastname, LastDate)), fail.   test :- summaryScores(Id, Lastname, ScoreSum, ScoreMean), writeln(summaryScores(Id, Lastname, ScoreSum, ScoreMean)), fail.
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure
Memory layout of a data structure
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
#Z80_Assembly
Z80 Assembly
softRS232_LO equ &C000 ;%87654321 (each bit represents the state of a numbered pin) softRS232_HI equ &C001 ;%-------9   ld hl,softRS232_LO ;memory location of soft RS232 port ld c,&00 ;&00 = the port that the RS232 is connected to. ;This is just an example, the actual port number depends on where the hardware is connected.   outi ;send the value contained in softRS232_LO thru port &00 outi ;send the value contained in softRS232_HI thru port &00
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.
#Common_Lisp
Common Lisp
  (defun mid3 (n) (let ((a (abs n)) (hmd)) ; how many digits (labels ((give (fmt &optional x y) (return-from mid3 (format nil fmt x y))) (need (x) (give "Need ~a digits, not ~d." x hmd)) (nbr (n) (give "~3,'0d" n))) (when (zerop n) (give "Zero is 1 digit")) (setq hmd (truncate (1+ (log a 10)))) (cond ((< hmd 3) (need "3+")) ((= hmd 3) (nbr a)) ((evenp hmd) (need "odd number of")) (t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000)))))))  
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m. The total number of mines to be found is shown at the beginning of the game. Each mine occupies a single grid point, and its position is initially unknown to the player The grid is shown as a rectangle of characters between moves. You are initially shown all grids as obscured, by a single dot '.' You may mark what you think is the position of a mine which will show as a '?' You can mark what you think is free space by entering its coordinates. If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. Points marked as a mine show as a '?'. Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines. Of course you lose if you try to clear space that has a hidden mine. You win when you have correctly identified all mines. The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted. You may also omit all GUI parts of the task and work using text input and output. Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described. C.F: wp:Minesweeper (computer game)
#PureBasic
PureBasic
Structure cell isMine.i display.c ;character to displays for cell, one of these {'.', '?', ' ', #) EndStructure   Global Dim grid.cell(0,0) Global mineCount, minesMarked, isGameOver   Procedure makeGrid(n, m) Protected rm, x, y Dim grid.cell(n - 1, m - 1) mineCount = n * m * (Random(4) + 2) / 10 If mineCount < 0: mineCount = 1: EndIf   For x = 0 To n - 1 For y = 0 To m - 1 grid(x, y)\display = '.' Next Next   rm = mineCount While rm x = Random(n - 1) y = Random(m - 1) If Not grid(x, y)\isMine rm - 1: grid(x, y)\isMine = #True EndIf Wend minesMarked = 0 isGameOver = #False EndProcedure   Procedure displayGrid(isEndOfGame = #False) #lMargin = 4 Protected x, y, display.s If Not isEndOfGame PrintN("Grid has " + Str(mineCount) + " mines, " + Str(minesMarked) + " mines marked.") EndIf PrintN(Space(#lMargin + 1) + ReplaceString(Space(ArraySize(grid(), 1) + 1), " ", "-")) For y = 0 To ArraySize(grid(), 2) Print(RSet(Str(y + 1), #lMargin, " ") + ":") For x = 0 To ArraySize(grid(), 1) Print(Chr(grid(x,y)\display)) Next PrintN("") Next EndProcedure   Procedure endGame(msg.s) Protected ans.s isGameOver = #True PrintN(msg): Print("Another game (y/n)?"): ans = Input() If LCase(Left(Trim(ans),1)) = "y" makeGrid(6, 4) EndIf EndProcedure   Procedure resign() Protected x, y, found For y = 0 To ArraySize(grid(), 2) For x = 0 To ArraySize(grid(), 1) With grid(x,y) If \isMine If \display = '?' \display = 'Y' found + 1 ElseIf \display <> 'x' \display = 'N' EndIf EndIf EndWith Next Next displayGrid(#True) endGame("You found " + Str(found) + " out of " + Str(mineCount) + " mines.") EndProcedure   Procedure usage() PrintN("h or ? - this help,") PrintN("c x y - clear cell (x,y),") PrintN("m x y - marks (toggles) cell (x,y),") PrintN("n - start a new game,") PrintN("q - quit/resign the game,") PrintN("where x is the (horizontal) column number and y is the (vertical) row number." + #CRLF$) EndProcedure   Procedure markCell(x, y) If grid(x, y)\display = '?' minesMarked - 1: grid(x, y)\display = '.' ElseIf grid(x, y)\display = '.' minesMarked + 1: grid(x, y)\display = '?' EndIf EndProcedure   Procedure countAdjMines(x, y) Protected count, i, j For j = y - 1 To y + 1 If j >= 0 And j <= ArraySize(grid(), 2) For i = x - 1 To x + 1 If i >= 0 And i <= ArraySize(grid(), 1) If grid(i, j)\isMine count + 1 EndIf EndIf Next EndIf Next   ProcedureReturn count EndProcedure   Procedure clearCell(x, y) Protected count If x >= 0 And x <= ArraySize(grid(), 1) And y >= 0 And y <= ArraySize(grid(), 2) If grid(x, y)\display = '.' If Not grid(x,y)\isMine count = countAdjMines(x, y) If count grid(x, y)\display = Asc(Str(count)) Else grid(x, y)\display = ' ' clearCell(x + 1, y) clearCell(x + 1, y + 1) clearCell(x , y + 1) clearCell(x - 1, y + 1) clearCell(x - 1, y) clearCell(x - 1, y - 1) clearCell(x , y - 1) clearCell(x + 1, y - 1) EndIf Else grid(x, y)\display = 'x' PrintN("Kaboom! You lost!") resign() EndIf EndIf EndIf EndProcedure   Procedure testforwin() Protected x, y, isCleared If minesMarked = mineCount isCleared = #True For x = 0 To ArraySize(grid(), 1) For y = 0 To ArraySize(grid(), 2) If grid(x, y)\display = '.': isCleared = #False: EndIf Next Next EndIf If isCleared: endGame("You won!"): EndIf EndProcedure   If OpenConsole() Define action.s usage() makeGrid(6, 4): displayGrid() Repeat PrintN(""): Print(">"): action = Input() Select Asc(LCase(Left(action, 1))) Case 'h', '?' usage() Case 'n' makeGrid(6, 4): displayGrid() Case 'c' clearCell(Val(StringField(action, 2, " ")) - 1, Val(StringField(action, 3, " ")) - 1) If Not isGameOver: displayGrid(): Else: testforwin(): EndIf Case 'm' markCell(Val(StringField(action, 2, " ")) - 1, Val(StringField(action, 3, " ")) - 1) displayGrid() testforwin() Case 'q' resign() EndSelect Until isGameOver   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
#Wren
Wren
import "timer" for Timer import "io" for Stdout   var metronome = Fn.new { |bpm, bpb, maxBeats| var delay = (60000/bpm).floor var beats = 0 while (true) { Timer.sleep(delay) System.write((beats % bpb == 0) ? "\n\aTICK " : "\atick ") Stdout.flush() beats = beats + 1 if (beats == maxBeats) break } System.print() }   metronome.call(120, 4, 20) // limit to 20 beats
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
#zkl
zkl
fcn job(name,sem){ name.println(" wait"); sem.acquire(); name.println(" go"); Atomic.sleep(2); sem.release(); name.println(" done") } // start 3 threads using the same semphore s:=Thread.Semaphore(1); job.launch("1",s); job.launch("2",s); job.launch("3",s);
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#True_BASIC
True BASIC
PRINT " X| 1 2 3 4 5 6 7 8 9 10 11 12" PRINT "---+------------------------------------------------"   FOR i = 1 TO 12 LET nums$ = (" " & STR$(i))[LEN(" " & STR$(i))-3+1:maxnum] & "|" FOR j = 1 TO 12 IF i <= j THEN IF j >= 1 THEN LET nums$ = nums$ & (" ")[1:(4-LEN(STR$(i*j)))] LET nums$ = nums$ & STR$(i*j) ELSE LET nums$ = nums$ & " " END IF NEXT j PRINT nums$ NEXT i PRINT END
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#TXR
TXR
(defmacro whil ((condition : result) . body) (let ((cblk (gensym "cnt-blk-")) (bblk (gensym "brk-blk-"))) ^(macrolet ((break (value) ^(return-from ,',bblk ,value))) (symacrolet ((break (return-from ,bblk)) (continue (return-from ,cblk))) (block ,bblk (for () (,condition ,result) () (block ,cblk ,*body)))))))   (let ((i 0)) (whil ((< i 100)) (if (< (inc i) 20) continue) (if (> i 30) break) (prinl i)))   (prinl (sys:expand '(whil ((< i 100)) (if (< (inc i) 20) continue) (if (> i 30) break) (prinl i))))
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
#Wren
Wren
import "meta" for Meta   var genericClass = Fn.new { |cname, fname| var s1 = "class %(cname) {\n" var s2 = "construct new(%(fname)){\n_%(fname) = %(fname)\n}\n" var s3 = "%(fname) { _%(fname) }\n" var s4 = "}\nreturn %(cname)\n" return Meta.compile(s1 + s2 + s3 + s4).call() // returns the Class object }   var CFoo = genericClass.call("Foo", "bar") var foo = CFoo.new(10) System.print([foo.bar, foo.type])
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is: Input: n > 2, an odd integer to be tested for primality; k, a parameter that determines the accuracy of the test Output: composite if n is composite, otherwise probably prime write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1 LOOP: repeat k times: pick a randomly in the range [2, n − 1] x ← ad mod n if x = 1 or x = n − 1 then do next LOOP repeat s − 1 times: x ← x2 mod n if x = 1 then return composite if x = n − 1 then do next LOOP return composite return probably prime The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory. Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
#Fortran
Fortran
  module Miller_Rabin use PrimeDecompose implicit none   integer, parameter :: max_decompose = 100   private :: int_rrand, max_decompose   contains   function int_rrand(from, to) integer(huge) :: int_rrand integer(huge), intent(in) :: from, to   real :: o call random_number(o) int_rrand = floor(from + o * real(max(from,to) - min(from, to))) end function int_rrand   function miller_rabin_test(n, k) result(res) logical :: res integer(huge), intent(in) :: n integer, intent(in) :: k   integer(huge), dimension(max_decompose) :: f integer(huge) :: s, d, i, a, x, r   res = .true. f = 0   if ( (n <= 2) .and. (n > 0) ) return if ( mod(n, 2) == 0 ) then res = .false. return end if   call find_factors(n-1, f) s = count(f == 2) d = (n-1) / (2 ** s) loop: do i = 1, k a = int_rrand(2_huge, n-2) x = mod(a ** d, n)   if ( x == 1 ) cycle do r = 0, s-1 if ( x == ( n - 1 ) ) cycle loop x = mod(x*x, n) end do if ( x == (n-1) ) cycle res = .false. return end do loop res = .true. end function miller_rabin_test   end module Miller_Rabin
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n == x. Task Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x. Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.) Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000). Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.) See also Wikipedia: Mertens function Wikipedia: Möbius function OEIS: A002321 - Mertens's function OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero Numberphile - Mertens Conjecture Stackexchange: compute the mertens function This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide. Related tasks Möbius function
#F.23
F#
  // Mertens function. Nigel Galloway: January 31st., 2021 let mertens=mobius|>Seq.scan((+)) 0|>Seq.tail mertens|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "\n####") let n=mertens|>Seq.take 1000|>Seq.mapi(fun n g->(n+1,g))|>Seq.groupBy snd|>Map.ofSeq n|>Map.iter(fun n g->printf "%3d->" n; g|>Seq.iter(fun(n,_)->printf "%3d " n); printfn "\n####") printfn "%d Zeroes\n####" (Seq.length (snd n.[0])) printfn "Crosses zero %d times" (mertens|>Seq.take 1000|>Seq.pairwise|>Seq.sumBy(fun(n,g)->if n<>0 && g=0 then 1 else 0)))  
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.
#Ceylon
Ceylon
"Run the module `menu`." shared void run() { value selection = menu("fee fie", "huff And puff", "mirror mirror", "tick tock"); print(selection); }   String menu(String* strings) { if(strings.empty) { return ""; } value entries = map(zipEntries(1..strings.size, strings)); while(true) { for(index->string in entries) { print("``index``) ``string``"); } process.write("> "); value input = process.readLine(); if(exists input, exists int = parseInteger(input), exists string = entries[int]) { return string; } } }