code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
require 'bit-struct' class RS232_9 < BitStruct unsigned :cd, 1, unsigned :rd, 1, unsigned :td, 1, unsigned :dtr, 1, unsigned :sg, 1, unsigned :dsr, 1, unsigned :rts, 1, unsigned :cts, 1, unsigned :ri, 1, 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 sample1 = RS232_9.new([( % num.to_s(2)).reverse].pack()) puts sample1.inspect_detailed sample2 = RS232_9.new_with_int(num) puts sample2.inspect_detailed puts
577Memory layout of a data structure
14ruby
ig5oh
(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))
581Middle three digits
6clojure
lxbcb
<?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; $fields = &$_SESSION['minesweeper']; 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]); } $mines += check_field(@$fields[$field - MINEGRID_WIDTH]); $mines += check_field(@$fields[$field + MINEGRID_WIDTH]); 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(); if (!isset($_SESSION['minesweeper'])) { $_SESSION['minesweeper'] = array_fill(1, MINEGRID_WIDTH * MINEGRID_HEIGHT, MINESWEEPER_NOT_EXPLORED); $number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT, 0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT); $random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines); foreach ($random_keys as $key) { $_SESSION['minesweeper'][$key] = MINESWEEPER_MINE; } $_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: 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: break; } } else { die('Tile doesn\'t exist.'); } } 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 ; ?> <table border=> <?php $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= ($x - 1) * MINEGRID_WIDTH + $y, ',event)return false?explore=', ($x - 1) * MINEGRID_WIDTH + $y, 'return flag(', ($x - 1) * MINEGRID_WIDTH + $y, ',event)return false?">Reboot?</a>'; } elseif (!empty($won)) { unset($_SESSION['minesweeper']); echo '<p>Congratulations. You won:).'; }
568Minesweeper game
12php
wcgep
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) }
560Multiplication tables
17swift
0uxs6
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 }
572Metaprogramming
16scala
9eqm5
const char *menu_select(const char *const *items, const char *prompt); int main(void) { const char *items[] = {, , , , NULL}; const char *prompt = ; printf(, 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(, i + 1, items[i]); } choice_max = i; if (prompt != NULL) printf(, prompt); else printf(); if (fgets(buf, sizeof(buf), stdin) != NULL) { choice = atoi(buf); } } while (1 > choice || choice > choice_max); return items[choice - 1]; }
582Menu
5c
lxkcy
object Rs232Pins9 extends App { val (off: Boolean, on: Boolean) = (false, true) val plug = new Rs232Pins9(carrierDetect = on, receivedData = on)
577Memory layout of a data structure
16scala
th7fb
bpm = Integer(ARGV[0]) rescue 60 msr = Integer(ARGV[1]) rescue 4 i = 0 loop do (msr-1).times do puts sleep(60.0/bpm) end puts sleep(60.0/bpm) end
573Metronome
14ruby
0u4su
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)
573Metronome
16scala
nrjic
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()+ MD5Helper.ReverseByte(B).ToString()+ MD5Helper.ReverseByte(C).ToString()+ MD5Helper.ReverseByte(D).ToString(); return st; } } public class MD5 { 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}; protected uint [] X = new uint [16]; protected Digest dgFingerPrint; protected byte [] m_byteInput; public delegate void ValueChanging (object sender,MD5ChangingEventArgs Changing); public delegate void ValueChanged (object sender,MD5ChangedEventArgs Changed); public event ValueChanging OnValueChanging; public event ValueChanged OnValueChanged; 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 { 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(); if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString())); } } 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 { 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(); if (this.OnValueChanged !=null) this.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString())); } } public string FingerPrint { get { return dgFingerPrint.ToString(); } } public MD5() { Value=; } protected Digest CalculateMD5Value() { byte [] bMsg; uint N; Digest dg =new Digest(); bMsg=CreatePaddedBuffer(); N=(uint)(bMsg.Length*8)/32; 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; } 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); } 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); } 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); } 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); } protected void PerformTransformation(ref uint A,ref uint B,ref uint C, ref uint D) { uint AA,BB,CC,DD; AA=A; BB=B; CC=C; DD=D; 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); 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); 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); 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; } protected byte[] CreatePaddedBuffer() { uint pad; byte [] bMsg; ulong sizeMsg; uint sizeMsgBuff; int temp=(448-((m_byteInput.Length*8)%512)); pad = (uint )((temp+512)%512); if (pad==0) pad=512; sizeMsgBuff= (uint) ((m_byteInput.Length)+ (pad/8)+8); sizeMsg=(ulong)m_byteInput.Length*8; bMsg=new byte[sizeMsgBuff]; for (int i =0; i<m_byteInput.Length;i++) bMsg[i]=m_byteInput[i]; bMsg[m_byteInput.Length]|=0x80; for (int i =8; i >0;i--) bMsg[sizeMsgBuff-i]=(byte) (sizeMsg>>((8-i)*8) & 0x00000000000000ff); return bMsg; } 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)]) ) ; } } }
583MD5/Implementation
5c
7dxrg
func inc(n int) { x := n + 1 println(x) }
579Memory allocation
0go
xlywf
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
578Merge and aggregate datasets
2perl
u0xvr
import Foreign bytealloc :: IO () bytealloc = do a0 <- mallocBytes 100 free a0 allocaBytes 100 $ \a -> poke (a::Ptr Word32) 0
579Memory allocation
8haskell
y1h66
null
579Memory allocation
9java
d75n9
''' Minesweeper game. There is an n by m grid that has a random number of between 20% to 60% of randomly hidden 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 neighbourhood, or as a single space ' ' if the free point is not adjacent to any true mines. * Of course you loose if you try to clear space that starts on a mine. * You win when you have correctly identified all mines. When prompted you may: Toggle where you think a mine is at position x, y: m <x> <y> Clear the grid starting at position x, y (and print the result): c <x> <y> Print the grid so far: p Resign r Resigning will first show the grid with an 'N' for unfound true mines, a 'Y' for found true mines and a '?' for where you marked clear space as a mine ''' gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are%i true mines of fixed position in the grid\n'% len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got%i and missed%i of the%i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
568Minesweeper game
3python
cwi9q
(defn menu [prompt choices] (if (empty? choices) "" (let [menutxt (apply str (interleave (iterate inc 1) (map #(str \space % \newline) choices)))] (println menutxt) (print prompt) (flush) (let [index (read-string (read-line))] (if (or (not (integer? index)) (> index (count choices)) (< index 1)) (recur prompt choices) (nth choices (dec index))))))) (println "You chose: " (menu "Which is from the three pigs: " ["fee fie" "huff and puff" "mirror mirror" "tick tock"]))
582Menu
6clojure
4oe5o
null
579Memory allocation
11kotlin
0ucsf
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = , decimal=) df_visits = pd.read_csv (r'visits.csv', sep = , decimal=) ''' import io str_patients = df_patients = pd.read_csv(io.StringIO(str_patients), sep = , decimal=) str_visits = df_visits = pd.read_csv(io.StringIO(str_visits), sep = , decimal=) ''' df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
578Merge and aggregate datasets
3python
58qux
import'dart:math'; int length(int x) { int i,y; for(i=0;;i++) { y=pow(10,i); if(x%y==x) break; } return i; } int middle(int x,int l) { int a=(x/10)-((x%10)/10); int b=a%(pow(10,l-2)); int l2=length(b); if(l2==3) { return b; } if(l2!=3) { return middle(b,l2); } return 0; } main() { int x=-100,y; if(x<0) x=-x; int l=length(x); if(l.isEven||x<100) {print('error');} if(l==3) {print('$x');} if(l.isOdd&& x>100) { y=middle(x,l); print('$y'); } }
581Middle three digits
18dart
nr2iq
null
560Multiplication tables
20typescript
cwy99
df_patient <- read.table(text = " PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz ", header = TRUE, sep = ",") df_visits <- read.table(text = " 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 ", header = TRUE, dec = ".", sep = ",", colClasses=c("character","character","numeric")) df_agg <- data.frame( cbind( PATIENT_ID = names(tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE)), last_visit = tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE), score_sum = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), sum, na.rm=TRUE), score_avg = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), mean, na.rm=TRUE) ) ) df_result <- merge(df_patient, df_agg, by = 'PATIENT_ID', all.x = TRUE) print(df_result)
578Merge and aggregate datasets
13r
lxace
package main import "log" func main() {
576Miller–Rabin primality test
0go
6pb3p
puts <<EOS Minesweeper game. There is an n by m grid that has a random number of between 20% to 60% of randomly hidden 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 neighbourhood, or as a single space ' ' if the free point is not adjacent to any true mines. * Of course you loose if you try to clear space that starts on a mine. * You win when you have correctly identified all mines. When prompted you may: Toggle where you think a mine is at position x, y: m <x> <y> Clear the grid starting at position x, y (and print the result): c <x> <y> Print the grid so far: p Quit q Resigning will first show the grid with an 'N' for unfound true mines, a 'Y' for found true mines and a '?' for where you marked clear space as a mine EOS WIDTH, HEIGHT = 6, 4 PCT = 0.15 NUM_MINES = (WIDTH * HEIGHT * PCT).round def create_mines sx, sy arr = Array.new(WIDTH) { Array.new(HEIGHT, false) } NUM_MINES.times do x, y = rand(WIDTH), rand(HEIGHT) redo if arr[x][y] or (x == sx and y == sy) arr[x][y] = true end arr end def num_marks $screen.inject(0) { |sum, row| sum + row.count() } end def show_grid revealed = false if revealed puts $mines.transpose.map { |row| row.map { |cell| cell? : }.join() } else puts puts $screen.transpose.map{ |row| row.join() } end end SURROUND = [-1,0,1].product([-1,0,1]) - [[0,0]] def surrounding x, y SURROUND.each do |dx, dy| yield(x+dx, y+dy) if (0...WIDTH).cover?(x+dx) and (0...HEIGHT).cover?(y+dy) end end def clear_space x, y return unless $screen[x][y] == count = 0 surrounding(x, y) { |px, py| count += 1 if $mines[px][py] } if count == 0 $screen[x][y] = surrounding(x, y) { |px, py| clear_space px, py } else $screen[x][y] = count.to_s end end def victory? return false if $mines.nil? return false if num_marks!= NUM_MINES mines_left = NUM_MINES WIDTH.times do |x| HEIGHT.times do |y| mines_left -= 1 if $mines[x][y] and $screen[x][y] == end end mines_left == 0 end def check_input x, y x, y = x.to_i - 1, y.to_i - 1 [x, y] if (0...WIDTH).cover?(x) and (0...HEIGHT).cover?(y) end $mines = nil $screen = Array.new(WIDTH) { Array.new(HEIGHT, ) } puts show_grid loop do print action = gets.chomp.downcase case action when , , , puts break when /^m (\d+) (\d+)$/ x, y = check_input $1, $2 next unless x if $screen[x][y] == $screen[x][y] = if victory? show_grid puts break end elsif $screen[x][y] == $screen[x][y] = end show_grid when /^c (\d+) (\d+)$/ x, y = check_input $1, $2 next unless x $mines ||= create_mines(x, y) if $mines[x][y] puts show_grid true break else clear_space x, y show_grid if victory? puts break end end when show_grid end end
568Minesweeper game
14ruby
2qdlw
module Primes where import System.Random import System.IO.Unsafe isPrime :: Integer -> Bool isPrime n = unsafePerformIO (isMillerRabinPrime 100 n) isMillerRabinPrime :: Int -> Integer -> IO Bool isMillerRabinPrime k n | even n = return (n==2) | n < 100 = return (n `elem` primesTo100) | otherwise = do ws <- witnesses k n return $ and [test n (pred n) evens (head odds) a | a <- ws] where (evens,odds) = span even (iterate (`div` 2) (pred n)) test :: Integral nat => nat -> nat -> [nat] -> nat -> nat -> Bool test n n_1 evens d a = x `elem` [1,n_1] || n_1 `elem` powers where x = powerMod n a d powers = map (powerMod n a) evens witnesses :: (Num a, Ord a, Random a) => Int -> a -> IO [a] witnesses k n | n < 9080191 = return [31,73] | n < 4759123141 = return [2,7,61] | n < 3474749660383 = return [2,3,5,7,11,13] | n < 341550071728321 = return [2,3,5,7,11,13,17] | otherwise = do g <- newStdGen return $ take k (randomRs (2,n-1) g) primesTo100 :: [Integer] primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] powerMod :: Integral nat => nat -> nat -> nat -> nat powerMod m x n = f (n - 1) x x `rem` m where f d a y = if d==0 then y else g d a y g i b y | even i = g (i `quot` 2) (b*b `rem` m) y | otherwise = f (i-1) b (b*y `rem` m)
576Miller–Rabin primality test
8haskell
jfd7g
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0
580Mertens function
0go
kzihz
extern crate rand; use std::io; use std::io::Write; fn main() { use minesweeper::{MineSweeper, GameStatus}; let mut width = 6; let mut height = 4; let mut mine_perctg = 10; let mut game = MineSweeper::new(width, height, mine_perctg); loop { let mut command = String::new(); println!( "\n\ M I N E S W E E P E R\n\ \n\ Commands: \n\ line col - reveal line,col \n\ m line col - mark line,col \n\ q - quit\n\ n - new game\n\ n width height perc - new game size and mine percentage\n" ); game.print(); print!("> "); io::stdout().flush().unwrap(); while let Ok(_) = io::stdin().read_line(&mut command) { let mut command_ok = false; { let values: Vec<&str> = command.trim().split(' ').collect(); if values.len() == 1 { if values[0] == "q" { println!("Goodbye"); return; } else if values[0] == "n" { println!("New game"); game = MineSweeper::new(width, height, mine_perctg); command_ok = true; } } else if values.len() == 2 { if let (Ok(x), Ok(y)) = ( values[0].parse::<usize>(), values[1].parse::<usize>(), ) { game.play(x - 1, y - 1); match game.game_status { GameStatus::Won => println!("You won!"), GameStatus::Lost => println!("You lost!"), _ => (), } command_ok = true; } } else if values.len() == 3 { if values[0] == "m" { if let (Ok(x), Ok(y)) = ( values[1].parse::<usize>(), values[2].parse::<usize>(), ) { game.mark(x - 1, y - 1); command_ok = true; } } } else if values.len() == 4 { if values[0] == "n" { if let (Ok(new_width), Ok(new_height), Ok(new_mines_perctg)) = ( values[1].parse::<usize>(), values[2].parse::<usize>(), values[3].parse::<usize>(), ) { width = new_width; height = new_height; mine_perctg = new_mines_perctg; game = MineSweeper::new(width, height, mine_perctg); command_ok = true; } } } } if command_ok { game.print(); } else { println!("Invalid command"); } print!("> "); io::stdout().flush().unwrap(); command.clear(); } } } pub mod minesweeper { pub struct MineSweeper { cell: [[Cell; 100]; 100], pub game_status: GameStatus, mines: usize, width: usize, height: usize, revealed_count: usize, } #[derive(Copy, Clone)] struct Cell { content: CellContent, mark: Mark, revealed: bool, } #[derive(Copy, Clone)] enum CellContent { Empty, Mine, MineNeighbour { count: u8 }, } #[derive(Copy, Clone)] enum Mark { None, Mine, } pub enum GameStatus { InGame, Won, Lost, } extern crate rand; use std::cmp::max; use std::cmp::min; use self::rand::Rng; use self::CellContent::*; use self::GameStatus::*; impl MineSweeper { pub fn new(width: usize, height: usize, percentage_of_mines: usize) -> MineSweeper { let mut game = MineSweeper { cell: [[Cell { content: Empty, mark: Mark::None, revealed: false, }; 100]; 100], game_status: InGame, mines: (width * height * percentage_of_mines) / 100, width: width, height: height, revealed_count: 0, }; game.put_mines(); game.calc_neighbours(); game } pub fn play(&mut self, x: usize, y: usize) { match self.game_status { InGame => { if!self.cell[x][y].revealed { match self.cell[x][y].content { Mine => { self.cell[x][y].revealed = true; self.revealed_count += 1; self.game_status = Lost; } Empty => { self.flood_fill_reveal(x, y); if self.revealed_count + self.mines == self.width * self.height { self.game_status = Won; } } MineNeighbour { .. } => { self.cell[x][y].revealed = true; self.revealed_count += 1; if self.revealed_count + self.mines == self.width * self.height { self.game_status = Won; } } } } } _ => println!("Game has ended"), } } pub fn mark(&mut self, x: usize, y: usize) { self.cell[x][y].mark = match self.cell[x][y].mark { Mark::None => Mark::Mine, Mark::Mine => Mark::None, } } pub fn print(&self) { print!(""); for _ in 0..self.width { print!(""); } println!(""); for y in 0..self.height { print!(""); for x in 0..self.width { self.cell[x][y].print(); } println!(""); } print!(""); for _ in 0..self.width { print!(""); } println!(""); } fn put_mines(&mut self) { let mut rng = rand::thread_rng(); for _ in 0..self.mines { while let (x, y, true) = ( rng.gen::<usize>()% self.width, rng.gen::<usize>()% self.height, true, ) { match self.cell[x][y].content { Mine => continue, _ => { self.cell[x][y].content = Mine; break; } } } } } fn calc_neighbours(&mut self) { for x in 0..self.width { for y in 0..self.height { if!self.cell[x][y].is_bomb() { let mut adjacent_bombs = 0; for i in max(x as isize - 1, 0) as usize..min(x + 2, self.width) { for j in max(y as isize - 1, 0) as usize..min(y + 2, self.height) { adjacent_bombs += if self.cell[i][j].is_bomb() { 1 } else { 0 }; } } if adjacent_bombs == 0 { self.cell[x][y].content = Empty; } else { self.cell[x][y].content = MineNeighbour { count: adjacent_bombs }; } } } } } fn flood_fill_reveal(&mut self, x: usize, y: usize) { let mut stack = Vec::<(usize, usize)>::new(); stack.push((x, y)); while let Some((i, j)) = stack.pop() { if self.cell[i][j].revealed { continue; } self.cell[i][j].revealed = true; self.revealed_count += 1; if let Empty = self.cell[i][j].content { for m in max(i as isize - 1, 0) as usize..min(i + 2, self.width) { for n in max(j as isize - 1, 0) as usize..min(j + 2, self.height) { if!self.cell[m][n].is_bomb() &&!self.cell[m][n].revealed { stack.push((m, n)); } } } } } } } impl Cell { pub fn print(&self) { print!( "{}", if self.revealed { match self.content { Empty => ' ', Mine => '*', MineNeighbour { count } => char::from(count + b'0'), } } else { match self.mark { Mark::Mine => '?', Mark::None => '.', } } ); } pub fn is_bomb(&self) -> bool { match self.content { Mine => true, _ => false, } } } }
568Minesweeper game
15rust
vsf2t
import Data.List.Split (chunksOf) import qualified Data.MemoCombinators as Memo import Math.NumberTheory.Primes (unPrime, factorise) import Text.Printf (printf) moebius :: Integer -> Int moebius = product . fmap m . factorise where m (p, e) | unPrime p == 0 = 0 | e == 1 = -1 | otherwise = 0 mertens :: Integer -> Int mertens = Memo.integral (\n -> sum $ fmap moebius [1..n]) countZeros :: [Integer] -> Int countZeros = length . filter ((==0) . mertens) crossesZero :: [Integer] -> Int crossesZero = length . go . fmap mertens where go (x:y:xs) | y == 0 && x /= 0 = y: go (y:xs) | otherwise = go (y:xs) go _ = [] main :: IO () main = do printf "The first 99 terms for M(1..99):\n\n " mapM_ (printf "%3d" . mertens) [1..9] >> printf "\n" mapM_ (\row -> mapM_ (printf "%3d" . mertens) row >> printf "\n") $ chunksOf 10 [10..99] printf "\nM(n) is zero%d times for 1 <= n <= 1000.\n" $ countZeros [1..1000] printf "M(n) crosses zero%d times for 1 <= n <= 1000.\n" $ crossesZero [1..1000]
580Mertens function
8haskell
nrvie
-- drop tables DROP TABLE IF EXISTS tmp_patients; DROP TABLE IF EXISTS tmp_visits; -- create tables CREATE TABLE tmp_patients( PATIENT_ID INT, LASTNAME VARCHAR(20) ); CREATE TABLE tmp_visits( PATIENT_ID INT, VISIT_DATE DATE, SCORE NUMERIC(4,1) ); -- load data from csv files -- load data hard coded INSERT INTO tmp_patients(PATIENT_ID, LASTNAME) VALUES (1001, 'Hopper'), (4004, 'Wirth'), (3003, 'Kemeny'), (2002, 'Gosling'), (5005, 'Kurtz'); INSERT INTO tmp_visits(PATIENT_ID, VISIT_DATE, SCORE) VALUES (2002, '2020-09-10', 6.8), (1001, '2020-09-17', 5.5), (4004, '2020-09-24', 8.4), (2002, '2020-10-08', NULL), (1001, NULL, 6.6), (3003, '2020-11-12', NULL), (4004, '2020-11-05', 7.0), (1001, '2020-11-19', 5.3); -- join tables and group SELECT p.PATIENT_ID, p.LASTNAME, MAX(VISIT_DATE) AS LAST_VISIT, SUM(SCORE) AS SCORE_SUM, CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG FROM tmp_patients p LEFT JOIN tmp_visits v ON v.PATIENT_ID = p.PATIENT_ID GROUP BY p.PATIENT_ID, p.LASTNAME ORDER BY p.PATIENT_ID;
578Merge and aggregate datasets
19sql
p6tb1
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, } func main() { for _, tc := range testCases { fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string)) } } var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21} var table [64]uint32 func init() { for i := range table { table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1)))) } } func md5(s string) (r [16]byte) { padded := bytes.NewBuffer([]byte(s)) padded.WriteByte(0x80) for padded.Len() % 64 != 56 { padded.WriteByte(0) } messageLenBits := uint64(len(s)) * 8 binary.Write(padded, binary.LittleEndian, messageLenBits) var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 var buffer [16]uint32 for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil {
583MD5/Implementation
0go
d7lne
import java.math.BigInteger; public class MillerRabinPrimalityTest { public static void main(String[] args) { BigInteger n = new BigInteger(args[0]); int certainty = Integer.parseInt(args[1]); System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite")); } }
576Miller–Rabin primality test
9java
u0svv
public class MertensFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) { int zeroCount = 0; int zeroCrossingCount = 0; int positiveCount = 0; int negativeCount = 0; int mSum = 0; int mMin = Integer.MAX_VALUE; int mMinIndex = 0; int mMax = Integer.MIN_VALUE; int mMaxIndex = 0; int nMax = (int) Math.pow(10, exponent); for ( int n = 1 ; n <= nMax ; n++ ) { int m = mertenFunction(n); mSum += m; if ( m < mMin ) { mMin = m; mMinIndex = n; } if ( m > mMax ) { mMax = m; mMaxIndex = n; } if ( m > 0 ) { positiveCount++; } if ( m < 0 ) { negativeCount++; } if ( m == 0 ) { zeroCount++; } if ( m == 0 && mertenFunction(n - 1) != 0 ) { zeroCrossingCount++; } } System.out.printf("%nFor M(x) with x from 1 to%,d%n", nMax); System.out.printf("The maximum of M(x) is M(%,d) =%,d.%n", mMaxIndex, mMax); System.out.printf("The minimum of M(x) is M(%,d) =%,d.%n", mMinIndex, mMin); System.out.printf("The sum of M(x) is%,d.%n", mSum); System.out.printf("The count of positive M(x) is%,d, count of negative M(x) is%,d.%n", positiveCount, negativeCount); System.out.printf("M(x) has%,d zeroes in the interval.%n", zeroCount); System.out.printf("M(x) has%,d crossings in the interval.%n", zeroCrossingCount); } } private static int MU_MAX = 100_000_000; private static int[] MU = null; private static int[] MERTEN = null;
580Mertens function
9java
q2yxa
class MD5 { private static final int INIT_A = 0x67452301 private static final int INIT_B = (int)0xEFCDAB89L private static final int INIT_C = (int)0x98BADCFEL private static final int INIT_D = 0x10325476 private static final int[] SHIFT_AMTS = [ 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 ] private static final int[] TABLE_T = new int[64] static { for (int i in 0..63) TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1))) } static byte[] computeMD5(byte[] message) { int messageLenBytes = message.length int numBlocks = ((messageLenBytes + 8) >>> 6) + 1 int totalLen = numBlocks << 6 byte[] paddingBytes = new byte[totalLen - messageLenBytes] paddingBytes[0] = (byte)0x80 long messageLenBits = (long)messageLenBytes << 3 for (int i in 0..7) { paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits messageLenBits >>>= 8 } int a = INIT_A int b = INIT_B int c = INIT_C int d = INIT_D int[] buffer = new int[16] for (int i in 0..(numBlocks - 1)) { int index = i << 6 for (int j in 0..63) { buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index]: paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8) index++ } int originalA = a int originalB = b int originalC = c int originalD = d for (int j in 0..63) { int div16 = j >>> 4 int f = 0 int bufferIndex = j switch (div16) { case 0: f = (b & c) | (~b & d) break case 1: f = (b & d) | (c & ~d) bufferIndex = (bufferIndex * 5 + 1) & 0x0F break case 2: f = b ^ c ^ d bufferIndex = (bufferIndex * 3 + 5) & 0x0F break case 3: f = c ^ (b | ~d) bufferIndex = (bufferIndex * 7) & 0x0F break } int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]) a = d d = c c = b b = temp } a += originalA b += originalB c += originalC d += originalD } byte[] md5 = new byte[16] int count = 0 for (int i in 0..3) { int n = (i == 0) ? a: ((i == 1) ? b: ((i == 2) ? c: d)) for (int j in 0..3) { md5[count++] = (byte)n n >>>= 8 } } return md5 } static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder() for (int i in 0..(b.length - 1)) { sb.append(String.format("%02X", b[i] & 0xFF)) } return sb.toString() } static void main(String[] args) { String[] testStrings = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ] for (String s: testStrings) System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"") } }
583MD5/Implementation
7groovy
0u6sh
function probablyPrime(n) { if (n === 2 || n === 3) return true if (n % 2 === 0 || n < 2) return false
576Miller–Rabin primality test
10javascript
7dnrd
import Control.Monad (replicateM) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import Data.Binary.Get import Data.Binary.Put import Data.Bits import Data.Array (Array, listArray, (!)) import Data.List (foldl) import Data.Word (Word32) import Numeric (showHex) type Fun = Word32 -> Word32 -> Word32 -> Word32 funF, funG, funH, funI :: Fun funF x y z = (x .&. y) .|. (complement x .&. z) funG x y z = (x .&. z) .|. (complement z .&. y) funH x y z = x `xor` y `xor` z funI x y z = y `xor` (complement z .|. x) idxF, idxG, idxH, idxI :: Int -> Int idxF i = i idxG i = (5 * i + 1) `mod` 16 idxH i = (3 * i + 5) `mod` 16 idxI i = 7 * i `mod` 16 funA :: Array Int Fun funA = listArray (1,64) $ replicate 16 =<< [funF, funG, funH, funI] idxA :: Array Int Int idxA = listArray (1,64) $ zipWith ($) (replicate 16 =<< [idxF, idxG, idxH, idxI]) [0..63] rotA :: Array Int Int rotA = listArray (1,64) $ concat . replicate 4 =<< [[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]] sinA :: Array Int Word32 sinA = listArray (1,64) $ map (floor . (*mult) . abs . sin) [1..64] where mult = 2 ** 32 :: Double main :: IO () main = mapM_ (putStrLn . md5sum . BLC.pack) [ "" , "a" , "abc" , "message digest" , "abcdefghijklmnopqrstuvwxyz" , "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" , "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ] md5sum :: BL.ByteString -> String md5sum input = let MD5 a b c d = getMD5 initial `runGet` input in foldr hex [] . BL.unpack . runPut $ mapM_ putWord32le [a,b,c,d] where initial = MD5 0x67452301 0xEFCDAB89 0x98BADCFE 0x10325476 hex x s | x < 16 = '0': showHex x s | otherwise = showHex x s data MD5 = MD5 { a :: !Word32 , b :: !Word32 , c :: !Word32 , d :: !Word32 } getMD5 :: MD5 -> Get MD5 getMD5 md5 = do chunk <- getLazyByteString 64 let len = BL.length chunk if len == 64 then getMD5 $! md5 <+> chunk else do bytes <- bytesRead let fin = runPut . putWord64le $ fromIntegral (bytes - 64 + len) * 8 pad n = chunk `BL.append` (0x80 `BL.cons` BL.replicate (n - 1) 0x00) return $ if len >= 56 then md5 <+> pad (64 - len) <+> BL.replicate 56 0x00 `BL.append` fin else md5 <+> pad (56 - len) `BL.append` fin (<+>) :: MD5 -> BL.ByteString -> MD5 infixl 5 <+> md5@(MD5 a b c d) <+> bs = let datA = listArray (0,15) $ replicateM 16 getWord32le `runGet` bs MD5 a' b' c' d' = foldl' (md5round datA) md5 [1..64] in MD5 (a + a') (b + b') (c + c') (d + d') md5round:: Array Int Word32 -> MD5 -> Int -> MD5 md5round datA (MD5 a b c d) i = let f = funA! i w = datA! (idxA! i) a' = b + (a + f b c d + w + sinA ! i) `rotateL` rotA ! i in MD5 d a' b c
583MD5/Implementation
8haskell
581ug
atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems ... free(addr) atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re-assigned
579Memory allocation
2perl
58xu2
null
576Miller–Rabin primality test
11kotlin
9eamh
class MD5 { private static final int INIT_A = 0x67452301; private static final int INIT_B = (int)0xEFCDAB89L; private static final int INIT_C = (int)0x98BADCFEL; private static final int INIT_D = 0x10325476; private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; private static final int[] TABLE_T = new int[64]; static { for (int i = 0; i < 64; i++) TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1))); } public static byte[] computeMD5(byte[] message) { int messageLenBytes = message.length; int numBlocks = ((messageLenBytes + 8) >>> 6) + 1; int totalLen = numBlocks << 6; byte[] paddingBytes = new byte[totalLen - messageLenBytes]; paddingBytes[0] = (byte)0x80; long messageLenBits = (long)messageLenBytes << 3; for (int i = 0; i < 8; i++) { paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits; messageLenBits >>>= 8; } int a = INIT_A; int b = INIT_B; int c = INIT_C; int d = INIT_D; int[] buffer = new int[16]; for (int i = 0; i < numBlocks; i ++) { int index = i << 6; for (int j = 0; j < 64; j++, index++) buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8); int originalA = a; int originalB = b; int originalC = c; int originalD = d; for (int j = 0; j < 64; j++) { int div16 = j >>> 4; int f = 0; int bufferIndex = j; switch (div16) { case 0: f = (b & c) | (~b & d); break; case 1: f = (b & d) | (c & ~d); bufferIndex = (bufferIndex * 5 + 1) & 0x0F; break; case 2: f = b ^ c ^ d; bufferIndex = (bufferIndex * 3 + 5) & 0x0F; break; case 3: f = c ^ (b | ~d); bufferIndex = (bufferIndex * 7) & 0x0F; break; } int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]); a = d; d = c; c = b; b = temp; } a += originalA; b += originalB; c += originalC; d += originalD; } byte[] md5 = new byte[16]; int count = 0; for (int i = 0; i < 4; i++) { int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d)); for (int j = 0; j < 4; j++) { md5[count++] = (byte)n; n >>>= 8; } } return md5; } public static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { sb.append(String.format("%02X", b[i] & 0xFF)); } return sb.toString(); } public static void main(String[] args) { String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; for (String s : testStrings) System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\""); return; } }
583MD5/Implementation
9java
9e7mu
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a array('l') array('c', 'hello world') array('u', u'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.1400000000000001]) >>>
579Memory allocation
3python
4oq5k
function MRIsPrime(n, k)
576Miller–Rabin primality test
1lua
cwe92
x=numeric(10) rm(x) x=vector("list",10) x=vector("numeric",10) rm(x)
579Memory allocation
13r
2qalg
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq'; sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors } sub { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1 : -1 : 0 } sub progressive_sum { my @sum = shift @_; push @sum, $sum[-1] + $_ for @_; @sum } my($upto, $show, @mebius) = (1000, 199, ()); push @mebius, ($_) for 1..$upto; my @mertens = progressive_sum @mebius; say "Mertens sequence - First $show terms:\n" . (' 'x4 . sprintf "@{['%4d' x $show]}", @mertens[0..$show-1]) =~ s/((.){80})/$1\n/gr . sprintf("\nEquals zero%3d times between 1 and $upto", scalar grep { ! $_ } @mertens) . sprintf "\nCrosses zero%3d times between 1 and $upto", scalar grep { ! $mertens[$_-1] and $mertens[$_] } 1 .. @mertens;
580Mertens function
2perl
mahyz
null
583MD5/Implementation
11kotlin
zkuts
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } s := strconv.Itoa(i) if len(s)%2 == 0 { return "", ErrorEven } m := len(s) / 2 return s[m-1 : m+2], nil }
581Middle three digits
0go
p6nbg
package main import "fmt" func menu(choices []string, prompt string) string { if len(choices) == 0 { return "" } var c int for { fmt.Println("") for i, s := range choices { fmt.Printf("%d. %s\n", i+1, s) } fmt.Print(prompt) _, err := fmt.Scanln(&c) if err == nil && c > 0 && c <= len(choices) { break } } return choices[c-1] } func main() { pick := menu(nil, "No prompt") fmt.Printf("No choices, result =%q\n", pick) choices := []string{ "fee fie", "huff and puff", "mirror mirror", "tick tock", } pick = menu(choices, "Enter number: ") fmt.Printf("You picked%q\n", pick) }
582Menu
0go
xlzwf
class Thingamajig def initialize fail 'not yet implemented' end end t = Thingamajig.allocate
579Memory allocation
14ruby
rn0gs
null
579Memory allocation
15rust
7d8rc
null
583MD5/Implementation
1lua
3b5zo
PRINT PEEK 16388+256*16389
579Memory allocation
16scala
kznhk
def middleThree(Number number) { def text = Math.abs(number) as String assert text.size() >= 3: "'$number' must be more than 3 numeric digits" assert text.size() % 2 == 1: "'$number' must have an odd number of digits" int start = text.size() / 2 - 1 text[start..(start+2)] }
581Middle three digits
7groovy
7dsrz
module RosettaSelect where import Data.Maybe (listToMaybe) import Control.Monad (guard) select :: [String] -> IO String select [] = return "" select menu = do putStr $ showMenu menu putStr "Choose an item: " choice <- getLine maybe (select menu) return $ choose menu choice showMenu :: [String] -> String showMenu menu = unlines [show n ++ ") " ++ item | (n, item) <- zip [1..] menu] choose :: [String] -> String -> Maybe String choose menu choice = do n <- maybeRead choice guard $ n > 0 listToMaybe $ drop (n-1) menu maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . filter (null . snd) . reads
582Menu
8haskell
y1r66
mid3 :: Int -> Either String String mid3 n | m < 100 = Left "is too small" | even lng = Left "has an even number of digits" | otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s where m = abs n s = show m lng = length s main :: IO () main = do let xs = [ 123 , 12345 , 1234567 , 987654321 , 10001 , -10001 , -123 , -100 , 100 , -12345 , 1 , 2 , -1 , -10 , 2002 , -2002 , 0 ] w = maximum $ (length . show) <$> xs (putStrLn . unlines) $ (\n -> justifyRight w ' ' (show n) ++ " -> " ++ either ((>>= id) . ("(":) . (: [")"])) id (mid3 n)) <$> xs where justifyRight :: Int -> Char -> String -> String justifyRight n c s = drop (length s) (replicate n c ++ s)
581Middle three digits
8haskell
fjud1
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n return m ms = mertens(1000) print() print(, end=' ') col = 1 for n in ms[1:100]: print(.format(n), end=' ') col += 1 if col == 10: print() col = 0 zeroes = sum(x==0 for x in ms) crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:])) print(.format(zeroes)) print(.format(crosses))
580Mertens function
3python
9ekmf
use bigint try => 'GMP'; sub is_prime { my ($n, $k) = @_; return 1 if $n == 2; return 0 if $n < 2 or $n % 2 == 0; my $d = $n - 1; my $s = 0; while (!($d % 2)) { $d /= 2; $s++; } LOOP: for (1 .. $k) { my $a = 2 + int(rand($n - 2)); my $x = $a->bmodpow($d, $n); next if $x == 1 or $x == $n - 1; for (1 .. $s - 1) { $x = ($x * $x) % $n; return 0 if $x == 1; next LOOP if $x == $n - 1; } return 0; } return 1; } print join ", ", grep { is_prime $_, 10 } (1 .. 1000);
576Miller–Rabin primality test
2perl
wc9e6
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s):%s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s):%s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
581Middle three digits
9java
0umse
require 'prime' def (n) return 1 if self == 1 pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even?? 1: -1 end def M(n) (1..n).sum{|n| (n)} end ([] + (1..199).map{|n| % M(n)}).each_slice(20){|line| puts line.join() } ar = (1..1000).map{|n| M(n)} puts puts
580Mertens function
14ruby
lxpcl
public static String select(List<String> list, String prompt){ if(list.size() == 0) return ""; Scanner sc = new Scanner(System.in); String ret = null; do{ for(int i=0;i<list.size();i++){ System.out.println(i + ": "+list.get(i)); } System.out.print(prompt); int index = sc.nextInt(); if(index >= 0 && index < list.size()){ ret = list.get(index); } }while(ret == null); return ret; }
582Menu
9java
d72n9
function middleThree(x){ var n=''+Math.abs(x); var l=n.length-1; if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1)); return n.slice(l/2-1,l/2+2); } [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){ try{console.log(n,middleThree(n))}catch(e){console.error(e.message)} });
581Middle three digits
10javascript
d7vnu
<?php function is_prime($n, $k) { if ($n == 2) return true; if ($n < 2 || $n % 2 == 0) return false; $d = $n - 1; $s = 0; while ($d % 2 == 0) { $d /= 2; $s++; } for ($i = 0; $i < $k; $i++) { $a = rand(2, $n-1); $x = bcpowmod($a, $d, $n); if ($x == 1 || $x == $n-1) continue; for ($j = 1; $j < $s; $j++) { $x = bcmod(bcmul($x, $x), $n); if ($x == 1) return false; if ($x == $n-1) continue 2; } return false; } return true; } for ($i = 1; $i <= 1000; $i++) if (is_prime($i, 10)) echo ; echo ; ?>
576Miller–Rabin primality test
12php
lxwcj
import Foundation func mertensNumbers(max: Int) -> [Int] { var mertens = Array(repeating: 1, count: max + 1) for n in 2...max { for k in 2...n { mertens[n] -= mertens[n / k] } } return mertens } let max = 1000 let mertens = mertensNumbers(max: 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? " ": String(format: "%2d", mertens[i]), terminator: "") if (i + 1)% columns == 0 { print() } } var zero = 0, cross = 0, previous = 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).")
580Mertens function
17swift
cwb9t
const readline = require('readline'); async function menuSelect(question, choices) { if (choices.length === 0) return ''; const prompt = choices.reduce((promptPart, choice, i) => { return promptPart += `${i + 1}. ${choice}\n`; }, ''); let inputChoice = -1; while (inputChoice < 1 || inputChoice > choices.length) { inputChoice = await getSelection(`\n${prompt}${question}: `); } return choices[inputChoice - 1]; } function getSelection(prompt) { return new Promise((resolve) => { const lr = readline.createInterface({ input: process.stdin, output: process.stdout }); lr.question(prompt, (response) => { lr.close(); resolve(parseInt(response) || -1); }); }); } const choices = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock']; const question = 'Which is from the three pigs?'; menuSelect(question, choices).then((answer) => { console.log(`\nYou chose ${answer}`); });
582Menu
10javascript
6pg38
use strict; use warnings; use integer; use Test::More; BEGIN { plan tests => 7 } sub A() { 0x67_45_23_01 } sub B() { 0xef_cd_ab_89 } sub C() { 0x98_ba_dc_fe } sub D() { 0x10_32_54_76 } sub MAX() { 0xFFFFFFFF } sub padding { my $l = length (my $msg = shift() . chr(128)); $msg .= "\0" x (($l%64<=56?56:120)-$l%64); $l = ($l-1)*8; $msg .= pack 'VV', $l & MAX , ($l >> 16 >> 16); } sub rotate_left($$) { ($_[0] << $_[1]) | (( $_[0] >> (32 - $_[1]) ) & ((1 << $_[1]) - 1)); } sub gen_code { my $MSK = ((1 << 16) << 16) ? ' & ' . MAX : ''; my %f = ( FF => "X0=rotate_left((X3^(X1&(X2^X3)))+X0+X4+X6$MSK,X5)+X1$MSK;", GG => "X0=rotate_left((X2^(X3&(X1^X2)))+X0+X4+X6$MSK,X5)+X1$MSK;", HH => "X0=rotate_left((X1^X2^X3)+X0+X4+X6$MSK,X5)+X1$MSK;", II => "X0=rotate_left((X2^(X1|(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;", ); my %s = ( S11 => 7, S12 => 12, S13 => 17, S14 => 22, S21 => 5, S22 => 9, S23 => 14, S24 => 20, S31 => 4, S32 => 11, S33 => 16, S34 => 23, S41 => 6, S42 => 10, S43 => 15, S44 => 21 ); my $insert = "\n"; while(defined( my $data = <DATA> )) { chomp $data; next unless $data =~ /^[FGHI]/; my ($func,@x) = split /,/, $data; my $c = $f{$func}; $c =~ s/X(\d)/$x[$1]/g; $c =~ s/(S\d{2})/$s{$1}/; $c =~ s/^(.*)=rotate_left\((.*),(.*)\)\+(.*)$//; my $su = 32 - $3; my $sh = (1 << $3) - 1; $c = "$1=(((\$r=$2)<<$3)|((\$r>>$su)&$sh))+$4"; $insert .= "\t$c\n"; } close DATA; my $dump = ' sub round { my ($a,$b,$c,$d) = @_[0 .. 3]; my $r;' . $insert . ' $_[0]+$a' . $MSK . ', $_[1]+$b ' . $MSK . ', $_[2]+$c' . $MSK . ', $_[3]+$d' . $MSK . '; }'; eval $dump; } gen_code(); sub _encode_hex { unpack 'H*', $_[0] } sub md5 { my $message = padding(join'',@_); my ($a,$b,$c,$d) = (A,B,C,D); my $i; for $i (0 .. (length $message)/64-1) { my @X = unpack 'V16', substr $message,$i*64,64; ($a,$b,$c,$d) = round($a,$b,$c,$d,@X); } pack 'V4',$a,$b,$c,$d; } my $strings = { 'd41d8cd98f00b204e9800998ecf8427e' => '', '0cc175b9c0f1b6a831c399e269772661' => 'a', '900150983cd24fb0d6963f7d28e17f72' => 'abc', 'f96b697d7cb7938d525a2f31aaf161d0' => 'message digest', 'c3fcd3d76192e4007dfb496cca67e13b' => 'abcdefghijklmnopqrstuvwxyz', 'd174ab98d277d9f5a5611c2c9f419d9f' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', '57edf4a22be3c955ac49da2e2107b67a' => '12345678901234567890123456789012345678901234567890123456789012345678901234567890', }; for my $k (keys %$strings) { my $digest = _encode_hex md5($strings->{$k}); is($digest, $k, "$digest is MD5 digest $strings->{$k}"); } __DATA__ FF,$a,$b,$c,$d,$_[4],7,0xd76aa478,/* 1 */ FF,$d,$a,$b,$c,$_[5],12,0xe8c7b756,/* 2 */ FF,$c,$d,$a,$b,$_[6],17,0x242070db,/* 3 */ FF,$b,$c,$d,$a,$_[7],22,0xc1bdceee,/* 4 */ FF,$a,$b,$c,$d,$_[8],7,0xf57c0faf,/* 5 */ FF,$d,$a,$b,$c,$_[9],12,0x4787c62a,/* 6 */ FF,$c,$d,$a,$b,$_[10],17,0xa8304613,/* 7 */ FF,$b,$c,$d,$a,$_[11],22,0xfd469501,/* 8 */ FF,$a,$b,$c,$d,$_[12],7,0x698098d8,/* 9 */ FF,$d,$a,$b,$c,$_[13],12,0x8b44f7af,/* 10 */ FF,$c,$d,$a,$b,$_[14],17,0xffff5bb1,/* 11 */ FF,$b,$c,$d,$a,$_[15],22,0x895cd7be,/* 12 */ FF,$a,$b,$c,$d,$_[16],7,0x6b901122,/* 13 */ FF,$d,$a,$b,$c,$_[17],12,0xfd987193,/* 14 */ FF,$c,$d,$a,$b,$_[18],17,0xa679438e,/* 15 */ FF,$b,$c,$d,$a,$_[19],22,0x49b40821,/* 16 */ GG,$a,$b,$c,$d,$_[5],5,0xf61e2562,/* 17 */ GG,$d,$a,$b,$c,$_[10],9,0xc040b340,/* 18 */ GG,$c,$d,$a,$b,$_[15],14,0x265e5a51,/* 19 */ GG,$b,$c,$d,$a,$_[4],20,0xe9b6c7aa,/* 20 */ GG,$a,$b,$c,$d,$_[9],5,0xd62f105d,/* 21 */ GG,$d,$a,$b,$c,$_[14],9,0x2441453,/* 22 */ GG,$c,$d,$a,$b,$_[19],14,0xd8a1e681,/* 23 */ GG,$b,$c,$d,$a,$_[8],20,0xe7d3fbc8,/* 24 */ GG,$a,$b,$c,$d,$_[13],5,0x21e1cde6,/* 25 */ GG,$d,$a,$b,$c,$_[18],9,0xc33707d6,/* 26 */ GG,$c,$d,$a,$b,$_[7],14,0xf4d50d87,/* 27 */ GG,$b,$c,$d,$a,$_[12],20,0x455a14ed,/* 28 */ GG,$a,$b,$c,$d,$_[17],5,0xa9e3e905,/* 29 */ GG,$d,$a,$b,$c,$_[6],9,0xfcefa3f8,/* 30 */ GG,$c,$d,$a,$b,$_[11],14,0x676f02d9,/* 31 */ GG,$b,$c,$d,$a,$_[16],20,0x8d2a4c8a,/* 32 */ HH,$a,$b,$c,$d,$_[9],4,0xfffa3942,/* 33 */ HH,$d,$a,$b,$c,$_[12],11,0x8771f681,/* 34 */ HH,$c,$d,$a,$b,$_[15],16,0x6d9d6122,/* 35 */ HH,$b,$c,$d,$a,$_[18],23,0xfde5380c,/* 36 */ HH,$a,$b,$c,$d,$_[5],4,0xa4beea44,/* 37 */ HH,$d,$a,$b,$c,$_[8],11,0x4bdecfa9,/* 38 */ HH,$c,$d,$a,$b,$_[11],16,0xf6bb4b60,/* 39 */ HH,$b,$c,$d,$a,$_[14],23,0xbebfbc70,/* 40 */ HH,$a,$b,$c,$d,$_[17],4,0x289b7ec6,/* 41 */ HH,$d,$a,$b,$c,$_[4],11,0xeaa127fa,/* 42 */ HH,$c,$d,$a,$b,$_[7],16,0xd4ef3085,/* 43 */ HH,$b,$c,$d,$a,$_[10],23,0x4881d05,/* 44 */ HH,$a,$b,$c,$d,$_[13],4,0xd9d4d039,/* 45 */ HH,$d,$a,$b,$c,$_[16],11,0xe6db99e5,/* 46 */ HH,$c,$d,$a,$b,$_[19],16,0x1fa27cf8,/* 47 */ HH,$b,$c,$d,$a,$_[6],23,0xc4ac5665,/* 48 */ II,$a,$b,$c,$d,$_[4],6,0xf4292244,/* 49 */ II,$d,$a,$b,$c,$_[11],10,0x432aff97,/* 50 */ II,$c,$d,$a,$b,$_[18],15,0xab9423a7,/* 51 */ II,$b,$c,$d,$a,$_[9],21,0xfc93a039,/* 52 */ II,$a,$b,$c,$d,$_[16],6,0x655b59c3,/* 53 */ II,$d,$a,$b,$c,$_[7],10,0x8f0ccc92,/* 54 */ II,$c,$d,$a,$b,$_[14],15,0xffeff47d,/* 55 */ II,$b,$c,$d,$a,$_[5],21,0x85845dd1,/* 56 */ II,$a,$b,$c,$d,$_[12],6,0x6fa87e4f,/* 57 */ II,$d,$a,$b,$c,$_[19],10,0xfe2ce6e0,/* 58 */ II,$c,$d,$a,$b,$_[10],15,0xa3014314,/* 59 */ II,$b,$c,$d,$a,$_[17],21,0x4e0811a1,/* 60 */ II,$a,$b,$c,$d,$_[8],6,0xf7537e82,/* 61 */ II,$d,$a,$b,$c,$_[15],10,0xbd3af235,/* 62 */ II,$c,$d,$a,$b,$_[6],15,0x2ad7d2bb,/* 63 */ II,$b,$c,$d,$a,$_[13],21,0xeb86d391,/* 64 */
583MD5/Implementation
2perl
b38k4
null
582Menu
11kotlin
0uysf
import math rotate_amounts = [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] constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)] init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \ 16*[lambda b, c, d: (d & b) | (~d & c)] + \ 16*[lambda b, c, d: b ^ c ^ d] + \ 16*[lambda b, c, d: c ^ (b | ~d)] index_functions = 16*[lambda i: i] + \ 16*[lambda i: (5*i + 1)%16] + \ 16*[lambda i: (3*i + 5)%16] + \ 16*[lambda i: (7*i)%16] def left_rotate(x, amount): x &= 0xFFFFFFFF return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF def md5(message): message = bytearray(message) orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message)%64 != 56: message.append(0) message += orig_len_in_bits.to_bytes(8, byteorder='little') hash_pieces = init_values[:] for chunk_ofst in range(0, len(message), 64): a, b, c, d = hash_pieces chunk = message[chunk_ofst:chunk_ofst+64] for i in range(64): f = functions[i](b, c, d) g = index_functions[i](i) to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little') new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF a, b, c, d = d, new_b, b, c for i, val in enumerate([a, b, c, d]): hash_pieces[i] += val hash_pieces[i] &= 0xFFFFFFFF return sum(x<<(32*i) for i, x in enumerate(hash_pieces)) def md5_to_hex(digest): raw = digest.to_bytes(16, byteorder='little') return '{:032x}'.format(int.from_bytes(raw, byteorder='big')) if __name__=='__main__': demo = [b, b, b, b, b, b, b] for message in demo: print(md5_to_hex(md5(message)),' <= ', sep='')
583MD5/Implementation
3python
p6obm
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1) def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(8): a = random.randrange(2, n) if trial_composite(a): return False return True
576Miller–Rabin primality test
3python
xlcwr
fun middleThree(x: Int): Int? { val s = Math.abs(x).toString() return when { s.length < 3 -> null
581Middle three digits
11kotlin
e9ta4
function select (list) if not list or #list == 0 then return "" end local last, sel = #list repeat for i,option in ipairs(list) do io.write(i, ". ", option, "\n") end io.write("Choose an item (1-", tostring(last), "): ") sel = tonumber(string.match(io.read("*l"), "^%d+$")) until type(sel) == "number" and sel >= 1 and sel <= last return list[math.floor(sel)] end print("Nothing:", select {}) print() print("You chose:", select {"fee fie", "huff and puff", "mirror mirror", "tick tock"})
582Menu
1lua
85m0e
#![allow(non_snake_case)]
583MD5/Implementation
15rust
e9daj
object MD5 extends App { def hash(s: String) = { def b = s.getBytes("UTF-8") def m = java.security.MessageDigest.getInstance("MD5").digest(b) BigInt(1, m).toString(16).reverse.padTo(32, "0").reverse.mkString } assert("d41d8cd98f00b204e9800998ecf8427e" == hash("")) assert("0000045c5e2b3911eb937d9d8c574f09" == hash("iwrupvqb346386")) assert("0cc175b9c0f1b6a831c399e269772661" == hash("a")) assert("900150983cd24fb0d6963f7d28e17f72" == hash("abc")) assert("f96b697d7cb7938d525a2f31aaf161d0" == hash("message digest")) assert("c3fcd3d76192e4007dfb496cca67e13b" == hash("abcdefghijklmnopqrstuvwxyz")) assert("d174ab98d277d9f5a5611c2c9f419d9f" == hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) assert("57edf4a22be3c955ac49da2e2107b67a" == hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890")) }
583MD5/Implementation
16scala
q2zxw
function middle_three(n) if n < 0 then n = -n end n = tostring(n) if #n % 2 == 0 then return "Error: the number of digits is even." elseif #n < 3 then return "Error: the number has less than 3 digits." end local l = math.floor(#n/2) return n:sub(l, l+2) end
581Middle three digits
1lua
wczea
def miller_rabin_prime?(n, g) d = n - 1 s = 0 while d % 2 == 0 d /= 2 s += 1 end g.times do a = 2 + rand(n - 4) x = a.pow(d, n) next if x == 1 || x == n - 1 for r in (1..s - 1) x = x.pow(2, n) return false if x == 1 break if x == n - 1 end return false if x!= n - 1 end true end p primes = (3..1000).step(2).find_all {|i| miller_rabin_prime?(i,10)}
576Miller–Rabin primality test
14ruby
sv2qw
use num::bigint::BigInt; use num::bigint::ToBigInt;
576Miller–Rabin primality test
15rust
0uvsl
import Foundation public class MD5 { private let s: [UInt32] = [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] private let K: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) } let a0: UInt32 = 0x67452301 let b0: UInt32 = 0xefcdab89 let c0: UInt32 = 0x98badcfe let d0: UInt32 = 0x10325476 private var message: NSData
583MD5/Implementation
17swift
1yipt
import scala.math.BigInt object MillerRabinPrimalityTest extends App { val (n, certainty )= (BigInt(args(0)), args(1).toInt) println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}") }
576Miller–Rabin primality test
16scala
ig4ox
sub menu { my ($prompt,@array) = @_; return '' unless @array; print " $_: $array[$_]\n" for(0..$ print $prompt; $n = <>; return $array[$n] if $n =~ /^\d+$/ and defined $array[$n]; return &menu($prompt,@array); } @a = ('fee fie', 'huff and puff', 'mirror mirror', 'tick tock'); $prompt = 'Which is from the three pigs: '; $a = &menu($prompt,@a); print "You chose: $a\n";
582Menu
2perl
58au2
<?php $stdin = fopen(, ); $allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock'); for(;;) { foreach ($allowed as $id => $name) { echo ; } echo ; $stdin_string = fgets($stdin, 4096); if (isset($allowed[(int) $stdin_string])) { echo ; break; } }
582Menu
12php
o4985
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix Ik Akbal Kan Chikchan Kimi Manik Lamat Muluk Ok Chuwen Eb Ben Hix Men Kib Kaban Etznab Kawak Ajaw") var civil = strings.Fields("Pop Wo Sip Sotz Sek Xul Yaxkin Mol Chen Yax Sak Keh Mak Kankin Muwan Pax Kayab Kumku Wayeb") var ( date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC) date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC) ) func tzolkin(date time.Time) (int, string) { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 13 if rem < 0 { rem = 13 + rem } var num int if rem <= 9 { num = rem + 4 } else { num = rem - 9 } rem = diff % 20 if rem <= 0 { rem = 20 + rem } return num, sacred[rem-1] } func haab(date time.Time) (string, string) { diff := int(date.Sub(date2).Hours()) / 24 rem := diff % 365 if rem < 0 { rem = 365 + rem } month := civil[(rem+1)/20] last := 20 if month == "Wayeb" { last = 5 } d := rem%20 + 1 if d < last { return strconv.Itoa(d), month } return "Chum", month } func longCount(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 diff += 13 * 400 * 360 baktun := diff / (400 * 360) diff %= 400 * 360 katun := diff / (20 * 360) diff %= 20 * 360 tun := diff / 360 diff %= 360 winal := diff / 20 kin := diff % 20 return fmt.Sprintf("%d.%d.%d.%d.%d", baktun, katun, tun, winal, kin) } func lord(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 9 if rem <= 0 { rem = 9 + rem } return fmt.Sprintf("G%d", rem) } func main() { const shortForm = "2006-01-02" dates := []string{ "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", } fmt.Println(" Gregorian Tzolkin Haab Long Lord of") fmt.Println(" Date # Name Day Month Count the Night") fmt.Println("---------- -------- ------------- -------------- ---------") for _, dt := range dates { date, _ := time.Parse(shortForm, dt) n, s := tzolkin(date) d, m := haab(date) lc := longCount(date) l := lord(date) fmt.Printf("%s %2d%-8s%4s%-9s %-14s %s\n", dt, n, s, d, m, lc, l) } }
584Mayan calendar
0go
jfx7d
import BigInt private let numTrails = 5 func isPrime(_ n: BigInt) -> Bool { guard n >= 2 else { fatalError() } guard n!= 2 else { return true } guard n% 2!= 0 else { return false } var s = 0 var d = n - 1 while true { let (quo, rem) = (d / 2, d% 2) guard rem!= 1 else { break } s += 1 d = quo } func tryComposite(_ a: BigInt) -> Bool { guard a.power(d, modulus: n)!= 1 else { return false } for i in 0..<s where a.power((2 as BigInt).power(i) * d, modulus: n) == n - 1 { return false } return true } for _ in 0..<numTrails where tryComposite(BigInt(BigUInt.randomInteger(lessThan: BigUInt(n)))) { return false } return true }
576Miller–Rabin primality test
17swift
q2lxg
use strict; use warnings; use utf8; binmode STDOUT, ":utf8"; use Math::BaseArith; use Date::Calc 'Delta_Days'; my @sacred = qw<Imix Ik Akbal Kan Chikchan Kimi Manik Lamat Muluk Ok Chuwen Eb Ben Hix Men Kib Kaban Etznab Kawak Ajaw>; my @civil = qw<Pop Wo Sip Sotz Sek Xul Yaxkin Mol Chen Yax Sak Keh Mak Kankin Muwan Pax Kayab Kumku Wayeb>; my %correlation = ( 'gregorian' => '2012-12-21', 'round' => [3,19,263,8], 'long' => 1872000, ); sub mayan_calendar_round { my $date = shift; tzolkin($date), haab($date); } sub offset { my $date = shift; Delta_Days( split('-', $correlation{'gregorian'}), split('-', $date) ); } sub haab { my $date = shift; my $index = ($correlation{'round'}[2] + offset $date) % 365; my ($day, $month); if ($index > 360) { $day = $index - 360; $month = $civil[18]; if ($day == 5) { $day = 'Chum'; $month = $civil[0]; } } else { $day = $index % 20; $month = $civil[int $index / 20]; if ($day == 0) { $day = 'Chum'; $month = $civil[int (1 + $index) / 20]; } } $day, $month } sub tzolkin { my $date = shift; my $offset = offset $date; 1 + ($offset + $correlation{'round'}[0]) % 13, $sacred[($offset + $correlation{'round'}[1]) % 20] } sub lord { my $date = shift; 1 + ($correlation{'round'}[3] + offset $date) % 9 } sub mayan_long_count { my $date = shift; my $days = $correlation{'long'} + offset $date; encode($days, [20,20,20,18,20]); } print <<'EOH'; Gregorian Tzolkin Haab Long Lord of Date ----------------------------------------------------------------------- EOH for my $date (<1961-10-06 2004-06-19 2012-12-18 2012-12-21 2019-01-19 2019-03-27 2020-02-29 2020-03-01 2071-05-16>) { printf "%10s %2s%-9s%4s%-10s %-14s G%d\n", $date, mayan_calendar_round($date), join('.',mayan_long_count($date)), lord($date); }
584Mayan calendar
2perl
6p536
import datetime def g2m(date, gtm_correlation=True): correlation = 584283 if gtm_correlation else 584285 long_count_days = [144000, 7200, 360, 20, 1] tzolkin_months = ['Imix', 'Ik', 'Akbal', 'Kan', 'Chikchan', 'Kimi', 'Manik', 'Lamat', 'Muluk', 'Ok', 'Chuwen', 'Eb', 'Ben', 'Hix', 'Men', 'Kib', 'Kaban', 'Etznab', 'Kawak', 'Ajaw'] haad_months = ['Pop', 'Wo', 'Sip', 'Sotz', 'Sek', 'Xul', 'Yaxkin', 'Mol', 'Chen', 'Yax', 'Sak', 'Keh', 'Mak', 'Kankin', 'Muwan', 'Pax', 'Kayab', 'Kumku', 'Wayeb'] gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal() julian_days = gregorian_days + 1721425 long_date = list() remainder = julian_days - correlation for days in long_count_days: result, remainder = divmod(remainder, days) long_date.append(int(result)) long_date = '.'.join(['{:02d}'.format(d) for d in long_date]) tzolkin_month = (julian_days + 16)% 20 tzolkin_day = ((julian_days + 5)% 13) + 1 haab_month = int(((julian_days + 65)% 365) / 20) haab_day = ((julian_days + 65)% 365)% 20 haab_day = haab_day if haab_day else 'Chum' lord_number = (julian_days - correlation)% 9 lord_number = lord_number if lord_number else 9 round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}' return long_date, round_date if __name__ == '__main__': dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01'] for date in dates: long, round = g2m(date) print(date, long, round)
584Mayan calendar
3python
y146q
def _menu(items): for indexitem in enumerate(items): print (% indexitem) def _ok(reply, itemcount): try: n = int(reply) return 0 <= n < itemcount except: return False def selector(items, prompt): 'Prompt to select an item from the items' if not items: return '' reply = -1 itemcount = len(items) while not _ok(reply, itemcount): _menu(items) reply = raw_input(prompt).strip() return items[int(reply)] if __name__ == '__main__': items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] item = selector(items, 'Which is from the three pigs: ') print ( + item)
582Menu
3python
4oe5k
showmenu <- function(choices = NULL) { if (is.null(choices)) return("") ans <- menu(choices) if(ans==0) "" else choices[ans] } str <- showmenu(c("fee fie", "huff and puff", "mirror mirror", "tick tock")) str <- showmenu()
582Menu
13r
2qblg
int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf(, max); return 0; }
585McNuggets problem
5c
0uzst
use strict ; use warnings ; sub middlethree { my $number = shift ; my $testnumber = abs $number ; my $error = "Middle 3 digits can't be shown" ; my $numberlength = length $testnumber ; if ( $numberlength < 3 ) { print "$error: $number too short!\n" ; return ; } if ( $numberlength % 2 == 0 ) { print "$error: even number of digits in $number!\n" ; return ; } my $middle = int ( $numberlength / 2 ) ; print "Middle 3 digits of $number: " . substr( $testnumber , $middle - 1 , 3 ) . "!\n" ; return ; } my @numbers = ( 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 , 1, 2, -1, -10, 2002, -2002, 0 ) ; map { middlethree( $_ ) } @numbers ;
581Middle three digits
2perl
cwk9a
(defn cart [colls] (if (empty? colls) '(()) (for [more (cart (rest colls)) x (first colls)] (cons x more)))) (defn nuggets [[n6 n9 n20]] (+ (* 6 n6) (* 9 n9) (* 20 n20))) (let [possible (distinct (map nuggets (cart (map range [18 13 6])))) mcmax (apply max (filter (fn [x] (not-any? #{x} possible)) (range 101)))] (printf "Maximum non-McNuggets number is%d\n" mcmax))
585McNuggets problem
6clojure
d79nb
char *MD4(char *str, int len); typedef struct string{ char *c; int len; char sign; }string; static uint32_t *MD4Digest(uint32_t *w, int len); static void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD); static uint32_t changeEndianness(uint32_t x); static void resetMD4Registers(void); static string stringCat(string first, string second); static string uint32ToString(uint32_t l); static uint32_t stringToUint32(string s); static const char *BASE16 = ; static uint32_t A = 0x67452301; static uint32_t B = 0xefcdab89; static uint32_t C = 0x98badcfe; static uint32_t D = 0x10325476; string newString(char * c, int t){ string r; int i; if(c!=NULL){ r.len = (t<=0)?strlen(c):t; r.c=(char *)malloc(sizeof(char)*(r.len+1)); for(i=0; i<r.len; i++) r.c[i]=c[i]; r.c[r.len]='\0'; return r; } r.len=t; r.c=(char *)malloc(sizeof(char)*(r.len+1)); memset(r.c,(char)0,sizeof(char)*(t+1)); r.sign = 1; return r; } string stringCat(string first, string second){ string str=newString(NULL, first.len+second.len); int i; for(i=0; i<first.len; i++){ str.c[i]=first.c[i]; } for(i=first.len; i<str.len; i++){ str.c[i]=second.c[i-first.len]; } return str; } string base16Encode(string in){ string out=newString(NULL, in.len*2); int i,j; j=0; for(i=0; i<in.len; i++){ out.c[j++]=BASE16[((in.c[i] & 0xF0)>>4)]; out.c[j++]=BASE16[(in.c[i] & 0x0F)]; } out.c[j]='\0'; return out; } string uint32ToString(uint32_t l){ string s = newString(NULL,4); int i; for(i=0; i<4; i++){ s.c[i] = (l >> (8*(3-i))) & 0xFF; } return s; } uint32_t stringToUint32(string s){ uint32_t l; int i; l=0; for(i=0; i<4; i++){ l = l|(((uint32_t)((unsigned char)s.c[i]))<<(8*(3-i))); } return l; } char *MD4(char *str, int len){ string m=newString(str, len); string digest; uint32_t *w; uint32_t *hash; uint64_t mlen=m.len; unsigned char oneBit = 0x80; int i, wlen; m=stringCat(m, newString((char *)&oneBit,1)); i=((56-m.len)%64); if(i<0) i+=64; m=stringCat(m,newString(NULL, i)); w = malloc(sizeof(uint32_t)*(m.len/4+2)); for(i=0; i<m.len/4; i++){ w[i]=stringToUint32(newString(&(m.c[4*i]), 4)); } w[i++] = (mlen<<3) & 0xFFFFFFFF; w[i++] = (mlen>>29) & 0xFFFFFFFF; wlen=i; for(i=0; i<wlen-2; i++){ w[i]=changeEndianness(w[i]); } hash = MD4Digest(w,wlen); digest=newString(NULL,0); for(i=0; i<4; i++){ hash[i]=changeEndianness(hash[i]); digest=stringCat(digest,uint32ToString(hash[i])); } return base16Encode(digest).c; } uint32_t *MD4Digest(uint32_t *w, int len){ int i,j; uint32_t X[16]; uint32_t *digest = malloc(sizeof(uint32_t)*4); uint32_t AA, BB, CC, DD; for(i=0; i<len/16; i++){ for(j=0; j<16; j++){ X[j]=w[i*16+j]; } AA=A; BB=B; CC=C; DD=D; MD4ROUND1(A,B,C,D,X[0],3); MD4ROUND1(D,A,B,C,X[1],7); MD4ROUND1(C,D,A,B,X[2],11); MD4ROUND1(B,C,D,A,X[3],19); MD4ROUND1(A,B,C,D,X[4],3); MD4ROUND1(D,A,B,C,X[5],7); MD4ROUND1(C,D,A,B,X[6],11); MD4ROUND1(B,C,D,A,X[7],19); MD4ROUND1(A,B,C,D,X[8],3); MD4ROUND1(D,A,B,C,X[9],7); MD4ROUND1(C,D,A,B,X[10],11); MD4ROUND1(B,C,D,A,X[11],19); MD4ROUND1(A,B,C,D,X[12],3); MD4ROUND1(D,A,B,C,X[13],7); MD4ROUND1(C,D,A,B,X[14],11); MD4ROUND1(B,C,D,A,X[15],19); MD4ROUND2(A,B,C,D,X[0],3); MD4ROUND2(D,A,B,C,X[4],5); MD4ROUND2(C,D,A,B,X[8],9); MD4ROUND2(B,C,D,A,X[12],13); MD4ROUND2(A,B,C,D,X[1],3); MD4ROUND2(D,A,B,C,X[5],5); MD4ROUND2(C,D,A,B,X[9],9); MD4ROUND2(B,C,D,A,X[13],13); MD4ROUND2(A,B,C,D,X[2],3); MD4ROUND2(D,A,B,C,X[6],5); MD4ROUND2(C,D,A,B,X[10],9); MD4ROUND2(B,C,D,A,X[14],13); MD4ROUND2(A,B,C,D,X[3],3); MD4ROUND2(D,A,B,C,X[7],5); MD4ROUND2(C,D,A,B,X[11],9); MD4ROUND2(B,C,D,A,X[15],13); MD4ROUND3(A,B,C,D,X[0],3); MD4ROUND3(D,A,B,C,X[8],9); MD4ROUND3(C,D,A,B,X[4],11); MD4ROUND3(B,C,D,A,X[12],15); MD4ROUND3(A,B,C,D,X[2],3); MD4ROUND3(D,A,B,C,X[10],9); MD4ROUND3(C,D,A,B,X[6],11); MD4ROUND3(B,C,D,A,X[14],15); MD4ROUND3(A,B,C,D,X[1],3); MD4ROUND3(D,A,B,C,X[9],9); MD4ROUND3(C,D,A,B,X[5],11); MD4ROUND3(B,C,D,A,X[13],15); MD4ROUND3(A,B,C,D,X[3],3); MD4ROUND3(D,A,B,C,X[11],9); MD4ROUND3(C,D,A,B,X[7],11); MD4ROUND3(B,C,D,A,X[15],15); A+=AA; B+=BB; C+=CC; D+=DD; } digest[0]=A; digest[1]=B; digest[2]=C; digest[3]=D; resetMD4Registers(); return digest; } uint32_t changeEndianness(uint32_t x){ return ((x & 0xFF) << 24) | ((x & 0xFF00) << 8) | ((x & 0xFF0000) >> 8) | ((x & 0xFF000000) >> 24); } void setMD4Registers(uint32_t AA, uint32_t BB, uint32_t CC, uint32_t DD){ A=AA; B=BB; C=CC; D=DD; } void resetMD4Registers(void){ setMD4Registers(0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476); }
586MD4
5c
d7mnv
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.': '.middlethree($nums). '<br>'; }
581Middle three digits
12php
xl3w5
(use 'pandect.core) (md4 "Rosetta Code")
586MD4
6clojure
6pv3q
def select(prompt, items = []) if items.empty? '' else answer = -1 until (0...items.length).cover?(answer) items.each_with_index {|i,j| puts } print begin answer = Integer(gets) rescue ArgumentError redo end end items[answer] end end response = select('Which is empty') puts items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] response = select('Which is from the three pigs', items) puts
582Menu
14ruby
rnxgs
import 'dart:math'; main() { var nuggets = List<int>.generate(101, (int index) => index); for (int small in List<int>.generate((100 ~/ (6 + 1)), (int index) => index)) { for (int medium in List<int>.generate((100 ~/ (9 + 1)), (int index) => index)) { for (int large in List<int>.generate((100 ~/ (20 + 1)), (int index) => index)) { nuggets.removeWhere((element) => element == 6 * small + 9 * medium + 20 * large); } } } print('Largest non-McNuggets number: ${nuggets.reduce(max).toString()?? 'none'}.'); }
585McNuggets problem
18dart
amo1h
fn menu_select<'a>(items: &'a [&'a str]) -> &'a str { if items.len() == 0 { return ""; } let stdin = std::io::stdin(); let mut buffer = String::new(); loop { for (i, item) in items.iter().enumerate() { println!("{}) {}", i + 1, item); } print!("Pick a number from 1 to {}: ", items.len());
582Menu
15rust
7dqrc
import scala.util.Try object Menu extends App { val choice = menu(list) def menu(menuList: Seq[String]): String = { if (menuList.isEmpty) "" else { val n = menuList.size def getChoice: Try[Int] = { println("\n M E N U\n") menuList.zipWithIndex.map { case (text, index) => s"${index + 1}: $text" }.foreach(println(_)) print(s"\nEnter your choice 1 - $n: ") Try { io.StdIn.readInt() } } menuList(Iterator.continually(getChoice) .dropWhile(p => p.isFailure ||!(1 to n).contains(p.get)) .next.get - 1) } } def list = Seq("fee fie", "huff and puff", "mirror mirror", "tick tock") println(s"\nYou chose: $choice") }
582Menu
16scala
kz8hk
func getMenuInput(selections: [String]) -> String { guard!selections.isEmpty else { return "" } func printMenu() { for (i, str) in selections.enumerated() { print("\(i + 1)) \(str)") } print("Selection: ", terminator: "") } while true { printMenu() guard let input = readLine(strippingNewline: true),!input.isEmpty else { return "" } guard let n = Int(input), n > 0, n <= selections.count else { continue } return selections[n - 1] } } let selected = getMenuInput(selections: [ "fee fie", "huff and puff", "mirror mirror", "tick tock" ]) print("You chose: \(selected)")
582Menu
17swift
giw49
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length% 2 == 1, mid = length return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print(% (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
581Middle three digits
3python
lxbcv
using namespace std; const int BMP_SIZE = 512, CELL_SIZE = 8; enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 }; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class mazeGenerator { public: mazeGenerator() { _world = 0; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.setPenColor( RGB( 0, 255, 0 ) ); } ~mazeGenerator() { killArray(); } BYTE* getMaze() const { return _world; } void create( int side ) { _s = side; generate(); } private: void generate() { killArray(); _world = new BYTE[_s * _s]; ZeroMemory( _world, _s * _s ); _ptX = rand() % _s; _ptY = rand() % _s; carve(); } void carve() { while( true ) { int d = getDirection(); if( d < NOR ) return; switch( d ) { case NOR: _world[_ptX + _s * _ptY] |= NOR; _ptY--; _world[_ptX + _s * _ptY] = SOU | SOU << 4; break; case EAS: _world[_ptX + _s * _ptY] |= EAS; _ptX++; _world[_ptX + _s * _ptY] = WES | WES << 4; break; case SOU: _world[_ptX + _s * _ptY] |= SOU; _ptY++; _world[_ptX + _s * _ptY] = NOR | NOR << 4; break; case WES: _world[_ptX + _s * _ptY] |= WES; _ptX--; _world[_ptX + _s * _ptY] = EAS | EAS << 4; } } } int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDir( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; } d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; if( !d ) return -1; switch( d ) { case NOR: _ptY--; break; case EAS: _ptX++; break; case SOU: _ptY++; break; case WES: _ptX--; break; } d = 1 << rand() % 4; } } bool testDir( int d ) { switch( d ) { case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); } return false; } void killArray() { if( _world ) delete [] _world; } BYTE* _world; int _s, _ptX, _ptY; myBitmap _bmp; }; class mazeSolver { public: mazeSolver() { _bmp.create( BMP_SIZE, BMP_SIZE ); _pts = 0; } ~mazeSolver() { killPoints(); } void solveIt( BYTE* maze, int size, int sX, int sY, int eX, int eY ) { _lastDir = NONE; _world = maze; _s = size; _sx = sX; _sy = sY; _ex = eX; _ey = eY; for( int y = 0; y < _s; y++ ) for( int x = 0; x < _s; x++ ) _world[x + _s * y] &= 0x0f; _world[_sx + _s * _sy] |= NOR << 4; killPoints(); _pts = new BYTE[_s * _s]; ZeroMemory( _pts, _s * _s ); findTheWay(); _sx = sX; _sy = sY; display(); } private: int invert( int d ) { switch( d ) { case NOR: return SOU; case SOU: return NOR; case WES: return EAS; case EAS: return WES; } return NONE; } void updatePosition( int d ) { switch( d ) { case NOR: _sy--; break; case EAS: _sx++; break; case SOU: _sy++; break; case WES: _sx--; } } void findTheWay() { while( true ) { int d = getDirection(); if( d < NOR ) return; _lastDir = invert( d ); _world[_sx + _s * _sy] |= d; _pts[_sx + _s * _sy] = d; updatePosition( d ); if( _sx == _ex && _sy == _ey ) return; _world[_sx + _s * _sy] |= _lastDir << 4; } } int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDirection( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; } d = ( _world[_sx + _s * _sy] & 0xf0 ) >> 4; if( !d ) return -1; _pts[_sx + _s * _sy] = 0; updatePosition( d ); _lastDir = invert( d ); d = 1 << rand() % 4; } } bool testDirection( int d ) { if( d == _lastDir || !( _world[_sx + _s * _sy] & d ) ) return false; switch( d ) { case NOR: return _sy - 1 > -1 && !( _world[_sx + _s * ( _sy - 1 )] & 0xf0 ); case EAS: return _sx + 1 < _s && !( _world[_sx + 1 + _s * _sy] & 0xf0 ); case SOU: return _sy + 1 < _s && !( _world[_sx + _s * ( _sy + 1 )] & 0xf0 ); case WES: return _sx - 1 > -1 && !( _world[_sx - 1 + _s * _sy] & 0xf0 ); } return false; } void display() { _bmp.setPenColor( RGB( 0, 255, 0 ) ); _bmp.clear(); HDC dc = _bmp.getDC(); for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE b = _world[x + yy]; int nx = x * CELL_SIZE, ny = y * CELL_SIZE; if( !( b & NOR ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny ); } if( !( b & EAS ) ) { MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); } if( !( b & SOU ) ) { MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); } if( !( b & WES ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx, ny + CELL_SIZE + 1 ); } } } drawEndPoints( dc ); _bmp.setPenColor( RGB( 255, 0, 0 ) ); for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE d = _pts[x + yy]; if( !d ) continue; int nx = x * CELL_SIZE + 4, ny = y * CELL_SIZE + 4; MoveToEx( dc, nx, ny, NULL ); switch( d ) { case NOR: LineTo( dc, nx, ny - CELL_SIZE - 1 ); break; case EAS: LineTo( dc, nx + CELL_SIZE + 1, ny ); break; case SOU: LineTo( dc, nx, ny + CELL_SIZE + 1 ); break; case WES: LineTo( dc, nx - CELL_SIZE - 1, ny ); break; } } } _bmp.saveBitmap( ); BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); } void drawEndPoints( HDC dc ) { RECT rc; int x = 1 + _sx * CELL_SIZE, y = 1 + _sy * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); x = 1 + _ex * CELL_SIZE, y = 1 + _ey * CELL_SIZE; SetRect( &rc, x, y, x + CELL_SIZE - 1, y + CELL_SIZE - 1 ); FillRect( dc, &rc, ( HBRUSH )GetStockObject( WHITE_BRUSH ) ); } void killPoints() { if( _pts ) delete [] _pts; } BYTE* _world, *_pts; int _s, _sx, _sy, _ex, _ey, _lastDir; myBitmap _bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); mazeGenerator mg; mazeSolver ms; int s; while( true ) { cout << ; cin >> s; if( !s ) return 0; if( !( s & 1 ) ) s++; if( s >= 3 ) { mg.create( s ); int sx, sy, ex, ey; while( true ) { sx = rand() % s; sy = rand() % s; ex = rand() % s; ey = rand() % s; if( ex != sx || ey != sy ) break; } ms.solveIt( mg.getMaze(), s, sx, sy, ex, ey ); cout << endl; } system( ); system( ); } return 0; }
587Maze solving
5c
e98av
package main import ( "golang.org/x/crypto/md4" "fmt" ) func main() { h := md4.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
586MD4
0go
7dar2
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1)
585McNuggets problem
0go
u0kvt
#!/usr/bin/env runhaskell import Data.ByteString.Char8 (pack) import System.Environment (getArgs) import Crypto.Hash main :: IO () main = print . md4 . pack . unwords =<< getArgs where md4 x = hash x :: Digest MD4
586MD4
8haskell
85z0z
import Data.Set (Set, fromList, member) gaps :: [Int] gaps = dropWhile (`member` mcNuggets) [100,99 .. 1] mcNuggets :: Set Int mcNuggets = let size = enumFromTo 0 . quot 100 in fromList $ size 6 >>= \x -> size 9 >>= \y -> size 20 >>= \z -> let v = sum [6 * x, 9 * y, 20 * z] in [ v | 101 > v ] main :: IO () main = print $ case gaps of x:_ -> show x [] -> "No unreachable quantities found ..."
585McNuggets problem
8haskell
wcned
(ns small-projects.find-shortest-way (:require [clojure.string:as str])) (defn cell-empty? [maze coords] (=:empty (get-in maze coords))) (defn wall? [maze coords] (=:wall (get-in maze coords))) (defn track? [maze coords] (=:track (get-in maze coords))) (defn get-neighbours [maze [y x cell]] [[y (dec x)] [(inc y) x] [y (inc x)] [(dec y) x]]) (defn get-difference [coll1 filter-coll] (filter #(not (contains? filter-coll %)) coll1)) (defn get-empties [maze cell] (->> (get-neighbours maze cell) (filter (partial cell-empty? maze)))) (defn possible-ways [maze cell filter-coll] (-> (get-empties maze cell) (get-difference filter-coll))) (defn replace-cells [maze coords v] (if (empty? coords) maze (recur (assoc-in maze (first coords) v) (rest coords) v))) (def cell-code->str [" " " " " " " " " " " " " " " " " " " " " " " " "" "" "" "" " " " " " " " " " " " " " " " " " " " " " " " " "" "" "" "" " " " " " " " " " " " " " " " " " " " " " " " " "" "" "" "" " " " " " " " " " " " " " " " " " " " " " " " " "" "" "" "" " "]) (defn get-cell-code [maze coords] (let [mode (if (track? maze coords) 1 0) check (if (zero? mode) wall? track?)] (transduce (comp (map (partial check maze)) (keep-indexed (fn [idx test] (when test idx))) (map (partial bit-shift-left 1))) (completing bit-or) (bit-shift-left mode 5) (sort (conj (get-neighbours maze coords) coords))))) (defn code->str [cell-code] (nth cell-code->str cell-code)) (defn maze->str-symbols [maze] (for [y (range (count maze))] (for [x (range (count (nth maze y)))] (code->str (get-cell-code maze [y x]))))) (defn maze->str [maze] (->> (maze->str-symbols maze) (map str/join) (str/join "\n"))) (defn parse-pretty-maze [maze-str] (->> (str/split-lines maze-str) (map (partial take-nth 2)) (map (partial map #(if (= \space %):empty:wall))) (map vec) (vec))) (defn find-new-border [maze border old-border] (apply conj (map (fn [cell] (zipmap (possible-ways maze cell (conj border old-border)) (repeat cell))) (keys border)))) (defn backtrack [visited route] (let [cur-cell (get visited (first route))] (if (= cur-cell:start) route (recur visited (conj route cur-cell))))) (defn breadth-first-search [maze start-cell end-cell] (loop [visited {start-cell:start} border {start-cell:start} old-border {start-cell:start}] (if (contains? old-border end-cell) (backtrack visited (list end-cell)) (recur (conj visited border) (find-new-border maze border old-border) border)))) (def maze (parse-pretty-maze maze-str)) (def solved-maze (replace-cells maze (breadth-first-search maze [1 1] [19 19]):track)) (println (maze->str solved-maze))
587Maze solving
6clojure
0ufsj
int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0; int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } } printf(, tri[0]); return 0; }
588Maximum triangle path sum
5c
xlowu