text
stringlengths
180
608k
[Question] [ Suppose you have existing regexes you wish to compile using one of the submissions to [Compile Regexes](https://codegolf.stackexchange.com/questions/7024/compile-regexes). In as few characters as possible, write a program that: * accepts an existing regex as input, as either (a) one line from standard input; or (b) one argument from the command line; or (c) the contents of a textbox in a dialog box; then * converts the regex into one that works with the compiler (see "Equivalent constructs"); then * prints the new regex either (a) on standard output; or (b) in a dialog box. ## Equivalent constructs You can convert... * ... the anchors `^` and `$` to the empty string. If `^` is not at the beginning (and/or if `$` is not at the end), prepend (and/or append) `.*`. (You may assume any `^` anchor is the first character of the regex and any `$` anchor is the last character of the regex.) * ... non-capturing groups to normal groups; replace `(?:x)` with `(x)`. * ... character classes; replace `.` with `[0-9A-Za-z]`, `\d` with `[0-9]`, and `\D` with `[A-Za-z]`. No character class will occur inside a bracket expression. * ... bracket expressions to groups containing alternation. For example, `[0-9A-FZ]` can become `(0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|Z)`, and `[^0A-Za-z]` can become `(1|2|3|4|5|6|7|8|9)`. * ... the plus operator: `+` to `{1,}`. * ... braces (`x` is the nearest character or group to the left): + `x{m}` to m × `x`. + `x{m,}` to m × `x` followed by `x*`. + `x{m,n}` to m × `x` followed by either of: - (n-m) × `x?` - (n-m) × `(|x` then (n-m) × `)` * ... the question mark operator: `x?` to `(|x)` or `(x|)`. ## Special rules * You may assume all non-alphanumeric characters are metacharacters. * Do not use general-purpose or Unicode algorithms to compress your code. * Methods of input and output are implementation defined yet may not trivialize the solution. * Using a special-purpose regex parsing library is prohibited. However, using one or more regexes as a tool for parsing the regex is OK (see below Scoring section). * The input will never be longer than 1000 bytes. ## Scoring Generally, the score is the number of characters in your submission. However, **you must double your score if you use a find-and-replace function and double it again if you use any regex or pattern matching function.** When writing your program, carefully consider whether to use regex and/or pattern matching functions, as using one just once quadruples your score. ## Test cases Infinitely many valid outputs exist for each input case; thus, I have chosen a single example of possible output for each. The final test case is perhaps the trickiest. ### Begins with "A" ``` Input: ^A Output: A(0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)* ``` * Valid: Abra, Absol, Aerodactyl, Aipom, Alakazam * Invalid: abra, absol, Bayleef, Beedrill ### Contains "sex" ``` Input: sex Output: (0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)*sex(0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)* ``` * Valid: partsexpress, sextet, middlesex * Invalid: partSEXpress, SEXtet, middleSEX ### Any decimal integer ``` Input: ^\d+$ Output: (0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)* ``` * Valid: 0, 7, 51, 370, 1040, 65536, 007, 051, 0000370, 001040, 065536 * Invalid: (the empty string), football, 10NIS ### Decimal integer without leading zeroes ``` Input: ^(0|[1-9]\d*)$ Output: (0|(1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)*) ``` * Valid: 0, 7, 51, 370, 1040, 65536 * Invalid: 007, 051, 0000370, 001040, 065536, football, 10NIS ### Lowercase Q without U word ``` Input: ^[a-tv-z]*q[a-tv-z]*$ Output: (a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|v|w|x|y|z)*q(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|v|w|x|y|z)* ``` * Valid: faqir, faqirs, qaid, qaids, qanat, qanats, qat, qats, qi, qindar, qindarka, qindars, qintar, qintars, qoph, qophs, qwerty, qwertys, sheqalim, sheqel, tranq, tranqs * Invalid: Faqir, qAid, quid, liquefy ### Ends in a vowel then three or more consonants ``` Input: [AEIOUaeiou][^0-9AEIOUaeiou]{3,}$ Output: (0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)*(A|E|I|O|U|a|e|i|o|u)(B|C|D|F|G|H|J|K|L|M|N|P|Q|R|S|T|V|W|X|Y|Z|b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z)(B|C|D|F|G|H|J|K|L|M|N|P|Q|R|S|T|V|W|X|Y|Z|b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z)(B|C|D|F|G|H|J|K|L|M|N|P|Q|R|S|T|V|W|X|Y|Z|b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z)(B|C|D|F|G|H|J|K|L|M|N|P|Q|R|S|T|V|W|X|Y|Z|b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|w|x|y|z)* ``` * Valid: Bouncy, bouncy, erhythm * Invalid: Noisy, noisy, Dodge, rhythm ### Exception to I before E, except after C ``` Input: ^\D*([^Cc][Ee][Ii]|[Cc][Ii][Ee])\D*$ Output: (A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)*((0|1|2|3|4|5|6|7|8|9|A|B|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)(E|e)(I|i)|(C|c)(I|i)(E|e))(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)* ``` * Valid (and incorrectly spelled): AIRFEILD, AIRfeild, eyepeice, reciept, veiwer, zeitgiest * Valid (yet correctly spelled): forfeit, glacier, science, zeitgeist * Invalid (and correctly spelled): AIRFIELD, AIRfield, eyepiece, receipt, viewer * Invalid (yet incorrectly spelled): 6AIRFIELD, AIRFIELD0, forfiet, glaceir, sceince, zietgiest ### U.S. amateur radio callsign (Note that the FCC has [reserved some of these](http://wireless.fcc.gov/services/index.htm?job=call_signs_3&id=amateur&page=1#Call%20Sign%20Availability) (*e.g.* callsigns containing "SOS"), so not all of the matched callsigns could be legitimate callsigns used by U.S. amateur radio operators. 1x1 "special event" callsigns are not included.) ``` Input: ^(?:[KNW]\d[A-Z]{2,3}|(?:A[A-L]|[KNW][A-Z])\d[A-Z]{1,2}|[KW][A-Z]\d[A-Z]{3})$ Output: ((K|N|W)(0|1|2|3|4|5|6|7|8|9)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(|(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z))|(A(A|B|C|D|E|F|G|H|I|J|K|L)|(K|N|W)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z))(0|1|2|3|4|5|6|7|8|9)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(|(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z))|(K|W)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(0|1|2|3|4|5|6|7|8|9)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)) ``` * Valid: W1AW, AB0C, AB2MH, NZ9WA, K9DOG, KL5CD, KA2DOG, KN0WCW * Invalid: WWVB, AB00, AM8ER, NZ99A, L9DOG, KNOWCW, KN0WCWW, kn0wcw [Answer] # perl, 1111 916 bytes There is more golfing to do, but under 1000 bytes seemed like a good stopping point, especially as no one else has answered this question yet =) ``` @l=("A".."Z","a".."z");@h=(0..9,@l);sub g{join"|",@_}sub p{length$_[0]>1&&substr($_[0],0,1)ne"("?"($_[0])":$_[0]}sub e{$e=$_[0];for(split//,$_[1]){return if$i[$e++]ne$_}1}sub x{push@o,$l=p g @_}$w=c("^.*\$");sub N{++$n}sub I{$i[$n]}sub c{@i=split//,shift;$f=$t=0;shift@i,$f=1 if$i[0]eq"^";pop@i,$t=1 if$i[-1]eq"\$";@o=();for($n=0;$n<@i;N){if(e$n,"(?:"){push@o,"(";N;N}elsif(e$n,"."){x@h}elsif(e$n,"\\d"){x 0..9;N}elsif(e$n,"\\D"){x@l;N}elsif(e$n,"["){N;my($v,@c);$v=1,N if"^"eq I;while(I ne"]"){push@c,$i[$n+1]eq"-"?I..$i[$n+=2]:I;N}@c=grep{$d=$_;!grep{$_ eq$d}@c}@h if$v;x @c}elsif(e$n,"?"){splice@o,-1,1,"(|$l)"}elsif(e$n,"+"){$l=p$l;splice@o,-1,1,"$l$l*"}elsif(e$n,"{"){N;my($j,$k,$h);$j.=$i[$n++]until","eq I||"}"eq I;if(","eq I){$h=1;$k.=I until$i[N]eq"}"}$l=p$l;@r=$l x$j;push@r,defined$k?"(|$l)"x($k-$j):"$l*"if$h;splice@o,-1,1,@r}else{x I}}push@o,$w if!$t;join"",$f?@o:($w,@o)}while(<>){chomp;print c($_).$/} ``` And here's a still-pretty-obfuscated, but at-least-it's-indented version: ``` use strict; use warnings; my @let = ('A'..'Z','a'..'z'); my @chars = (0..9,@let); sub g { join('|',@_) } sub p { length $_[0] > 1 && substr($_[0],0,1) ne '(' ? "($_[0])" : $_[0] }; sub comp { my @i = split//,shift; my ($front_anchor, $tail_anchor); if($i[0] eq '^') { shift @i; $front_anchor=1 } if($i[-1] eq '$') { pop @i; $tail_anchor=1 } my @out; my $last; for(my $n=0;$n<@i;++$n) { if($i[$n] eq '(' && $i[$n+1] eq '?' && $i[$n+2] eq ':') { push @out, '('; $n+=2; } elsif($i[$n] eq '.') { $last = g @chars; push @out, p $last; } elsif($i[$n] eq '\\' && $i[$n+1] eq 'd') { $last = g 0..9; push @out, p $last; ++$n; } elsif($i[$n] eq '\\' && $i[$n+1] eq 'D') { $last = g @let; push @out, p $last; ++$n; } elsif($i[$n] eq '[') { ++$n; my $invert=0; if($i[$n] eq '^') { $invert=1; ++$n; } my @c; do { if($i[$n+1] eq '-') { push @c, $i[$n]..$i[$n+2]; $n+=2; } else { push @c, $i[$n]; } ++$n; } while($i[$n] ne ']'); @c = grep { my $c=$_; !grep { $_ eq $c } @c } @chars if $invert; $last = g @c; push @out, p $last; } elsif($i[$n] eq '?') { $last = "(|$last)"; splice @out, -1, 1, $last; } elsif($i[$n] eq '+') { $last = p $last; $last = "$last$last*"; splice @out, -1, 1, $last; } elsif($i[$n] eq '{') { ++$n; my ($bm, $bn, $hc); $bm .= $i[$n++] until $i[$n] eq ',' || $i[$n] eq '}'; if($i[$n] eq ',') { $hc=1; $bn .= $i[$n] until $i[++$n] eq '}'; } my @r; push @r, p $last for 1..$bm; push @r, p($last).'*' if $hc && !defined $bn; if($hc && defined $bn) { my $y = $bn - $bm; push @r, '(|'.p($last).')' for 1..$y; } splice @out, -1, 1, @r; undef $last; #no nested quantifiers } else { $last = $i[$n]; push @out, $last; } } @out = (comp('^.*$'),@out) unless $front_anchor; @out = (@out,comp('^.*$')) unless $tail_anchor; return wantarray?@out:join"",@out; } while(<>) { chomp; print comp($_)."\n"; } ``` ]
[Question] [ The challenge is to create one program that will accept as arguments (arrays of arrays) or on standard input (line-by-line, separated by commas) a collection of families and names, like so: ``` John,Anna Mark,James Elizabeth,Daniel,Isabelle Ryan,Ruth ``` As well as two other arguments (two more arrays of pairs, as arrays) or on standard input (a blank line after the preceding input, followed by two comma-separated lists on two lines with an `=` separating pairings; see example) that represent the two previous years' Christmas lists: ``` John=Mark,James=Anna,Elizabeth=Ryan,... John=Isabelle,Ryan=Elizabeth,Daniel=Mark,... ``` The function/program must return/output (in any format) a way that each person is assigned somebody to give a present to, following these rules: 1. A person cannot give a present to him or herself. 2. A person cannot give a present to anybody in his or her own family. 3. A person cannot be assigned the same person he or she was assigned in any of the two previous years. If such a matching is impossible for every person, output/return `null` or nothing or something appropriate. This is a code golf, so shortest code wins, but I'll also give a bounty to the code that runs fastest (on my computer, at least, though results shouldn't vary much). [Answer] ### GolfScript, 90 characters ``` +:q;:f[]*:^[]:r\{.,{(^3${1=}%-f{2$\?)},~-q{(3$={-.}*;}/{.[[2$\]]4$|3$c;}%;;;}{;:r}if;}:c~r ``` The program does a simple recursive search on the names. It actually calculates all possible lists but saves them to a variable for output, so only the last one is returned. The input/output is on the interpreter stack (first families then two previous years` assignments), e.g. ``` #PREPARE INPUT ; [["John" "Anna"]["Mark" "James"]["Elizabeth" "Daniel" "Isabelle"]["Ryan" "Ruth"]] [["Ruth" "John"] ["Ryan" "Daniel"] ["Isabelle" "Mark"] ["Daniel" "Anna"] ["Elizabeth" "James"] ["James" "Elizabeth"] ["Mark" "Ryan"] ["Anna" "Isabelle"] ["John" "Ruth"]] [["Ruth" "Anna"] ["Ryan" "Elizabeth"] ["Isabelle" "John"] ["Daniel" "James"] ["Elizabeth" "Mark"] ["James" "Daniel"] ["Mark" "Isabelle"] ["Anna" "Ruth"] ["John" "Ryan"]] #PROGRAM +:q;:f[]*:^[]:r\{.,{(^3${1=}%-f {2$\?)},~-q{(3$={-.}*;}/{.[[2$\]]4$|3$c;}%;;;}{;:r}if;}:c~r #SHOW OUTPUT p ``` prints the output ``` [["Ruth" "Elizabeth"] ["Ryan" "John"] ["Isabelle" "James"] ["Daniel" "Mark"] ["Elizabeth" "Anna"] ["James" "Ruth"] ["Mark" "Daniel"] ["Anna" "Ryan"] ["John" "Isabelle"]] ``` ]
[Question] [ there is only one rule: get accept for this problem <http://acm.ut.ac.ir/sc/problemset/view/1032>! to submit your code, you need to create an account(if you don't want to do so, just post your code here and I'll submit it). so far shortest code is written with C and has 85 character length. winner will be the shortest C/C++ code submitted before 2012/02/01 note: to check shortest codes submitted you can click on "accepted runs" and then "code length" as elssar suggested I've copied the question here : How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below. [figure http://acm.ut.ac.ir/sc/assets/problem\_images/1032\_50ac13c53158fd843d1884e8afa962dd.jpg](http://acm.ut.ac.ir/sc/assets/problem_images/1032_50ac13c53158fd843d1884e8afa962dd.jpg) # Input The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits. # Output For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples. # Sample Input 1.00 3.71 0.04 5.19 0.00 # Sample Output 3 card(s) 61 card(s) 1 card(s) 273 card(s) [Answer] ## C, 149 89 Well, this was a noobish shot at it, but probably a decent starting point: ``` #include <cstdio> float i; int o(float a,int n=2){return a<0?n-2:o(a-1./n,n+1);} main(){if (scanf("%f",&i),i==0) return 0;printf("%d card(s)\n",o(i));main();} ``` It reported as 145 characters. --- With a push in the right direction, I got the solution down to 122 by changing the function to a for loop. ``` #include <cstdio> float i; main(){ if (scanf("%f",&i),i==0) return 0; int n=2;for(;i>0;)i-=1./n++; printf("%d card(s)\n",n-2); main();} ``` --- On a roll! ``` #include <cstdio> main() { float i,n=2; for(scanf("%f",&i);i>0;i-=1/n++); if (n-=2) printf("%.0f card(s)\n",n), main(); } ``` Scooted `scanf`, for loop division doesn't need `1.` any more, adjusting `n` now done in conditional. --- Switched over to C, got some good savings. Down to 89 characters. ``` main(n) { float i; for(scanf("%f",&i);i>0;i-=1./++n); if (--n) printf("%d card(s)\n",n), main(1); } ``` [Answer] As I said so far there is an answer with 85 characters written in C99 (note that white spaces are not counted) ``` main(i){for(float x;i=scanf("%f",&x),x;printf("%d card(s)\n",--i))for(;x>0;x-=1./++i);} ``` that was the whole code, hope It gives you the idea how to optimize it! ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/1060/edit) Let's say that we are programming a game that lets you play Scrabble®. * We have a board with tiles placed on it, and empty cells are either normal or have multiplier properties (double or triple the points for a word or for a single letter). * Each tile has a value and blank tiles have no value. Thee goal here is to write a method that, given a `new_word` structure, will: * verify that this word can be placed onto the grid at the specified position (the originating rack has the missing letters, it is not out of board range, blank tiles will not be adjacent on the board) * return the number of points granted to the player. * letter multipliers have priority over word multipliers * all new words on the grid are counted (both horizontal and vertical) Below are sample structures provided as an example. ``` // SCRABBLE® STRUCTURES // a single Scrabble® tile. struct tile { // blank tiles are recognized by their value of 0. // The value of 'letter' is a space (L' ') until they // are positioned on the board. From that stage the // value of 'letter' contains what they represent. wchar_t letter; unsigned int points; }; // the bag with undrawed tiles struct tile_bag { // English version: 100 at start of game unsigned int remaining_tiles; tile *tiles; }; // the content of a player rack struct player_rack { unsigned int tile_count; tile *tiles; }; // a multiplier square struct multiplier_cell { enum { letter_scope, word_scope, } multiplier_scope; unsigned int multiplication_factor; }; // a cell on the Scrabble® board struct cell { enum { normal, // empty cell with no multiplier multiplier, // empty special cell, see multiplier_detail tile, // cell with a tile on it, see tile_detail } cell_type; union { multiplier_cell multiplier_detail; tile tile_detail; }; }; // a scrabble board; struct board { unsigned int width; // usually 15 unsigned int height; // usually 15 cell **cells; }; // a new word, placed on the grid struct new_word { // zero-terminated string representing the actual word. const wchar_t *zWord; // the same string, but with spaces for blanks that come // from the rack const wchar_t *zWord_with_blanks; // the rack the word originates from player_rack *original_rack; // the cell position where the word begins unsigned int verticalStart; unsigned int horizontalStart; // the direction enum { vertical, horizontal, } direction; }; // SCRABBLE® NUMERIC CONSTANTS // how many tiles are allowed on the rack of a single player // this is also the number of tiles that grant a bonus when // placed onto the board at the same time. // usually 7 extern const int max_allowed_tiles_on_a_rack; // how many extra points are granted when scrabbling // usually 50 extern const int scrabble_extra_points; // GLOBAL VARIABLES extern board theBoard; extern tile_bag theBag; extern int theNumberOfPlayers; extern player_rack *theRacks; ``` [Answer] # Haskell: ``` pointsFromWord :: [[Tile]] -> [Char] -> Word -> Maybe Int pointsFromWord board rack (word, (x, y), Vertical) = pointsFromWord (transpose board) rack (Word word (y,x) Horizontal) pointsFromWord board rack w@(word, (x, y), Horizontal) = if (validWord board w) then Just (wordScore board w) else Nothing validWord :: [[Tile]] -> [Char] -> Word -> Bool validWord board rack w@(word, (x, y), _) = x >= 0 && y >= 0 && y < length board && (a + length word) < length (board!!y) && foldl (\acc (c,t)->acc && characterFits t c) True (zip word wordLocation) where wordLocation = take (length word) (drop x (board!!y)) characterFits (PlacedTile letter) c = letter == c characterFits _ c = contains rack c wordScore :: [[Tile]] -> Word -> Int wordScore board (word, (x, y), _) = (letterScore * multiplier) + scrabbleBonus where letterScore = foldl (\acc (c,t)->acc + value t c) 0 (zip word wordLocation) wordLocation = take (length word) (drop x (board!!y)) value (LetterMultiplier mult) c = tileValue c * mult value (PlacedTile letter value) c = value value _ c = tileValue c multiplier = foldl (\acc t->acc * wordMultValue t) 1 wordLocation wordMultValue (WordMultiplier mult) = mult wordMultValue _ = 1 scrabbleBonus = if length (filter fromRack wordLocation) == 7 then 50 else 0 fromRack PlacedTile = False fromRack _ = True ``` A little longer than I'd like (especially the ton of where clauses on `wordScore`), but seems readable enough (at least to me). I took a few liberties with the data structures themselves - transliterating the C structures into Haskell doesn't really work. The board structure is a list of lists of tiles - a list of tiles forms a row, and a list of rows form a board. Words contain, in order: * A `[Char]` containing the exact tiles used (including blanks where a blank will be used instead of a letter). I assume this is prescreened for the no-two-blanks-next-to-each-other condition, though I suppose I could validate that as well. * An `(Int, Int)` tuple specifying the location of the word * An `Orientation` type constructed with either `Vertical` or `Horizontal`, specifying the orientation of the word. Additionally, the player's current rack of tiles is passed separately from the word being tested, because that makes more sense. I also assume a `tileValue` function which takes a character (including space) and returns the standard value of a tile depicting that character. ]
[Question] [ Write the shortest function you can that takes two [binary-coded decimal](http://en.wikipedia.org/wiki/Binary-coded_decimal) integers and a character indicating an arithmetic operation to perform and return the result. **Input Specification** You will be passed two 32-bit bit patterns representing unsigned BCD integers. In C or Java, for example, you would be passed an `int` (`unsigned`, if you prefer). The third argument to your function will be a single character denoting what operation to perform. If your language requires fixed return sizes, return a 32-bit result and ignore overflow. Your return value should also be encoded as a BCD. You should support `+`, `-`, `*`, `/`, and `%`. For subtraction, the first argument is the minuend and the second argument is the subtrahend. For division and modulo, the first argument is the quotient and the second is the divisor. **Example** ``` bcd(0x00000127, 0x00000003, '+') => 0x00000130 // NOT 0x0000012A ``` [Answer] # Python - 47 chars ``` bcd=lambda*a:"0x%08d"%eval("%x%s%x"%(a*2)[::2]) ``` tests ``` >>> print bcd(0x00000127, 0x00000003, '+') 0x00000130 >>> print bcd(0x00000127, 0x00000003, '*') 0x00000381 >>> print bcd(0x00000127, 0x00000003, '/') 0x00000042 >>> print bcd(0x00000127, 0x00000003, '-') 0x00000124 ``` [Answer] # Windows PowerShell, 54 ~~56~~ ~~69~~ ``` filter f($a,$b,$o){'0x'+("{0:x}$o{1:x}"-f+$a,+$b|iex)} ``` A bit cheating, I guess, but the output very well works as input again. I.e., PowerShell doesn't care whether it's a string or actual numeric literal there. Test: ``` > f 0x127 0x3 + 0x130 ``` History: * 2011-02-11 10:35 (69) – First attempt. * 2011-02-11 10:36 (56) – Going easy on the extra zeroes. * 2011-02-11 10:41 (54) – `filter` is shorter. [Answer] # JavaScript ES6, 61 bytes ``` (a,b,y)=>0|'0x'+~~eval([a,b].map(t=>+t.toString(16)).join(y)) ``` ]
[Question] [ [This prompt](https://codegolf.stackexchange.com/q/11735 "Convert to and from the factorial number system") asked you to convert back and forth to factoradic, but is very limited in scope (only decimal integers from 0 to 10!-1). Your task in this challenge is to reach just a bit further and fully implement conversion between factoradic and any other integer base. The factoradic system is extended to the reals by using reciprocals of factorials: ``` 43210.001234 (max value at each position, ==DEC119.991666666... and ==DEC14399/120) = 4 3 2 1 0 . 0 0 1 2 3 4 = 4*4! + 3*3! + 2*2! + 1*1! + 0*0! + 0*1/0! + 0*1/1! + 1*1/2! + 2*1/3! + 3*1/4! + 4*1/5! = 96 + 18 + 4 + 1 + 0 + 0 + 0 + 1/2 + 1/3 + 1/8 + 1/30 = 119+119/120 (last two here lines are in decimal; but same idea for any other base) ``` Because of how this is defined, any real factoradic number has at most [denominator+1] digits past the decimal. As you can see from the above example, which has significantly less than 121 digits after the decimal, the number of digits required is much less for numbers with lots of factors. To convert in the other direction, a real numer a/b -> factoradic, requires a bit more effort. There may be an easier way to do this, but I couldn't find anyone who has done this before so I had to work out the formula myself. If you come up with an easier formula feel free to add it. Since we're working in multiple bases here, clarification may be needed: a number prefixed by a 3-letter abbreviation is being represented in the base which that prefix [corresponds to](https://www.youtube.com/embed/7OEF3JD-jYo?start=1033 "if you like math and linguistics, you should watch the rest of the video and the whole channel as well; jan Misali is one of my favorite video essayists ^^"), I am using the notation of `baseN(#)` to mean `convert number # to base N`, and unspecified numbers are in decimal for convenience. ``` 14399/120 = 119 + 119/120 whole number portion: 119 / 4! = 4 r 23 23 / 3! = 3 r 5 5 / 2! = 2 r 1 1 / 1! = 1 r 0 0 / 0! = 0 r 0 fraction portion: 119/120 = 119/5! base5(DEC119) = 434 (43 4) base4(QUI43) = 113 (11 3) base3(QUA11) = 12 (1 2) base2(TRI1) = 1 (0 1) base1(BIN0) = 0 (0 0) base0(UNA0) = 0 (0 0) factorial: 43210.001234 bigger example: 123454321/11 = 11223120 + 1/11 whole number portion: 11223120 / 10! = 3 r 336720 336720 / 9! = 0 r 336720 336720 / 8! = 8 r 14160 14160 / 7! = 2 r 4080 4080 / 6! = 5 r 480 480 / 5! = 4 r 0 0 / 4! = 0 r 0 0 / 3! = 0 r 0 0 / 2! = 0 r 0 0 / 1! = 0 r 0 0 / 0! = 0 r 0 fraction portion: 1/11 = (1*(11-1)!)/11! = 3628800/11! base11(DEC3628800) = 205940A (205940 A) base10(ELE205940) = 329890 (32989 0) base9(DEC32989) = 50224 (5022 4) base8(NON5022) = 7121 (712 1) base7(OCT712) = 1223 (122 3) base6(SEP112) = 145 (14 5) base5(SEX14) = 20 (2 0) base4(QUI2) = 2 (0 2) base3(QUA0) = 0 (0 0) base2(TRI0) = 0 (0 0) base1(BIN0) = 0 (0 0) base0(UNA0) = 0 (0 0) factorial number: 30825400000.00002053140A converting number n0 from base b1 to b2: n0/b2 = n1 r d1 ( this only works ) n1/b2 = n2 r d2 ( if you actually ) n2/b2 = n3 r d3 ( do all the work ) ..until n<b2... ( in the 1st base ) n0 in b1 is n:...:d3:d2:d1 in b2, where a colon represents separation of digits if you can't do operations in other bases, first convert to base 10: digit1 * b1^(#digits) + digit2 * b1^(#digits-1) + ... + digitn * b1^0 = number_in_base10 ``` In words: For the whole number part you take the floor of the number, and divide it by the largest factorial less than it, using the floor of that answer as the next digit and the remainder as the next argument. For the fraction part, you multiply top and bottom until the denominator is a factorial n!, and convert the numerator to base n. Then remove the last digit and convert to the next lower base, using the full sequence of removed digits as the decimal. You may notice that the three middle digits (...0.00...) are always 0. You may either include or exclude them, but state in your answer which you are going to do, and be consistent (ie, either your input and output both always use the abbreviated form like !1.1=DEC3/2 or they both always use the complete form like !10.001=DEC3/2). Your code should take as input an input & output base, along with a real number represented in the input base, and then output that same real number in the output base. [(depricated req)](https://codegolf.stackexchange.com/q/267096/119818 "For numbers using only base 36 or less, numbers should be written with digits 0 to Z or 0 to z; numbers requiring larger bases must be written in your choice of sub-base with your choice of separator between digits.") Note that at some point you will need to select a sub-base to represent the digits of numbers in bases larger than you can represent with one character. The higher you can get without falling back onto a sub-base the happier you will make me personally. You may assume exactly one of either 'input' or 'output' must be in factoradic. Your output must take the same format as your input, ie your code should be able to back-convert anything it outputs. Numbers should be output in their simplest form (ie no leading/trailing 0's; no #/1's, 0/#'s, or #/0's; no -0; no #/-# or -#/-#; 6/4 -> 3/2; etc). [(depricated req)](https://codegolf.stackexchange.com/q/267096/119818 "In bases less than or equal to 36, number format should fit regex of either `^-?[a-z0-9]+(.|/)?[a-z0-9]*$` or `^-?[A-Z0-9]+(.|/)?[A-Z0-9]*$` (eg, `13f.4a` or `3G/2`). In higher number bases, number format should look something like `23 a3 42.3f 3e` or `< 42 > < 5 > / < 27 > < 34 >` or similar things; either the same something between each place value, the same something before/after each place value, or the same something around each place value. If a factorial number requires a digit which can take on 37 or more values, the full number must be in the second format.") In the spirit of flexible I/O you may use the default representation of higher-number bases for your language. Please state in your answer what format your numbers will use. You may define the format for specifying 'input and output bases' in any way you like, as long as it can represent any integer base >= 2 and specifies whether the input will be going into or out of factoradic. You may represent the non-factoradic number as either a/b (recommended) or as a real number n; if you use real number n as your input and output format you have to come up with a way to represent repeated digits like in DEC1/3, DEC1/7, or DEC1/28 (eg, digits after some delimiter repeat or something). The factoradic part must be one number, you may not separately convert the numerator and denominator and return a fraction. Examples: ``` radix: decimal-in number: 14399/120 output: 43210.001234 radix: decimal-out number: -43210.001234 output: -14399/120 radix: decimal-in number: 123454321/11 output: 30825400000.00002053140A radix: octal-in number: -11656 output: -6543200 radix: hex-out number: 42130100.001004 output: 4FD06/F radix: 100-in number(sub-base is hex): 1c|3|2f|62|35|5a|3/1|1e|4c|4a|24|50|0 output: 3110.0002223571381ccd radix: binary-in number: 0 output: 0 ``` [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in each language wins. You may assume input always follows your specified format, and it will always be a valid output as if your code had been given its own output and told to convert the other way. The logic of your code should work for any real number, converting between any positive integer base >=2 and factoradic in either direction. If your language has a built-in factoradic conversion function, you may include a secondary answer to show it off, but your first answer should not use it. Other integer base -> integer base conversion functions are fine. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~94~~ 93 bytes ``` ⁹1!ḍ@¥1#ḢR;!:¥ɗU×1¦%Ḣd¥\FḊU :1!>¥1#Ḣ’!€Ɗ;ƲUṪd¥\FḊ,ç ḅç/ ẈḶ!U×¥:@ƭ€FṀ$©$ḋ⁸S;®:g/$b A⁵ŀ⁹×1¦ṠFḢɗ ``` [Try it online!](https://tio.run/#%23y0rNyan8//9R405DxYc7eh0OLTVUfrhjUZC1otWhpSenhx6ebnhomSpQJOXQ0hi3hzu6QrmsDBXtoMoeNcxUfNS05liX9bFNoQ93roIp0jm8nOvhjtbDy/W5Hu7qeLhjmyLQoENLrRyOrQUqd3u4s0Hl0EqVhzu6HzXuCLY@tM4qXV8licvxUePWow1Ap4AtfbhzAdCoRSen////PzraUMdEx1jHUscyVgfINtIxiI39b2jw3xgA) [Test suite](https://tio.run/#%23VU7LSsNAFN3nKxqNuxsyk7R5FUq76QcoRSQGQRSh9AfcpYIgLa5cFEFBirEo1kVBmSi4mNJA/YvJj4w3YwSFy8w9D865/ePB4FTKYphRXbDLNk/ppmDT7aYe8nQ96S0nlD9sIXPE0/2uYKOeFlK9VdmK5Fovzp7zUTNf9ET29GuC5UwT7Hw5szTxfiHYm45BPA3b@RztXZElBn80BBsXQ7bT5C/hiWUcap1i@LpK8BRVKrI7jJquJ7LjHaDC7ytto1J2v8YaNFaJZWAmER9joGCvrnAx8gVWi2yej1AS2Se@OP3yS25qZqtWJLd7UkZRRKEODgQQxIC7DSSOgRIEkYIOyg1lsYEqC/1roOCi7JYC0r5iSYVshWy/zPAg8KGBPQQcleIQ8FzwMNgFn1StP6kmBbMOpgNmgPP/LCmdbw "Jelly – Try It Online") A full program taking three arguments. The first argument is a list of two lists of integers. This will be base digits for the numerator and denominator if converting to the factoradic representation. If converting from factoradic representation, it will be the factoradic digits before and after the point. The second argument will be an integer representing the base and the third will be the integer `3` for conversion to factoradic representation and `4` for conversion from factoradic representation. The program prints a list of lists of integers representing the results of the conversion. When converting from factoradic, the result will always be a fraction in its simplest form, with a denominator of 1 for integers. When converting to factoradic, a zero whole number portion is represented as an empty list, while after the point there will always be the two fixed zeros (even if there are no other digits). The TIO link runs a series of five variants of the test cases from the question, first converting to factoradic and then back again. Integer maths is used throughout, so should handle any size of input. ## Explanation ``` ⁹1!ḍ@¥1#ḢR;!:¥ɗU×1¦%Ḣd¥\FḊU # ‎⁡Helper link 1: takes numerator as left argument and denominator as right argument and returns the portion of the factoriadic representation after the point ⁹ # ‎⁢Right argument (denominator) 1!ḍ@¥1#Ḣ # ‎⁣Starting at 1, find the first integer where the factorial is divisible by the denominator (referred to as z below) ɗ # ‎⁤Following as a dyad with the original denominator as the right argument R # ‎⁢⁡- Range (1 to z) ; ¥ # ‎⁢⁢- Concatenated to: !: # ‎⁢⁣ - The result # ‎⁢⁣of dividing the factorial of z by the original denominator U # ‎⁢⁤Reverse the order of the list ×1¦% # ‎⁣⁡Multiply the first number (z!/denominator) by the result of numerator mod denominator Ḣd¥\ # ‎⁣⁢Reduce by popping the head and then taking divmod the next member of the list, collecting up intermediate results F # ‎⁣⁣Flatten Ḋ # ‎⁣⁤Remove the original starting point for the reduction U # ‎⁤⁡Reverse the order of the list ‎⁤⁢ :1!>¥1#Ḣ’!€Ɗ;ƲUṪd¥\FḊ,ç # ‎⁤⁣Helper link 2: takes numerator as left argument and denominator as right argument and returns the factoriadic representation : # ‎⁤⁤Integer divide numerator by denominator Ʋ # ‎⁢⁡⁡Following as a monad: 1!>¥1#Ḣ # ‎⁢⁡⁢- Starting with one, find the first integer that has a factorial greater than this Ɗ # ‎⁢⁡⁣- Following as a monad: ’ # ‎⁢⁡⁤ - Decrease by 1 !€ # ‎⁢⁢⁡ - Factorial of each integer from 1 to this ; # ‎⁢⁢⁢- Concatenate to floor(numerator/denominator) U # ‎⁢⁢⁣Reverse order of the list Ṫd¥\ # ‎⁢⁢⁤Reduce by popping the tail and then taking divmod the next member of the list, collecting up intermediate results F # ‎⁢⁣⁡Flatten Ḋ # ‎⁢⁣⁢Remove the original starting point for the reduction ,ç # ‎⁢⁣⁣Pair to the result of calling helper link 1 with the original arguments to this link ‎⁢⁣⁤ ḅç/ # ‎⁢⁤⁡Helper link 3: takes the numerator # ‎⁢⁤⁡and denominator as base digits as the left argument and a base as the right. Converts from that base, then calls helper link 2 with the numerator as the left argument and denominator as the right ‎⁢⁤⁢ ẈḶ!U×¥:@ƭ€FṀ$©$ḋ⁸S;®:g/$b # ‎⁢⁤⁣Helper link 4: takes a factoradic representation as the left argument and a base as the right. Returns the base digits of the numerator and denominator after converting from factoradic Ẉ # ‎⁢⁤⁤Lengths of list Ḷ # ‎⁣⁡⁡Range from # ‎⁣⁡⁡0..each of these lengths -1 ! # ‎⁣⁡⁢Factorial (vectorised) $ # ‎⁣⁡⁣Following as a monad: ƭ€FṀ$© # ‎⁣⁡⁤Use the following, first chain for the first argument, second for the second, in both cases using the max of the flattened list as the right argument (and also preserving this max in the register) U×¥ # ‎⁣⁢⁡- For the first argument, reverse the order and multiply by the max of the flattened list :@ # ‎⁣⁢⁢- For the second, divide the max of the flattened list by this ḋ⁸ # ‎⁣⁢⁣Dot product with the original left argument S # ‎⁣⁣⁡Sum ;® # ‎⁣⁣⁢Append the register :g/$ # ‎⁣⁣⁣Divide by the GCD of these (simplifying the fraction) b # ‎⁣⁣⁤Convert to the requested base ‎⁣⁤⁡ A⁵ŀ⁹×1¦ṠFḢɗ # ‎⁣⁤⁢Main link A # ‎⁣⁤⁣Absolute ⁵ŀ⁹ # ‎⁣⁤⁤Call the helper link indicated by argument 3 ×1¦ ɗ # ‎⁤⁡⁡Multiply the first part of the result by: ṠFḢ # ‎⁤⁡⁢The first sign of the original first argument, flattened 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ It is well-known that a [3D rotation](https://codegolf.stackexchange.com/questions/258001/3d-rotation-matrix-to-quaternion) can always be represented by a quaternion. It is less well-known that a *4D* rotation can always be represented by [*two* quaternions](https://en.wikipedia.org/wiki/Rotations_in_4-dimensional_Euclidean_space#Relation_to_quaternions), sending a point \$p=(a,b,c,d)^T\$ represented as the quaternion \$a+bi+cj+dk\$ to the point \$p'=xpy\$ for an appropriate choice of unit quaternions \$x,y\$. Let \$R\$ be a 4D rotation matrix. Then the corresponding \$x,y\$ can be obtained through [a direct algorithm of Perez-Gracia and Thomas](https://www.iri.upc.edu/people/thomas/papers/AGACSE2015a.pdf): * Compute \$S=\frac{R-A\_1RA\_1-A\_2RA\_2-A\_3RA\_3}4\$ where $$A\_1=\begin{bmatrix}0&0&0&-1\\0&0&-1&0\\0&1&0&0\\1&0&0&0\end{bmatrix}$$ $$A\_2=\begin{bmatrix}0&0&1&0\\0&0&0&-1\\-1&0&0&0\\0&1&0&0\end{bmatrix}$$ $$A\_3=\begin{bmatrix}0&-1&0&0\\1&0&0&0\\0&0&0&-1\\0&0&1&0\end{bmatrix}.$$ * Set \$Y=\frac S{(\det S)^{1/4}}\$ and \$X=RY^T\$. We have \$R=XY\$, where \$X\$ and \$Y\$ are the matrices of *left- and right-isoclinic rotations* respectively – very special matrices with at most four distinct magnitudes among their entries. * Finally \$x\$ and \$y\$ are the left-most columns of \$X\$ and \$Y\$. The pair \$(-x,-y)\$ also corresponds to \$R\$, analogous to the 3D case. \$S\$ above may have zero determinant, in which case one of the following alternative expressions should be used. These of course give different \$S\$ matrices, but the steps afterwards are unchanged: $$S=-\frac14(RA\_1+A\_1R+A\_3RA\_2-A\_2RA\_3)$$ $$S=-\frac14(RA\_2+A\_2R+A\_1RA\_3-A\_3RA\_1)$$ $$S=-\frac14(RA\_3+A\_3R+A\_2RA\_1-A\_1RA\_2)$$ ## Task Given \$R\$ – an orthogonal (to floating-point error) 4×4 real matrix with determinant 1 – output a corresponding \$(x,y)\$ pair to within \$10^{-6}\$ entrywise relative error. You may use any reasonable and consistent formats for input and output, and any correct formula for the calculation (including the one in the previous section). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases These are in the format \$R\to x\ y\$. The random cases were generated (and you can generate your own random cases) with [this program](https://ato.pxeger.com/run?1=rZK9TsMwEMfFmqc4MdnICU3SASGC2m6MjRhaoqqKiBssJXbquFLDq7B0gXcCHoWFcwJtQGVDinTn88_38c89vVSNeVBy9_ouykppA3JTVg2kNcjK0TKHCB1PpzJTpZfxVbopzBLjhDoOHqG7WWplUiOUJDIa0ksHxvgOKU8qXaYFqcUjj4hkklJwYMog7vIWQqZF7q01GVMHJhicwsheZCLNCdpa5JJ8nRWyJKYUSbHqvc64IRMKVzDAwjBJBgs4i8D1HdDcbLSEyfPGrNyL1w_b8Drj96qsMBHSd37XR1su8ZnPXPstaJKELMDjYLFAKuhTrsW-qYCFbMD8lgp_5nIPFOZBLrDUHCESg4ulR_EI66MXWC-wXmi9kMI5DC163ias19qQnu2NPW_VmGHOGHWbe7f7mcksucTuGcxbSzsJ3k5uVkojLJDAVLzhZMgy01Q8EtJQBu7R6JFgN3urEPtTHJSGhT-A_n0rnZXF_ootgwbnOPweByqNhUjsGVWI2hDs49S9PmWw7UWavY8LaWdb2tlwK3NOApvXbtrvJaX_Ua5TdLfr7Cc). ``` [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] -> [1.0, 0.0, 0.0, 0.0] [1.0, 0.0, 0.0, 0.0] [[-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]] -> [1.0, 0.0, 0.0, 0.0] [-1.0, 0.0, 0.0, 0.0] [[0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]] -> [1.0, 0.0, 0.0, 0.0] [0.0, 0.0, -1.0, 0.0] [[0, 0, 1, 0], [-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1]] -> [0.5, 0.5, 0.5, -0.5] [-0.5, -0.5, -0.5, -0.5] [[0, 0, 0, -1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]] -> [0, -0.7071067811865476, 0, -0.7071067811865476] [-0.7071067811865476, 0, 0.7071067811865476, 0] [[-0.6609058926555349, -0.30938449301078536, -0.6536493902436745, -0.2005669742797215], [-0.19737145221236216, 0.6931746532606626, 0.08266116424964398, -0.6882735952028355], [0.13703192282789176, -0.6502921800262064, 0.3686714537074865, -0.6499412988447983], [0.7109642487712476, 0.030169788832262925, -0.6557369638659809, -0.25224721015459695]] -> [0.560009784749661, 0.400037446835586, 0.272063553490942, 0.6725626401873549] [0.06637964559158858, 0.052592253308694104, 0.6737046111530368, 0.7341320688092741] [[0.6544007065477859, -0.5813716570041381, -0.411235410397809, -0.2542678684713569], [0.6193101080207767, 0.7694074810291105, -0.005562224168405557, -0.1563207596643309], [0.38183012824424395, -0.12606111825246455, 0.23940297340390976, 0.8837423628837136], [-0.2059622745505508, 0.23265364607854452, -0.8795116345009956, 0.36043183434001774]] -> [0.9455738853169363, -0.26286929698266226, 0.18881691258838904, -0.033733271870118764] [0.5350303732855687, 0.7836340999984829, 0.31251919145079116, 0.044630168680125246] ``` --- This question and its 3D version were inspired by [my answer to a MathsSE question](https://math.stackexchange.com/a/4641430/357390). I needed to wrestle with 4D rotations when rendering images like these for [this other MathsSE question which I have asked, and for which I have no answers](https://math.stackexchange.com/q/3822404/357390): ![](https://i.stack.imgur.com/0VmxY.jpg) [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 194 bytes ``` $R(0ää1~,0ä1~0,0 1áä,1 0ää)$A(0ä1á,0ää1~,1~0ää,0 1áä)$B(0 1~0ä,1 0ää,0ää1~,0ä1á)$C(RARA**-BRB**-CRC**-4÷RA*AR*+CRB**+BRC**-4÷~RB*BR*+ARC**+CRA**-4÷~RC*CR*+BRA**+ARB**-4÷~)äa¿×èäarr÷$Y(YRT*YT)µ0@ ``` with newlines for readability: ``` $R (0ää1~,0ä1~0,0 1áä,1 0ää)$A (0ä1á,0ää1~,1~0ää,0 1áä)$B (0 1~0ä,1 0ää,0ää1~,0ä1á)$C ( RARA**-BRB**-CRC**-4÷ RA*AR*+CRB**+BRC**-4÷~ RB*BR*+ARC**+CRA**-4÷~ RC*CR*+BRA**+ARB**-4÷~ ) äa¿×è äarr÷$Y (YRT*YT)µ0@ ``` input as matrix, output as pair of lists *For some test-cases \$(-x,-y)\$ is returned instead* [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=JFIoMOTkMX4sMOQxfjAsMCAx4eQsMSAw5OQpJEEoMOQx4Sww5OQxfiwxfjDk5CwwIDHh5CkkQigwIDF-MOQsMSAw5OQsMOTkMX4sMOQx4SkkQyhSQVJBKiotQlJCKiotQ1JDKiotNPdSQSpBUiorQ1JCKiorQlJDKiotNPd-UkIqQlIqK0FSQyoqK0NSQSoqLTT3flJDKkNSKitCUkEqKitBUkIqKi00934p5GG_1-jkYXJy9yRZKFlSVCpZVCm1MEA=&in=KDAgMCAxIDAsLTEgMCAwIDAsMCAxIDAgMCwwIDAgMCAtMSk) [version taking nested arrays as input](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=riRSKDDk5DF-LDDkMX4wLDAgMeHkLDEgMOTkKSRBKDDkMeEsMOTkMX4sMX4w5OQsMCAx4eQpJEIoMCAxfjDkLDEgMOTkLDDk5DF-LDDkMeEpJEMoUkFSQSoqLUJSQioqLUNSQyoqLTT3UkEqQVIqK0NSQioqK0JSQyoqLTT3flJCKkJSKitBUkMqKitDUkEqKi00935SQypDUiorQlJBKiorQVJCKiotNPd-KeRhv9fo5GFycvckWShZUlQqWVQptTBA&in=W1swLCAwLCAwLCAtMV0sIFsxLCAwLCAwLCAwXSwgWzAsIDEsIDAsIDBdLCBbMCwgMCwgMSwgMF1d) ## Explanation Straight forward implementation of the algorithm in the question: ``` ® ; convert (implicit) input to matrix (makes it easier to use the test cases) $R ; store input in R (0ää1~,0ä1~0,0 1áä,1 0ää)$A ; matrix A1 (0 1 -> literals, ä -> dup, ~ -> negate, á -> over) (0ä1á,0ää1~,1~0ää,0 1áä)$B ; matrix A2 (0 1~0ä,1 0ää,0ää1~,0ä1á)$C ; matrix A3 ( ; array containing the three possibilities for S RARA**-BRB**-CRC**-4÷ RA*AR*+CRB**+BRC**-4÷~ RB*BR*+ARC**+CRA**-4÷~ RC*CR*+BRA**+ARB**-4÷~ ) ; get all elements of the array with non-zero determinant: äa ; vector of determinants of the elements ¿ ; is nonzero (vectorized) × ; repeat elements of array that many times, picks elements satisfying condition è ; get the first element of that array "S" äarr÷$Y ; compute Y ( S/ sqrt(sqrt(det( S )))) (YRT*YT) ; pair containing X^T=Y*R^T and Y^T µ0@ ; replace elements with their first row (get first column of X and Y) ``` ]
[Question] [ ## Background With the success of [Simple Boolean Algebra Calculator](https://codegolf.stackexchange.com/questions/254514/simple-boolean-algebra-calculator), I present a more difficult problem. Boolean Algebra concerns representing values with letters and simplifying expressions. The following is a chart for the standard notation used: [![Notation](https://i.stack.imgur.com/kWE7v.png)](https://i.stack.imgur.com/kWE7v.png) Above is what actual boolean algebra looks like. For the purposes of this code golf, this is not the exact syntax that will be used. ## Your Task Given a short boolean expression, return the solution to the expression. There will be at most two values and one function involved in the calculator. The values may be any of 0, 1, or a capital letter(s). The functions may be /, +, or . Any of the following may be an input: (values are demonstrated with X and Y in these examples.) **One function, One value** * There is only one possibility for this, which is /X. Return NOT X. If X is a variable, return /X, otherwise compute and output. This is the only scenario where /, the backslash, will be used. **Two values** * There is only one possibility for this, which is XY. Return X AND Y. If X and Y are different variables, return XY, otherwise compute and output. This is the only scenario where two values are next to each other. **One value, One function, Another value** * If you've done [Simple Boolean Algebra Calculator](https://codegolf.stackexchange.com/questions/254514/simple-boolean-algebra-calculator), this is exactly the same except that it now must be able to output two variable calculations. * Return the value for X (function) Y. If X and Y are different variables, output X (function) Y. * (function), the second character in this scenario, will be either "+" or ".". If "+", treat as OR. If ".", treat as AND. *Input: Either two characters or three characters.* *Output: Either one character, two characters, or three characters.* ## Explained Examples ``` Input => Output /0 => 1 /1 => 0 /P => /P ``` These expressions output the NOT value for the input. /P outputs /P because it cannot be simplified further. ``` Input => Output 0Q => 0 ``` 0Q evaluates to 0 because 0 AND Q will always be 0, regardless of what value Q takes. ``` Input => Output Z1 => Z ``` Z1 evaluates to Z because the output for Z AND 1 depends entirely on the value of Z. ``` Input => Output AH => AH (or A.H) ``` AH evaluates to AH because it cannot be simplified further. A.H is also a valid output. ``` Input => Output A+1 => 1 ``` A+1 evaluates to 1 because the OR statement is overridden by 1. That is, no matter what value A takes, the presence of 1 means that the statement will always evaluate to 1. ``` Input => Output B+B => B ``` B+B evaluates to B because the OR statement is dependent on either Bs being true. If both Bs are false, then the output would also be false. So, the statement returns B since whatever value B takes, the output would return that. ``` Input => Output W+L => W+L ``` W+L evaluates to W+L because it cannot be simplified further. ``` Input => Output 0.H => 0 ``` 0.H evaluates to 0 because the AND statement is overridden by 0. That is, no matter what value H takes, the presence of 0 means that the statement will always evaluate to 0. ``` Input => Output 1.1 => 1 ``` 1.1 evaluates 1 because the AND statement requires both inputs to be 1, and since they are both 1, 1 is returned. ``` Input => Output G.L => G.L ``` G.L evaluates to G.L because it cannot be simplified further. ## Examples/Test cases ``` Input => Output /0 => 1 /1 => 0 /P => /P 00 => 0 11 => 1 0Q => 0 Z1 => Z NN => N AH => AH (or A.H) A+1 => 1 B+B => B R+0 => R 1+1 => 1 0+0 => 0 A+B => A+B Y+Z => Y+Z 0.0 => 0 Q.Q => Q 0.A => 0 1.C => C 1.1 => 1 R.S => R.S N.W => N.W ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. Good luck. [Answer] # JavaScript (ES6), 75 bytes ``` s=>([x,o,y]=s,y||(y=o,o=-1),x<'0')?1/y?y^1:s:x+1|y+1|x==y?~x&y!=0^o+1?x:y:s ``` [Try it online!](https://tio.run/##TUzLTsMwELzzFYsP2FZcJ746bC2Q@IoolaLQFFDVreoKeUXKrwcbRNXD7Kzm9TF8DnE8vR/PqwO9bpcJl4hr1SVDhnuMhudZMZIhXDlt0qNspA6u5sAb56NPlZs5IyFy@E4PfI/NhioXkmcfl7YTVhgQBVU5tejtRKeXYXxTBLiGrzuA8iHIWkKATogePHTWWtG4p2fR62shlcKNczX4fwkgAkKCCiiD219ppEOk/dbuaadilmWOyMyTilqXyOWPbnNZuOh2@QE "JavaScript (Node.js) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 62 bytes ``` 0\+|\+0 /0|1\+.|.\+1 1 /1|.*0.* 0 1\.?(.)|(.)(\.?1|.?\2) $1$2 ``` [Try it online!](https://tio.run/##DYyhDsMwEEO5v6Og7UmXu/5AlY4URUsHplVHBgZGBqbB/Htm8GRbtvx9/d6fZ@8W0kIMSNY8RJuGOBzJm86mMwweuo46NTLSslhjmTD4sPSejFOkK4xDh1WcjlKQd2QebbLh4L3TGzUzP@SEqaFqpWa4Xojj0BuK3v8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` 0\+|\+0 ``` `0+X` and `X+0` become `X`. ``` /0|1\+.|.\+1 1 ``` `/0`, `1+X` and `X+1` become `1`. ``` /1|.*0.* 0 ``` `/1`, `0X`, `0.X`, `X0` and `X.0` become `0`. (This is tested after `/0` so that it doesn't erroneously match the `X0` rule and after `0+X` and `X+0` so that a simpler regex can be used that would otherwise erroneously match them.) ``` 1\.?(.)|(.)(\.?1|.?\2) $1$2 ``` `1X`, `1.X`, `X1`, `X.1`, `XX`, `X.X` and `X+X` become `X`. (This is tested after `/1` so that it doesn't erroneously match the `X1` rule.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ¿№θ/¿‹⌈θAI¬Σθθ¿⁼²LΦα№θιθFI№θ+¿№θιι⌈θ ``` [Try it online!](https://tio.run/##XY49C8IwEIb/ypHpghXRtZMUnaoIbm5HSW0gbciX@O9jotGqt9099350A9lOk4pR9oCNDpNHUwFbMc4hn1rhHB7oLscwouEJbTM6WZk@G3Iej9rj@QnT1CCUEwWb95qNdiaQcripoBXT1Q@4l8oLi1TBJ1ZmC/6v7rWFV9Tcb8F4KfgtLkr5W2Nuz@sYL@u4vKkH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ¿№θ/ ``` If the input contains a `/`, then: ``` ¿‹⌈θA ``` If the input does not contain a letter, then... ``` I¬Σθ ``` ... output the complement of the digit that it contains, otherwise... ``` θ ``` ... output the input. ``` ¿⁼²LΦα№θι ``` Otherwise, if the input contains two letters, then... ``` θ ``` ... output the input, otherwise... ``` FI№θ+¿№θιι⌈θ ``` ... solve the problem using the method from [Simple Boolean Algebra Calculator](https://codegolf.stackexchange.com/q/254514/). ]
[Question] [ ## Introduction Large meetings waste working time. Our aim is to split a large meeting into a number of smaller meetings, so the average number topics that a person discusses is minimized but every person has to be in every meeting they are interested in. ## Input Given is a function from a set of topics \$T\$ to a set of persons \$P\$ that are interested in this topic $$f:T \rightarrow 2^P$$ and maximum partition size \$m\$. This is encoded as an array of arrays, where element \$f(i)\$ contains the topics of person \$i\$. ## Test Case ``` m = 3 f = [ [9,7], [3,7,6,4], [3,1,2], [7,5,4,2], [6,2,8,1,4], [3,7,2,9,8], [4,3,2], [3,4,6], [1,9,5,3], [6,4,1,2], [9,7,3,1], [1,7,4], [5,1,7,2], [5,2,7], [4,2,6,9], [6,4,1], [6,5,9,8], [9,1], [9,1,5,6], [1,2,4,8,7] ] ``` ## Output Find a partition of \$T\$ (a split into subsets that are disjoint and that cover the whole set) into $$X = {T\_1, T\_2, \ldots, T\_n}$$ where \$n\le m\$, so that the following term is minimized: $$r = \sum\_{T' \in X}{(|(\bigcup\_{t \in T'} f(t))|\times |T'|)} $$ To help understand \$r\$, if each topic takes an hour to discuss, then \$r\$ is the total amount of person hours required for the meetings. If there are multiple partition sizes with the same \$r\$, \$n\$ should be minimized as well. The output should contain the partition \$X\$ as a two-dimensional array, such as: $$X = [[0,1,2,3],[4,5,6],[7,8,9]] $$ ## Winning Condition I am looking for the fastest algorithm that finds the absolute minimum \$r\$ and \$n\$. If that is not possible in polynomial time, then I am also looking for an polynomial algorithm that has the lowest upper bound on \$r\$ in relation to the absolute minimum \$r\$ (e.g. double). [Answer] # R with lpSolve Turn the problem into an integer linear programming problem with \$2^t\$ variables and \$t+1\$ constraints, where \$t\$ is the number of topics. The cost function is modified by multiplying it with \$m\$ and adding the size of the partition. This makes the size of the partition a secondary optimization goal. ``` require("lpSolve") decode <- function(n) { res <- c() i <- 1 while (n>0){ if (n %% 2 == 1) res <- c(res,i) i <- i+1 n <- n %/% 2 } res } opt <- function(m,p) { nr_pers <- length(p) nr_topics <- max(unlist(p)) x <- array(0,c(nr_topics,nr_pers)) for (i in 1:nr_pers) for (j in 1:length(p[[i]])) x[p[[i]][[j]],i] <- 1 l <- array(0,c(2^nr_topics,nr_pers)) cb <- rep(0,2^nr_topics) w <- rep(1,2^nr_topics) mt <- matrix(0,nr_topics+1,2^nr_topics) mt[nr_topics+1,1] <- 1 len <- 1 for (i in 1:nr_topics) { for(j in 1:len) { j1 <- len+j l[j1,] <- l[j,]+x[i,] cb[j1] <- cb[j] + 1 w[j1] <- m*sum(l[j1,] != 0)*cb[j1]+1 mt[,j1] <- mt[,j] mt[nr_topics+1-i,j1] <- 1 } len <- 2*len } dir <- c(rep("=",nr_topics),"<=") rhs <- c(rep(1,nr_topics),m) sol <- lp("min",w,mt,dir,rhs,all.bin=TRUE)$solution res <- list() j <- 1 for (i in 1:length(sol)) if (sol[i]==1) { res[[j]] <- decode(i-1) j <- j+1 } res } # test case f <- list( c(9,7), c(3,7,6,4), c(3,1,2), c(7,5,4,2), c(6,2,8,1,4), c(3,7,2,9,8), c(4,3,2), c(3,4,6), c(1,9,5,3), c(6,4,1,2), c(9,7,3,1), c(1,7,4), c(5,1,7,2), c(5,2,7), c(4,2,6,9), c(6,4,1), c(6,5,9,8), c(9,1), c(9,1,5,6), c(1,2,4,8,7)) ``` On debian, this needs the package `r-cran-lpsolve`. The code assumes that the topics start with 1 and that each topic number up to the maximum is used. Input and output is as list of vectors, which is not too nice. The test case example is defined in the code, but the list can of course also be entered directly. To use it, start `R` and then `source` the code file and use the function like this: ``` > source("opt.r") Loading required package: lpSolve > opt(3,f) [[1]] [1] 1 2 3 4 [[2]] [1] 6 8 [[3]] [1] 5 7 9 > ``` So `[[1,2,3,4],[6,8],[5,7,9]]` is an optimal partition for the test case. ]
[Question] [ Each March in the United States, the NCAA holds a 68-team tournament for both men's and women's college basketball. Here's what the bracket looks like: [![Bracket from 2016 - the basic format is the same each year](https://i.stack.imgur.com/lHyVA.jpg)](https://i.stack.imgur.com/lHyVA.jpg) There are four regions, each with 16 teams seeded from 1-16. Each region is seeded the same way, and across the four regions, the same matchups occur between seeds. For example, in the first round, #1 plays #16 and #8 plays #9, then the winners of those games play in the second round. So, possible options for the second round matchup are #1 vs #8, #1 vs #9, #16 vs #8, and #16 vs #9. Teams with the same seed can only meet in two ways: the first is in the semifinals (round 5), where the champion of each of the four regions plays another regional champion. The second has to do with a wrinkle in the tournament. There are also 4 "play-in" games, where two teams with the same seed play each other to enter the "true" game in the round of 64 teams. As you can see in the bracket, this only happens for seeds 11 and 16, so those seeds can play another team in the same seed in the play-in games (round 0). **The Challenge** Given two seeds from 1 to 16, inclusive, in any standard format, output the number of the earliest round a matchup between two teams with those integers as seeds could occur in the NCAA basketball tournament. **Test Cases** ``` Input Output 1,16 1 1,8 2 1,9 2 9,16 2 3,11 2 3,14 1 1,2 4 5,5 5 11,11 0 16,16 0 15,16 4 3,4 4 6,7 3 6,10 3 6,11 1 10,11 3 1,6 4 1,11 4 4,5 2 4,6 4 4,7 4 4,8 3 4,9 3 5,8 3 5,9 3 2,7 2 ``` This is code-golf, so the submission with the fewest bytes wins. [Answer] # Mathematica, 79 bytes ``` o={r=1,1} Which[#==11o||#==16o,0,Tr@#==(c=32/2^r+1),r,0<r++,#0[Min[#,c-#]&/@#]]& ``` The second line defines a pure function taking a pair of numbers as input and returning the appropriate nonnegative integer. Inside the `Which` (which is an "if-then-else" construct): `#==11o||#==16o,0,` deals with the play-in special cases; `Tr@#==(c=32/2^r+1),r,` checks whether the sum of the two team seeds is equal to the magic number that means they could be matched up in round `r`; and `0<r++,#0[Min[#,c-#]&/@#]` is the "else" clause (since `0<r++` will always be true here) which recursively calls the function on `Min[#,c-#]&/@#`, which replaces any lower seed with the seed of the higher-ranked team it would have beaten to get to the next round. ]
[Question] [ **This question already has answers here**: [Short Deadfish Numbers](/questions/40124/short-deadfish-numbers) (15 answers) Closed 7 years ago. # Goal: Given any natural number `k` such that `k<256`, produce an deadfish program that gives the smallest solution possible. # Background: Deadfish is a joke esoteric programming language. It has a single unsigned byte of memory, called the `accumulator`, initialized at 0. There are four commands which form a string. * `i` = `accumulator += 1` * `d` = `accumulator -= 1` * `s` = `accumulator = accumulator * accumulator` * `o` = `print(accumulator)` For example, the string `iiisis` would produce 100, as this would be the memory after each command: * i -> 1 * i -> 2 * i -> 3 * s -> 9 * i -> 10 * s -> 100 # Specification: * Read a number through any reasonable means (from a file, STDIO, or a function argument), and output an optimal string of commands producing that number. * A solution is considered optimal if there are no solutions that use fewer commands. * Output through any reasonable means (to a file, STDIO, or a return value). * The accumulator may not exceed 256. # Examples: ``` 0 -> (Empty string, nothing, or error) 1 -> i 4 -> iis 8 -> iiisd 35 -> iisiisd 150 -> iiisiiisiiiiii 256 -> (Empty string, nothing, or error) ``` [Answer] # Mathematica, 164 bytes ``` a=#~Mod~256&;Switch[#2,#+1,"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1/.256->#,#-1,If[#<16,#^2,#]}]&)/@0~Range~255],0,#],2,1]& ``` Anonymous function. Takes a number as input and returns a list of instructions as output. Previous solution before requirements were changed: ### Mathematica, 148 bytes ``` a=#~Mod~256&;Switch[#2,a[#+1],"i",a[#-1],"d",_,"s"]&@@@Partition[FindShortestPath[Graph[Join@@(Thread[#->a@{#+1,#-1,#^2}]&)/@0~Range~255],0,#],2,1]& ``` Anonymous function. Takes a number as input and returns a list of instructions as output. First, the edges for a graph of value transitions are generated. Then, `FindShortestPath` is used to find the shortest path from 0 to the requested value. Finally, pairs of values are taken and compared to find the instructions used. All outputs of this program can be found [here](http://pastebin.com/Jj0eiftf). ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/103216/edit). Closed 7 years ago. [Improve this question](/posts/103216/edit) Create a program that can create a randomly arranged maze (The path of the maze changes each time) with exactly 1 exit and one enterance and a minimum size of 8x4 and max size of 32x32, with the exact dimensions x and y as input Submissions can be original code, but to score higher add onto a submission with another language (polyglot) Writing code in labyrinth gives brownie points as suggested by Mistah Figgins :) --- Example Case (8x4): ``` __ _____ | | | __ | |_____| | | | _| | |____| | ``` Non-Examples: ``` __ |_| Too Small __ _____ | | | __ | |___|_| | | | _| | |____| | No Solution ``` --- Apologies if challenge is confusing or cumbersome, this is my first PCG and after reading up on the meta I still had some blurry regions. [Answer] ## C and C++, 603 bytes ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define Y x+1+rand()%(y/2-1)*2 #define C(n,i) if(j n&&M[i])c[b++]=i; typedef int I;I m;I main(I argc, char**argv){srand(time(0));I x=atoi(argv[1]),y=atoi(argv[2]),*L=(I*)malloc(2*x*y*sizeof(I)),j=Y;char*M=(char*)malloc(x*y);memset(M,1,x*y);M[j]=0;for(;;){I b=0,c[4];C(%x>1,j-2)C(>2*x,j-2*x)C(%x<x-3,j+2)C(/x<y-3,j+2*x)if(b){I z=c[rand()%b];M[z]=M[z+j>>1]=0;L[m++]=j=z;}else if(m)j=L[--m];else break;}for(;;){I j=Y;if(!M[j]){M[j-x]=0;break;}}for(j=0;j<y;++j){for(m=0;m<x;++m)putchar(M[j*x+m]?88:32);puts("");}free(M);free(L);} ``` Edit: this was written before the prompt was revised. This program just outputs X for the walls and places only one door. ]
[Question] [ > > [Jellyfish](https://github.com/iatorm/jellyfish) is a two-dimensional esoteric programming language inspired by J and written in Python 3. It was inspired by a challenge on PPCG. The name was suggested in PPCG chat as a combination of Jelly, a golfing language inspired by J, and Fish, a two-dimensional esoteric language. > > > What general tips do you have for golfing in Jellyfish? I'm looking for ideas which can be applied to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") problems and which are also at least somewhat specific to Jellyfish. [Answer] # Use functions before consumed by operators When calculating the [Catalan number](https://codegolf.stackexchange.com/q/66127/48934), I used this trick in [my Jellyfish answer](https://codegolf.stackexchange.com/a/88818/48934): ``` p %C+ & >+i ``` The `>` function is taking `+` as argument, while the `&` takes the same `+` as functional argument. As a result, the `+` that the `>` gets is unary, while the `&` makes `+` binary to be used by `C`. [Answer] # Remove unnecessary whitespaces In my Jellyfish answer to [this question](https://codegolf.stackexchange.com/q/88732/48934), I golfed my program from [41 bytes](https://codegolf.stackexchange.com/revisions/88780/3) down to [29 bytes](https://codegolf.stackexchange.com/revisions/88780/5) just by finding alternative methods of placing the functions and operators so as to minimize the number of spaces used. 41-byte version: ``` p n + + `1 /+&* `/* r&;>i 1 ``` 29-byte version: ``` p n + +`/ `1* / + &*r&;>i ``` Use the fact that literals cannot take argument to pack things together. For example, in my 29-byte version, I have a `1` above a `*` which does not affect the performance of `*`. The major goal when I was golfing from 41 bytes to 29 bytes is to minimize the whitespaces used on the second line, meaning to minimize the horizontal span of the remaining lines. Also, in the 41-byte version, I had two occurrences of `1`, and in my 29-byte version I combined them. ]
[Question] [ # King of the Torus! Your job is to conquer the torus, but wait, there are multiple other players banded together in teams facing you! You will need to use your wit's to conquer the torus. There are three teams: red, blue and green. Teams are self-assigned arbitrarily. If the teams are even you may join the team of your choice, otherwise you must join the smallest team(s). The map is a torus presented as a square of length 640 by 640. Lets take a look at a sample map ``` OOOOOOOOOOOOOOOOOOOOOOOOOOO RRRRRRRRRRRRRRRRRRRRRRRRRRR OOOOOOOOOOOOOOOOOOOOOOOOOOO GGGGGOOOOOOOOBBBBBBBBBBBBBB GGGGGGGGGGGGGGGGGGGGGOOOOOG OOOOOOOOOOOOOOOOOOOOOOOOOGG RRRRRRRRRRRRRRRRRRRRRRRRRRR OOOOOOOOOOOOOOOOOOOOOOOOOOO ``` as you can see, the red team has built a wall to safely conquer the territory between the two walls. Blue, and green will have to fight it out. This scaled down version of the map is representative of the larger one. Red would likely win this battle as they would finish the game (once the board is filled or a large number of turns have passed) with the most territory Now each bot has a location (known only to you). You can only move to an adjacent square if it is owned by your team. At the start of your game, you start on a single square of your teams color. Your goal is to expand this splotch by conquering other land. At any turn you can choose to move to any adjacent color of your own territory or you may alternatively choose to attack an adjacent territory. If the attacked square is unowned it will be captured. ## Java API You will override the Bot class to return a single number (0-3) for attempted moves and 4-7 for an attempted attack. Your bot's should only take 10 milliseconds to move, but the rule will not be formally enforced unless it becomes a problem. Problematic, malicous, or otherwise obnoxious bots are clearly not in the spirit of this competition and will be disqualified with an immediate low quality flag. Otherwise bots acting in good faith, but otherwise buggy will be given time as needed for bug repairs. Method summary ``` public abstract class Bot{ public final int team;// 0 = red 1 = green 2 = blue public Bot(int inTeam){team=inTeam}//be sure to call super(inTeam); public int move(){};//you will override this } Methods available Color Bot.getColor(int x,int y){}//returns a Color object with rgb values where the r g or b value of the team owning it will be 100. getX(); returns the X position of your bot getY(); returns the y position of your bot Bot.getMap();//returns the array representing the map. I.e Bot.getMap[i][j] returns a color with r g b values representing each teams stake in that spot. //only one r g b value will be greater than 0 as only one team can hold a spot Do not abuse the map access. Giving direct access (as opposed to a copy) is to speed up access to the map. Abusing it will result in disqualification! ``` A wrapper program may be made available as long as it still allows the program to run smoothly. ## How to play: Step one: Post your bot here as an answer and ensure it follows the specs. Step Two Head over to this [gitHub repository](https://github.com/rjhunjhunwala/Conquer-The-Torus) fork it and add your bot's file in as well as add these two lines after '//init bots' Bot.run. Be sure to choose the team with the least members if applicable. ``` bots.add(new UniqueBotNameHere(team=choiceOfTeam,x=getRandom(0,map.length),y=getRandom(0,map[0].length))); map[x][y].colors[team]=255; ``` Step Three: Make a pull request. I will accept your pull request and your bot will automagically be added to the tournament. Step Four: Download the source files and copy them into the proper package. Run the build and enjoy watching the bots --- Good luck and don't let your team down! Team's will be made even by my sample bots. I may also move around teams to ensure equal members. --- ### Interesting trivia Modifying the Half Hearted flood filling sample bot, gives an interesting map generator. [![Reminds of the Mediterranean sea!](https://i.stack.imgur.com/uexYw.png)](https://i.stack.imgur.com/uexYw.png) [Answer] # Waller He builds a wall, but he can't make the other team pay for it! He makes a nice low level bot to help debug your submissions. ``` public class Trump extends Bot{ int moves; int direction; public Trump(int team, int inX, int inY) { super(team, inX, inY); direction = Bot.getRandom(0, 4); } @Override public int move() { int ret = direction; switch(++moves%4){ case 0: ret = direction+4; break; case 1: ret = direction; break; case 2: ret = direction + 1; break; case 3: ret = direction +3; } return ret; } } ``` [Answer] # Half Hearted Flood Filler Another low level bot. He tries to flood fill the map, but he only puts in 50% effort! I will enter another more competitve bot, but this guy is just to demonstrate one possible approach. ``` /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package toroidal.domination; import java.awt.Color; import java.util.Stack; /** * * @author rohan */ public class HalfHeartedFloodFillBot extends Bot{ public static class Node{ public final int x,y; public Node(int x, int y){ this.x=x;this.y=y; } } private Stack<Integer> nodes = new Stack<>(); public HalfHeartedFloodFillBot(int team, int inX, int inY) { super(team, inX, inY); } @Override public int move() { int x,y; for(int i = 0;i<4;i++){ if(isEmpty(Bot.getColorAtSpot(x=getX()+(int) Math.cos(i*Math.PI/2),y= getY()+(int) Math.sin(i*Math.PI/2)))){ nodes.add((i+2)%4); return i+4; } } //no empty spots found try to backtrack or just do stuff! return nodes.isEmpty()?Bot.getRandom(0,2)==0?Bot.getRandom(0, 2)==0?0:1:Bot.getRandom(0, 2)==0?2:3:nodes.pop(); } boolean isEmpty(Color c){ int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); return r == 0 && b == 0&& g == 0; } } ``` [Answer] # SpiralBot This bot will go until he hits something that is not neutral, then will turn left, making a spiral in the free space. ``` public class SpiralBot extends Bot{ int d; public SpiralBot (int team, int inX, int inY) { super(team, inX, inY); d = 0; } int dx(int move){ return (int) Math.cos(move * Math.PI / 2); } int dy(int move){ return (int) Math.sin(move * Math.PI / 2); } @Override public int move() { int x = getX(); int y = getY(); Color[]c = new Color[4]; for(int i = 0;i<4;i++) c[i] = Bot.getColor(x+dx(i), y+dy(i)); if(c[d].equals(Color.black)) return d; if(c[(d+1)%4].equals(Color.black)) return d = (d+1)%4; if(c[(d+3)%4].equals(Color.black)) return d = (d+3)%4; return d + 2; } } ``` I have no account on GitHub, so if someone could push this for me that would be good. Thank you. ]
[Question] [ Taylor series are a very useful tool in calculating values of analytic functions that cannot be expressed in terms of elementary functions, using only information about that function at a single point. In this challenge, you won't be actually doing any math with them, but merely making string representations of taylor series of functions with periodic derivatives. # Specs You will takes a input three things: 1. A cycle of the derivatives of the function, including the original function as a list of strings, e.g. `["sin(x)", "cos(x)", "-sin(x)", "-cos(x)"]`. 2. A number `a`, the point around which to center the approximation. 3. A positive integer `n`, the number of terms of the series to output. The general form for the nth term of a taylor series is: ``` f^(n)(a)/n!*(x-a)^n ``` where `f^(n)` is the nth derivative of `f`. Here is the taylor series of `f` in a better formatted image from wikipedia: ![](https://upload.wikimedia.org/math/c/3/a/c3a379aaf2b04999084373279ed2da10.png). The above example with `sin(x)`, and `a` of 1, and `n` of 6, would have an output of: ``` sin(1) + cos(1)*(x-1) - sin(1)/2*(x-1)^2 - cos(1)/6*(x-1)^3 + sin(1)/24*(x-1)^4 + cos(1)/120*(x-1)^5 ``` You can do the whitespace want. However, you have to replace `+ -` and `- -` with `-` and `+` respectively. Also, if the series is a maclaurin series, and `a` is `0`, you cannot have `(x-0)`. `(x)` and just `x` is fine, but not `(x-0)`. Niether can you have `^0` nor `^1` nor `/1` . Additionally, you must expand out the factorials in the denominators. Multiplication by juxtaposition is not allowed. # Test cases ``` ["e^x"], 0, 4 -> e^0 + e^0*x + e^0*x^2/2 + e^0*x^3/6 ["sin(x)", "cos(x)", "-sin(x)", "-cos(x)"], 1, 6 -> sin(1) + cos(1)*(x-1) - sin(1)/2*(x-1)^2 - cos(1)/6*(x-1)^3 + sin(1)/24*(x-1)^4 + cos(1)/120*(x-1)^5 ["e^(i*x)", "i * e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"], 0, 7 -> e^(i*0) + i*e^(i*0)*x - e^(i*0)*x^2/2 - i*e^(i*0)*x^3/6 + e^(i*0)*x^4/24 + i*e^(i*0)*x^5/120 - e^(i*0)*x^6/720 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] ## JavaScript (ES6), 183 bytes ``` (c,a,n)=>[...Array(n)].map((_,i)=>(s=c[i%c.length].replace(/x/g,a),i?s=s.replace(/^-?/,c=>c?` - `:` + `)+(a>0?`*(x-${a})`:a<0?`*(x+${-a})`:`*x`):s,i>1?s+`^${i}/${f*=i}`:s),f=1).join`` ``` Lots of tedious string manipulation. Explanation: ``` (c,a,n)=> Parameters [...Array(n)].map((_,i)=>( Loop i from 0 to n-1 s=c[i%c.length] Get the right element from the cycle .replace(/x/g,a), Substitute a in for x i? If i > 0 s=s.replace(/^-?/,c=>c?` - `:` + `) Turn the sign into an operator +(a>0?`*(x-${a})` If a > 0 then * (x - a) :a<0?`*(x+${-a})` If a < 0 then * (x + -a) :`*x`) If a == 0 then * x :s, No change if i < 1 i>1? If i > 1 s+`^${i}/${f*=i}` Append ^ i / i! :s), No change if i < 2 f=1 0! == 1 ).join`` Join all the results together ``` 170 bytes if you remove all the whitespace: ``` (c,a,n)=>[...Array(n)].map((_,i)=>(s=c[i%c.length].replace(/x/g,a),i?s=(s[0]=='-'?'':'+')+s+(a>0?`*(x-${a})`:a<0?`*(x+${-a})`:`*x`):s,i>1?s+`^${i}/${f*=i}`:s),f=1).join`` ``` [Answer] # Python 2, 181 bytes ``` D,a,N=input() D=["+"*(d[0]!="-")+d.replace("x",`a`)for d in D] x=a and"*(x-%s)"%a or"*x" r=D[0][1:]+(D[1]+x)*(N>1) n=f=2 while n<N:r+=D[n%len(D)]+"/"+`f`+x+"^"+`n`;n+=1;f*=n print r ``` [Answer] # Python 3.5, 308 299 bytes: ``` def g(f,a,n,L=len,S=str):import math,re;A=S(a);print('+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x')) ``` This *always* outputs in the order according to the equation `f^(n)(a)/n!*(x-a)^n`. For instance, if the expected output for one of the terms is `e^0*x^2/2`, it instead outputs `e^0/2*x^2`. However, they are both basically the same answer, so I hope this is okay. [Confirmed by OP](https://codegolf.stackexchange.com/questions/78424/taylor-series-of-a-function-with-periodic-derivatives/78682#comment192711_78424) that this is okay. This works perfectly as I have had no issues with it. I will shorten this over time wherever I can. **Note:** In the output, all `(x-0)` are replaced with `(x)`. [Try it online! (Ideone)](http://ideone.com/TuPBut) (Accepts input on 3 lines, where the first line is the input list, `f`, the second line is `a`, and the third line is `n`) # Explanation For the purposes of this explanation, assume the function is executed with the values `"e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7`. That being said, basically, what's going on in the main part, step-by-step, is: 1. `'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)]))` A list is created from each item pair in a zip object containing the input list, `f`, with `n` number of items, and another list which contains each term in the sequence *except* the items in `f`. In this second list, `*+a` is added, followed by a `/`+ `n!` for each value, `n`, in the range `n`, and finally, a lone `*` followed by `(x-a)^n`. After all this is done, for each item pair in this zip object, `t` corresponding to each object in `f` and `g` corresponding to each value in the second list, each `'x'` in `t` is replaced with `a`, and every `g` goes through a regular expression substitution, namely `(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)`, in which every `(x-a)^0`, `/1`,`*1`,`^1`, and `*0` is matched and replaced with `''` as long as each of those are *not* followed by any more integers. After all this substitution is done, each `t` and `g` are concatenated together, and each term created using this method is joined with `+`s and returned. For this particular case in which `"e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7` is the input, this part would return: ``` e^(i*0)+i*e^(i*0)*(x-0)+-e^(i*0)/2*(x-0)^2+-i*e^(i*0)/6*(x-0)^3+e^(i*0)/24*(x-0)^4+i*e^(i*0)/120*(x-0)^5+-e^(i*0)/720*(x-0)^6 ``` As you can see, those `+-`s, `--`s, and `(x-0)`s exist. However, these will all be replaced with `-`,`+`,and `(x)` respectively in the next part. 2. `'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x')` Here is where those substrings such as `+-`,`++`,and `(x-0)` in the now joined string are replaced with their correct substitutes using Python's built-in sub-string replacement function. After all the replacing has been done, this finally returns the finished product, which in this case would be: ``` e^(i*0)+i*e^(i*0)*(x)-e^(i*0)/2*(x)^2-i*e^(i*0)/6*(x)^3+e^(i*0)/24*(x)^4+i*e^(i*0)/120*(x)^5-e^(i*0)/720*(x)^6 ``` ]
[Question] [ The goal of this challenge is to compute the set of equivalence classes over the transitive closure of a symmetric, reflexive relation. For those who don't know what that means, here is a brief introduction into the relevant terms: A relation ◊ is *symmetric* if *a* ◊ *b* ↔ *b* ◊ *a*. It is *reflexive* if each object is related to itself, i.e. *a* ◊ *a* always holds. It is *transitive* if *a* ◊ *b* ∧ *b* ◊ *c* → *a* ◊ *c*, i.e. if *a* is related to *b* and *b* is related to *c*, then *a* is related to *c*. An *equivalence relation* is a relation that is symmetric, reflexive and transitive. The *transitive closure* ◊\* of ◊ is a transitive relation such that *a* ◊\* *b* holds if and only if there is a (possibly empty) series of objects *c*1, *c*2, ..., *c**n* such that *a* ◊ *c*1 ◊ *c*2 ◊ ··· ◊ *c**n* ◊ *b*. The transitive closure of a symmetric, reflexive relation is an equivalence relation. Let ≡ be an equivalence relation over the set *S*. An *equivalence class* *a*≡ of an object *a* over the relation ≡ is the largest subset of *S* such that *a* ≡ *x* for all *x* ∈ *S* or formally: *a*≡ = { *x* | *x* ∈ *S*, *a* ≡ *x* }. All elements of *a*≡ are equivalent to one another. The *set of equivalence classes* *S*/≡ of ≡ over *S* is the set of equivalence classes of all members of *S*. ## Constraints In this task, your objective is to write a function that takes a binary relation ≅ and a finite non-empty set *S*. You may take input in a suitable way and choose a suitable data-structure for *S* (e.g. an array or a linked list). Assume that ≅ is a symmetric, reflexive relation over *S*. Your function should return or print out the set of equivalence classes over *S* of the transitiveclosure of ≅. You may choose a suitable output format or data structure for the result. As the result is a set, each object in *S* may appear only once. You may not use library routines or other builtin functionality to find the components of a graph or related things. ## Winning condition The shortest answer in octets wins. The most elegant answer is chosen in case of a tie. ## Sample input The reflexive and symmetric members of ≅ have been omitted for brevity. *S*1 = {A, B, C, D, E, F, G, H} ≅1 = {(A, B), (B, C), (B, E), (D, G) (E, H)} *S*1/≅1\* = {{A, B, C, E, H}, {D, G}, {F}}. *S*2 = {α, β, γ, δ, ε, ζ, η, θ, ι, κ} ≅2 = {(α, ζ), (α, ι), (β, γ), (β, ε), (γ, δ), (γ, ε), (ζ, θ), (η, κ), (θ, ι)} *S*2/≅2\* = {{α, ζ, θ, ι}, {β, γ, δ, ε}, {η, κ}} *S*3 = {♠, ♣, ♥, ♦} ≅3 = {} *S*3/≅3\* = {{♠}, {♣}, {♥}, {♦}} *S*4 = {Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ} ≅4 = {(Α, Ε), (Β, Ζ), (Γ, Η), (Δ, Θ), (Ε, Ι), (Ζ, Κ), (Η, Λ), (Θ, Α), (Ι, Β), (Κ, Γ), (Λ, Δ)} *S*4/≅4\* = {{Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ}} [Answer] # Pyth, ~~50~~ 29 bytes ``` JchQ1FNeQAmf/@JTd0N XGJ.(JH;J ``` Input is expected to be a list of two elements where the first element is a list of all the objects in S, and the second element is a list of all the members in ≅, represented as lists. So for the first example, the input is ``` [["A", "B", "C", "D", "E", "F", "G", "H"], [["A", "B"], ["B", "C"], ["B", "E"], ["D", "G"], ["E", "H"]]] ``` Explanation: ``` Implicit assignment of Q to input, so head(Q) is S and end(Q) is ≅ JchQ1 Assign J to chop(head(Q),1) e.g. [1,2,3] => [[1],[2],[3]] FNeQ For N in end(Q) A Assign [H,G] to following list m N Map following function over N f 0 Return first T where following function of T starting at 0,1,2... is truthy /@JTd lambda d: true if d is J[T] XGJ.(JH; Append J[H] to J[G] and pop J[H] J Print J ``` Note that if transitive or reflexive members (i.e. redundant) members of ≅ are included, my code should output junk. You can try it out [here](https://pyth.herokuapp.com/?code=JchQ1FNeQAmf%2F%40JTd0N+XGJ.%28JH%3BJ&input=[[%22A%22%2C+%22B%22%2C+%22C%22%2C+%22D%22%2C+%22E%22%2C+%22F%22%2C+%22G%22%2C+%22H%22]%2C[[%22A%22%2C+%22B%22]%2C+[%22B%22%2C+%22C%22]%2C+[%22B%22%2C+%22E%22]%2C+[%22D%22%2C+%22G%22]%2C+[%22E%22%2C+%22H%22]]]&debug=0). ]
[Question] [ John Doe used to be one of the fastest QWERTY keyboard typists in the world, but a recent head injury caused by a stampeding herd of downgoats has critically hampered his ability to type accurately. In a desperate effort to retain his reputation as a typing prodigy, he has tasked us with the creation of a spellchecker - well, sort of. This spellchecker's rigged so that John Doe can worry less about accuracy and more about speed. # Challenge Here's the keyboard you'll be using. **NOTE: non-spacebar keys are separated by 2 spaces, with the un`shift`ed key followed by the `shift`ed key.** ``` `~ 1! 2@ 3# 4$ 5% 6^ 7& 8* 9( 0) -_ =+ Tab qQ wW eE rR tT yY uU iI oO pP [{ ]} \| aA sS dD fF gG hH jJ kK lL ;: '" enter zZ xX cC vV bB nN mM ,< .> /? [ SPACEBAR ] ``` Notice how I have arranged the keys to line up properly. This is crucial for this challenge to work. Write a full program/function that, given 2 strings of equal length containing only characters from the above keyboard, outputs a truthy/falsy value according to the following: --- If all characters' keys are at most 1 away (horizontally, vertically, or diagonally) from the characters' keys at the same index in string 2, then output truthily. * Example using `a`: Any characters in `aAqQsSzZwWxX` or `\t` (tab key) would return truthily. * Special cases: `\n` (enter key) would return truthily for any character in `[{]}\|'"` or `\n`. Spaces (spacebar key) would return truthily for any character in `xXcCvVbBnNmM,<` or spaces. Otherwise, output falsily. **Note: Tabs and newlines will be actual representations instead of their escaped equivalents (`\t` and `\n`).** --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code wins. # Example test cases ``` String1 String2 Output --------------------------------- asdf QWeR => true cat gsl => false 12345 qWeRty => true John Doe Jonh Deo => false ``` [Answer] # JavaScript (ES6), 287 bytes ``` (a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+ \t qQwWeErRtTyYuUiIoOpP[{]}\\| aAsSdDfFgGhHjJkKlL;:'" zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r ``` ## Explanation Returns `1` for true and `0` for false. Note that the `\t` should be a literal tab character. ``` (a,b)=> [...a].map((l,i)=>{ // for each character l at index i in word A p=k[g="indexOf"](l); // p = index of l in k q=k[g](o=b[i]); // o = letter in word B, q = index of o in k r=r? // if r l==s|o==s? // if l or o is a space ~m[g](l)&&~m[g](o) // check the space-matching characters for l and o : (x=(p%28/2|0)-(q%28/2|0)) // X distance between letters A and B <2&x>-2& // if distance is 2 or greater, r = 0 (y=(p/28|0)-(q/28|0)) // Y distance between letters A and B <2&y>-2 // if distance is 2 or greater, r = 0 :0 // do nothing if r == 0 }, r= // r = result // Keyboard string, each row is 28 characters long, using spaces as padding k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+ \t qQwWeErRtTyYuUiIoOpP[{]}\\| aAsSdDfFgGhHjJkKlL;:'" zZ${m="xXcCvVbBnNmM,<"}.>/?`, m+= // m = list of characters that are adjacent to space s=" " // add space to the list, s = space character ) |r // return r ``` ## Test ``` var solution = (a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+ \t qQwWeErRtTyYuUiIoOpP[{]}\\| aAsSdDfFgGhHjJkKlL;:'" zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r ``` ``` A = <input type="text" id="A" value="John Doe" /><br /> B = <input type="text" id="B" value="Jonh Deo" /><br /> <button onclick="result.textContent=solution(A.value,B.value)">Go</button> <pre id="result"></pre> ``` ]
[Question] [ You have a phone plan that lets you talk 180 minutes a day. Every day that you go over your daily limit you have to pay a fine of **F = Men**, where *M* is the number of minutes you went over and *n* is the number of days you have gone over (e.g if I went 20 minutes over the daily limit and it's my 2nd day going over, I have to pay 20\*e2 = 147.78). You will be given a list of 12-hour clock times. Even-indexed times represent the start of a phone call, odd-indexed times represent the end of a phone call. Using this list find out how much money the person has to pay in fines. # Notes * Please use an approximation of *e* that is at least as accurate as 2.718 * You never need to round your answers or include a currency symbol. * The first time in the list will always be an A.M (morning) time. * Remember that in 12-hour time `1` comes after `12` (you can think of `12` as `0`). * A day starts at 12:00 AM and ends at 11:59 PM * If a number is lower than the previous time, then that means that it is in the opposite (A.M./P.M) time range. * A call will never start in one day and end in another. # Test Cases ``` 10:30 2:30 5:30 6:30 ``` This person made two phone calls in one day. One from 10:30 A.M. to 2:30 P.M., another from 5:30 P.M to 6:30 P.M. In total, they talked for 5 hours this day, going 120 minutes over the daily limit. Since it's their first offense, they have to pay 120\*e = `$326.19` (yes, their phone plan is quite Draconic). --- ``` 10:30 11:45 5:15 6:45 8:20 9:20 5:30 7:50 2:30 3:30 ``` This person made several phone calls over 2 days. The first day they were on the phone from 10:30-11:45 A.M, 5:15-6:45 P.M., and 8:20-9:20 PM using a total of 225 minutes. That is an overage of 45 minutes. So their fine for the day is 45\*e = $122.32. The next day they talked from 5:30-7:50 A.M and 2:30-3:30 P.M., a total of 200 minutes. They went over by 20 minutes, and since it's their second offense they pay 20\*e2 = $147.78 You output their total fee as $122.32 + $147.78 = `$270.10` --- ``` 10:30 11:30 6:30 7:30 9:45 11:00 10:25 11:25 8:45 9:45 6:00 8:00 2:30 4:30 ``` * **Day 1:** + 10:30-11:30 A.M., 6:30-7:30 P.M., 9:45-11:00 P.M. = 195 minutes + Fee: 15\*e = $40.77 * **Day 2:** + 10:25-11:25 A.M., 8:45-9:45 P.M. = 120 minutes + Fee: $0 * **Day 3:** + 6:00 - 8:00 A.M., 2:30-4:30 P.M. = 240 minutes + Fee: 60\*e2 = $443.34 Output: $40.77 + $0 + $443.34 = `$484.11` [Answer] # [Perl 5](https://www.perl.org/), 185 bytes ``` @c=map{s/(.+):(.+)/$1%12*60+$2/er}<>;while(@c){$s=shift@c;$e=shift@c;$p+=0>($k=$e-$s)?720+$k:$k;if($e>$c[0]||$k<0){if($m||!@c){$f+=0>($p-=180)?0:$p*exp++$d;$p=0}$m=!$m}}printf'$%.2f',$f ``` [Try it online!](https://tio.run/##RYzBCoJAFEX3/UVwRcfJfE5ooY35H9EibAZFjUGFAvXbTWvR5nC5cI5RbR3Oc5bL5m6Gznf2nMUrfARWINyIOISv2umcJq@irJWT5WxAJ7ui1H2WJ1D/abik1EEloTx07HIUi13FqJJSO1Ap8ivdxhHVmdiwXs04br89/TONJ4MTsQvFMK56G87xWLKSJjRyi2aaTFs@e23D2gtt76DnOaD4QBuxIlwRLfgA "Perl 5 – Try It Online") ]
[Question] [ **Input** Two dates, each comprising of a month (Dec or Jan) and a day (01-31). These will be given as 4 integers (`12 01 01 01`, for example), in any reasonable format you choose (leading zeroes, no leading zeroes, list, individual inputs, list of lists, etc.). The first date is supposed to represent today's date. **Output** * If the second input date is Dec 14, output `Sufganiyot` * If it is Dec 18, output `A new hope` * For Dec 23, `The airing of grievances` * For Dec 25, `O Tannenbaum` * For Dec 31 or Jan 1, `Auld Lang Syne` * Otherwise output `Try some other day!` (in which case you will not compare the dates, see below) This is followed by * `, Go and get it!` if the first and second input dates are same. * `, Wait for it!` if the first date comes before the second date. * `, But you missed it!` if the first date comes after the second date. **Sample runs** `Dec 23 Dec 23` -> `The airing of grievances, Go and get it!` `Dec 28 Jan 1` -> `Auld Lang Syne, Wait for it!` `Dec 18 Dec 17` -> `Try some other day!` `Jan 25 Dec 25` -> `O Tannenbaum, But you missed it!` **Score** This is code golf, so shortest code in bytes wins. [Answer] # Java, ~~400~~ ~~340~~ 333 - 139 = ~~261~~ ~~201~~ 194 bytes I considered these characters "convenient": ``` , Go and get it!, Wait for it!, But you missed it!Try some other day!Auld Lang SyneO TannenbaumThe airing of grievancesA new hopeSufganiyot ``` Here is the code (called with `s(first month number, first month date, second month number, second month date)`): ``` String s(int a,int b,int c,int d){String x="";int e=(a*b!=1)?a*b:372;if(e==372)x="Auld Lang Syne";if(e==216)x="A new hope";if(e==276)x="The airing of grievances";if(e==300)x="O Tannenbaum";if(x=="")return"Try some other day!";int f=(c==1)?372*d:c*d;return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!");} ``` Ungolfed: ``` static String v(int a,int b,int c,int d){ String x=""; int e=(a*b!=1)?a*b:372; if(e==372)x="Auld Lang Syne"; if(e==216)x="A new hope"; if(e==276)x="The airing of grievances"; if(e==300)x="O Tannenbaum"; if(x=="")return"Try some other day!"; int f=(c==1)?372*d:c*d; return x+", "+((e>f)?"Wait for it...":(e<f)?"But you missed it!":"Go and get it!"); } ``` [Answer] # [Mouse-2002](https://github.com/catb0t/mouse15), 664 - 171 = 493 bytes I consider the following strings "convenient": ``` "Sufganiyot""A new hope""The airing of grievances""O Tannenbaum""Auld Lang Syne""Auld Lang Syne"", go and get it!"", wait for it!"", but you missed it""Try some other day" ``` And the code: ``` ?a:?b:?c:?d:c.12=[d.14=["Sufganiyot"a.12=[b.14=[#R,1;|b.14<[#R,2;|b.14>[#R,3;]]]|a.1=[#R,3;]]|d.18=["A new hope"|a.12=[b.18=[#R,1;|b.18<[#R,2;|b.18>[#R,3;]]]|a.1=[#R,3;]]|d.23=["The airing of grievances"|a.12=[b.23=[#R,1;|b.23<[#R,2;|b.23>[#R,3;]]]|a.1=[#R,3;]]|d.25=["O Tannenbaum"|a.12=[b.23=[#R,1;|b.23<[#R,2;|b.23>[#R,3;]]]|a.1=[#R,3;]]|d.31=["Auld Lang Syne"|a.12=[b.31=[#R,1;|b.31<[#R,2;|b.31>[#R,3;]]]|a.1=[b.1=[#R,1;|b.1<[#R,2;|b.1>[#R,3;]]]]]]]]]]|c.1=[d.1=["Auld Lang Syne"|a.1=[b.1=[#R,1;|b.1<[#R,2;|b.1>[#R,3;]]]]]|#R,4;]]$R1%a:a.1=[", Go and get it"#E;|a.2=[", Wait for it"#E;|a.3=[", But you missed it"#E;|a.4=["Try some other day"#E;]]]]@$E33!'"!"@$ ``` Ungolfed: ``` ~ [Create a Winter Bash 2015 hat reminder](https://codegolf.stackexchange.com/questions/66699/create-a-winter-bash-2015-hat-reminder) ``` ? a: ? b: ? c: ? d: c. 12 = [ d. 14 = [ "Sufganiyot" a. 12 = [ b. 14 = [ #R,1; | b. 14 < [ #R,2; | b. 14 > [ #R,3; ] ] ] | a. 1 = [ #R,3; ] ] | d. 18 = [ "A new hope" | a. 12 = [ b. 18 = [ #R,1; | b. 18 < [ #R,2; | b. 18 > [ #R,3; ] ] ] | a. 1 = [ #R,3; ] ] | d. 23 = [ "The airing of grievances" | a. 12 = [ b. 23 = [ #R,1; | b. 23 < [ #R,2; | b. 23 > [ #R,3; ] ] ] | a. 1 = [ #R,3; ] ] | d. 25 = [ "O Tannenbaum" | a. 12 = [ b. 23 = [ #R,1; | b. 23 < [ #R,2; | b. 23 > [ #R,3; ] ] ] | a. 1 = [ #R,3; ] ] | d. 31 = [ "Auld Lang Syne" | a. 12 = [ b. 31 = [ #R,1; | b. 31 < [ #R,2; | b. 31 > [ #R,3; ] ] ] | a. 1 = [ b. 1 = [ #R,1; | b. 1 < [ #R,2; | b. 1 > [ #R,3; ] ] ] ] ] ] ] ] ] ] | c. 1 = [ d. 1 = [ "Auld Lang Syne" | a. 1 = [ b. 1 = [ #R,1; | b. 1 < [ #R,2; | b. 1 > [ #R,3; ] ] ] ] ] | #R,4; ] ] $R 1% a: a. 1 = [ ", Go and get it" #E; | a. 2 = [ ", Wait for it" #E; | a. 3 = [ ", But you missed it" #E; | a. 4 = [ "Try some other day" #E; ] ] ] ] @ $E33!'"!"@ $ I am never, ever, ever going anywhere near this thing ever, ever again. ]
[Question] [ Pick six cities or villages, one from each of the populated continents, Asia, Africa, North America, South America, Europe and Australia. The forecasts cover 8351174 places, more than 2 million in the US, 150000 in Pakistan, 10000 in Uganda, and [16 places](http://www.yr.no/place/Vanuatu/Shefa/) in the [Shefa province in Vanuatu](https://en.wikipedia.org/wiki/Shefa_Province), so I think you'll find a place near you. Make a table where the weather for each of the cities are listed, for the coming ten 6-hour periods. The cities should be listed in the order above (first an Asian city, then an African city ...). The information that should be listed is: * City: `Name, CC` (`CC` is the first two letters of the country name) * Time: `yyyy-mm-dd` * Period: `1` * Weather: `Cloudy` * Temperature: `24` The output format has the following restrictions: The order is given as below (Time, Period, Weather, Temperature, Weather Temperature, Weather, Temperature ...). The city name and country code are headers ``` Kyoto, JA Addis Ababa, ET Minneapolis, US Rio de Janeiro, BR Genoa, IT Perth, AU 2015-11-05, 3, Cloudy, 15 Clear sky, 18 Heavy rain, 24 Cloudy, 12 Fair, 14 Rain, 26 2015-11-06, 0, Cloudy, 12 Fair, 14 Rain, 26 Cloudy, 12 Fair, 14 Rain, 26 2015-11-06, 1, Heavy rain, 14 Clear sky, 17 Rain, 22 Heavy rain, 14 Clear sky, 17 Rain, 22 2015-11-06, 2, Rain, 15 Clear sky, 12 Rain, 25 Heavy rain, 14 Clear sky, 17 Rain, 22 2015-11-06, 3, Partly cloudy, 9 Fair, 8 Heavy rain, 30 Clear sky, 8 Fair, 14 Partly cloudy, 25 2015-11-07, 1, Clear sky, -8 Fair, 14 Partly cloudy, 25 Clear sky, 8 Fair, -14 Partly cloudy, 25 2015-11-07, 2, Fog, 13 Partly cloudy, 15 Fair, 22 Clear sky, 8 Fair, 14 Partly cloudy, 25 ``` The weather forecast can be found on [www.yr.no](http://yr.no). The weather data can be found on xml-format on urls such as: ``` http://www.yr.no/place/Australia/Western_Australia/Perth/forecast.xml http://www.yr.no/place/Italy/Liguria/Genoa/forecast.xml http://www.yr.no/place/Turks_and_Caicos_Islands/Other/Cockburn_Town/forecast.xml http://www.yr.no/place/Bahamas/San_Salvador_and_Rum_Cay/Cockburn_Town/forecast.xml ``` Yes, there are apparently two places called "Cockburn Town". You can search for places on the main page (yr.no), and simply append `/forecast.xml` when you've found your place. (You can select language in the top right corner, the website might be shown in Norwegian). The data has the following format: ``` <time from="2015-11-05T19:00:00" to="2015-11-06T00:00:00" period="3"> <!-- Valid from 2015-11-05T19:00:00 to 2015-11-06T00:00:00 --> <symbol number="4" numberEx="4" name="Cloudy" var="04"/> <precipitation value="0" minvalue="0" maxvalue="0.4"/> <!-- Valid at 2015-11-05T19:00:00 --> <windDirection deg="131.5" code="SE" name="Southeast"/> <windSpeed mps="3.7" name="Gentle breeze"/> <temperature unit="celsius" value="12"/> <pressure unit="hPa" value="1014.2"/> </time> <time from="2015-11-06T00:00:00" to="2015-11-06T06:00:00" period="0">...</time> <time from="2015-11-06T06:00:00" to="2015-11-06T12:00:00" period="1">...</time> ``` As you can see, each 6 hour period has a period number "0", "1", "2" or "3". The table must have the date followed by the period number, `2015-11-06, 3` (might be separated by a comma, tab or whatever). You must, for each of the periods list what type of weather it is, and the temperature, in this case: `Cloudy, 12` (not `12 Cloudy`). The values can be separated by a comma, tab, or whatever. Each city must be separated from the others in such a way that they form distinct "blocks", as in the example output. The output should be on a table like format. The details of the output format is optional. These parts: `Italy/Liguria/Genoa/`, `Brazil/Rio_de_Janeiro/Rio_de_Janeiro/` of the code can be subtracted from the byte count (no need to chose the shortest city names). Url-shorteners are prohibited. It must be possible to run your code a year from now, so you can't hard code dates etc. The weather data is free and publicly available, as long as the following attribution is shown, so please include it in the bottom of your answer. This is code golf, so the shortest answer in bytes win. [Weather forecast from yr.no, delivered by the Norwegian Meteorological Institute and the NRK.](http://www.yr.no/) [Answer] # Mathematica 418 bytes These are the URL's. We will assume they are contained in variables and thus not count them. t="http://www.yr.no/place/Japan/Tokyo/Tokyo/forecast.xml"; a="http://www.yr.no/place/Algeria/Alger/Algiers/forecast.xml"; b="http://www.yr.no/place/United\_States/Massachusetts/Boston/forecast.xml"; r="http://www.yr.no/place/Brazil/Pernambuco/Recife/forecast.xml"; p="http://www.yr.no/place/France/Île-de-France/Paris/forecast.xml"; c="http://www.yr.no/place/Australia/Australian\_Capital\_Territory/Canberra/forecast.xml"; This is the code used. ``` z@{s_,k_}:=Cases[s~Import~"XML",XMLElement["time",{"from"-> d_,b_,"period"->p_}, {XMLElement[_,{___,"name"->w_,___},{}],___,XMLElement["temperature",{___,"value"->t_},{}], ___}]:>{" "->Row[{d~StringTake~10,p},", "],k->Row[{w, t},", "]},Infinity]; w=Join@@(z/@{{t,"Tokyo, JA"},{a,"Algiers, AL"},{b,"Boston, US"},{r,"Recife, BR"}, {p,"Paris, FR"},{c,"Canberra, AU"}}); Dataset[Association/@(Prepend[Cases[w,{#,r__}:>r],#]&/@w[[All,1]])] ``` --- [![table](https://i.stack.imgur.com/GPRo1.png)](https://i.stack.imgur.com/GPRo1.png) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 9 years ago. [Improve this question](/posts/45677/edit) I see GolfScript, Pyth, CJam and similar languages can make compex-ish algorithms in few bytes. This terseness makes think about genetic programming applications (using said languaes as the thing being mutated). I assume that to make a good GP language, it should have following characteristics: * Programs are typically short; * Random bytes should have high change of being a well-formed program; * Programs should compile and run fast; * Typical programs should not fall into endless loop often, or such loops should be early-detectable in most cases; * Contatenations, extraction of substrings, small modifications should often lead to something related to the original program; * Program should be easy to put in a sandbox (i.e. should not crash the interpreter); * Be turing-complete or near it. How much languages typically used for golfing suit for genetic programming? [Answer] I would be surprised if any golfing languages were appropriate for genetic programming. Pyth, at least, is very unlikely to form a valid program with random bytes, and I believe the same is true of most golfing languages. This, if nothing else, probably invalidates them as genetic programming languages. ]
[Question] [ You are to make a program that given a number, such as `22009`, will go for example to [Pi Calculation Code Golf](https://codegolf.stackexchange.com/questions/22009). Then it will, for each answer, try to figure out what the code is, and count its characters. It will then output, for each answer, its number of characters, and a link to it. It should be sorted with fewest characters at the top. For example : ``` $ answers 22009 5 https://codegolf.stackexchange.com/a/22138/16842 5 https://codegolf.stackexchange.com/a/22188/16842 6 https://codegolf.stackexchange.com/a/22012/16842 6 https://codegolf.stackexchange.com/a/22043/16842 and so on ``` This is code-golf, so shortest code wins! Note: If there are multiple things that look like code blocks, it doesn't matter which you choose. It is better though if you look which block actually looks like a program, or you could post a different one for each block. Note: This specifically says characters. It does not matter what the question actually says, just count characters. [Answer] ## Perl - 233 ``` use LWP::Simple;for($s="http://codegolf.stackexchange.com",$h=get"$s/questions/@ARGV";$h=~/-answerid="(\d+).+?(<div id="answer-|$)/sg;){$a=$&;$i=$1;$_=$1,$_=~s/&.+?;/@/sgm,print length."$u\t$s/a/$i/\n"while$a=~/<pre><code>(.+?)</sg;} ``` More aerated version: ``` use LWP::Simple; $s="http://codegolf.stackexchange.com"; $h=get"$s/questions/@ARGV"; for(;$h=~/-answerid="(\d+).+?(<div id="answer-|$)/gs;){ $a=$&; $i=$1; while($a=~/<pre><code>(.+?)</gs){ $_=$1; $_=~s/&.+?;/@/sgm; print length."$u\t$s/a/$i/\n" } } ``` This is my first script in this language... so there's still probably a lot of golfing to do. [Answer] # Javascript? (jQuery) 321 This is my first golf in javascript. ``` var l={};$(".answercell").each(function(){var w=0,c=0,t=$(this),s;t.find("pre code").each(function(){w+=$(this).text().length;c+=1});s=Math.floor(w/c);if(!isNaN(s)){l[t.find(".short-link").prop("href")]=s}});var s=Object.keys(l).sort(function(a,b){return l[a]-l[b]});for(var i=0;i<s.length;i++){console.log(l[s[i]],s[i])} ``` Ungolfed: ``` var list = {}; $(".answercell").each(function () { var w = 0, c = 0, s; t.find("pre code").each(function () { w += $(this).text().length; c += 1; }); s = Math.floor(w/c); if (!isNaN(s)) { list[$(this).find(".short-link").prop("href")] = s; } }); var sorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]}); for (var i=0; i<sorted.length; i++) { console.log(list[sorted[i]], sorted[i]); } ``` Works in the browser console, so maybe it's against the rules, idk. The way it computes for the score is adding all lenghts of code blocks and then dividing by the number of blocks, for each question. This version, at 257, just counts the first code block: ``` var l={};$(".answercell").each(function(){var t=$(this),s;s=t.find("pre code").text().length;if(s>0){l[t.find(".short-link").prop("href")]=s}});var s=Object.keys(l).sort(function(a,b){return l[a]-l[b]});for(var i=0;i<s.length;i++){console.log(l[s[i]],s[i])} ``` ]
[Question] [ Write a program that takes a sorted integer array, shuffles all the elements in such a way that for every `i` there must exist a `j` such that, one of the following is satisfied: ``` a[i] < a[j] < a[i+1] a[i] > a[j] > a[i+1] ``` `i` and `j` are within the bounds of array. If there are not many distinct elements, you must show an error. For example, ``` Input: 1, 2 Output: Error Input: 1, 2, 3, 4, 5, 6, 7 Output: 7, 1, 4, 2, 5, 3, 6 Input: 1, 2, 2, 4, 5, 6, 7 Output: 1, 4, 6, 2, 5, 2, 7 Input: 1, 2, 2, 3 Output: Error Input: 1, 5, 7, 7, 11 Output: Error ``` There may be more than one possible correctly shuffled arrays. You just have to solve for 1 correct solution. Input array can have repeated elements, this requirement makes the solution tricky, otherwise a sort and skip would have worked. Being able to have duplicates in input also makes it different from [The Strange Unsorting Machine for Nefarious Purposes](https://codegolf.stackexchange.com/questions/8800/the-strange-unsorting-machine-for-nefarious-purposes) . And a correct solution is much trickier than the that. The output must be of same size as input array and all elements from the input array must exist at some position in the output array. **How to take input:** The program must take input either through console input or a simple delimited text file. **How to output:** The program must output to the console. **What to output:** Program must output both the input and the output array in following format ``` Input: 1, 2, 3, 4, 5, 6, 7 Output: 7, 1, 4, 2, 5, 3, 6 ``` If input cannot be shuffled as required, the output should look like ``` Input: 1, 2, 3 Output: Error ``` Shortest code (byte count) wins. **BONUS 1:** Deduct 10 points from your count if your solution can work on unsorted inputs. **BONUS 2:** Deduct 20 points from your count if your solution can find more than 1 (not all) solutions for the same input. To qualify for this bonus, your additional solution must not be just a reversed output of the other solution. [Answer] # Haskell, ~~311~~276 (-30 bonus=246) ``` import Data.List m=map w=putStrLn b=(intercalate",").(m show) o="Output: " z[]=[o++"Error"] z a=m((o++).b)a main=do r<-getLine let q=m read(words r)::[Int] w$"Input: "++b q mapM_ w$z$filter(\d->and$m(\(a,b)->any(\x->(a<x&&x<b)||(a>x&&x>b))d)$zip d(tail d))$permutations q ``` Compile with `ghc`, Run from the command line, input is a single line with space delimited numbers, eg `echo 1 2 3 4|shuffle`. This is a brute force solution so is quite likely to be slow for large input lists. It prints all the solutions. ]
[Question] [ Based on [this](https://stackoverflow.com/questions/14720579/implement-simple-interpreter-which-tells-us-current-value-of-a-variable-using-ja/14720954#14720954) closed question on stack overflow, what is the shortest way to stimulate scope for variables in an input. For simplicity, `print` is replaced with `>`. copying critical information from the linked source: > > `[` and `]` start and end a new scope. > > > > > > > Within scopes any changes to a variable outside of that scope is not permanent and is reverted when the scope has left, but the outer values are used to determine if a variable is undefined and its starting value. > > > > > > > > > Input will always start with `[` and will end with matching `]` > > If its not defined then value should be `0` > > All input that is not a variable is a number with no decimal points. as in `10` or `582` > > `> a` means print the contents of `a` > > `a 10` assigns `10` to `a` > > `a b` assigns the contents of `b` to `a` > > Variables should be considered strings: `one 1` is valid syntax > > It is not required for the input to contain the print command `>` > > > **Note on scoring**: ``` You may chose how to input and output the "code", but it should be explained in the answer. ``` I answered this on the linked page in java, but I did not go for shortest code. Comment any suggestions or questions, so I can improve my future posts. Shortest code by character wins. Good luck. [Answer] ## Python 2, 165 ``` def f(v): while 1: s=raw_input().split() if'['in s:f(dict(v)) elif']'in s:break elif'>'in s:print v.get(s[1],0) else:v[s[0]]=v.get(s[1],s[1]) raw_input() f({}) ``` Character count assumes tabs are used for the second level of indentation. ]
[Question] [ Write the smallest program performs a time stretch operation on a PCM Wave (.wav) file. Rules: * Parameter input will by via whatever standard argument mechanism your language comes with, e.g. `argv` in C/C++, `$_GET` in PHP. Hard coded paths are not allowed. * First parameter will be a decimal value that represents the stretch coefficient. 1 means don't stretch, 2 means twice the length, 0.5 means half the length, 0.333 means one third the length. An example might be `stretch.exe 1.5 c:\sound.wav` * The time stretch operation does not need to perform pitch correction. * You must not drop samples to fit a compression (i.e. stretch < 1). You should use interpolation, weighted mean, or a similar method. * Assume a [WAVE PCM](https://ccrma.stanford.edu/courses/422/projects/WaveFormat/) file with a RIFF header. * Assume 16-bits per sample (bonus if your code works for 8-bit and 24-bit audio) * You must handle any number of audio channels. * You must at least handle 11025, 22050 and 44100Hz sample rates, though the ability to handle arbitrary rates would be a bonus! :) * Your output file must keep the same sample rate, sample size and channel count as the input file. * The output file must be named "stretch.wav" * You may not use any 3rd party libraries or built-in functions for audio processing. The parsing of the WAV file and the time stretch operation must be your own code. On Windows, the `C:\Windows\Media` directory contains plenty of WAV files to test with. [Answer] ### Ruby, 220 characters ``` s,n=$* w=IO.binread(n).unpack r='s<*' x=[];t=[g=0]*c=w[11] w[u=22..-1].each_slice(c){|f|g+=v=1.0/s.to_f c.times{|h|t[h]+=f[h]*v} (c.times{|h|x<<=m=t[h]/g;t[h]-=m};g-=1)until 1>g} w[u]=x;IO.binwrite'stretch.wav',w.pack(r) ``` This version works with ruby 1.9.3 with basic 16 bit files (e.g. no additional chunks) for any sample rate or number of channels. ]
[Question] [ There's a lot of questions about *Conway's* Game of Life, but nothing about customization (Related: [2-Player Life](https://codegolf.stackexchange.com/questions/83988/its-life-jim-but-not-as-we-know-it)). Given an input, determine the result on a 100x100 grid after some iterations. The input is given as a string. For example: ``` Using the character #, follow the following rules: If there are 2 or 3 neighboring nothing, turn into #. Using nothing, follow the following rules: If there are 3 neighboring #, turn into #. Output the result after 100 iterations for the cells: [Lots of cells here] ``` As you might be able to tell, this is Conway's Game of Life, where a cell is alive if there are three live neighbors, and a live cell with less than two or more than three neighbors dies. You may use any kind of input, but I'll be doing it like this for simplicity. ### Input * For simplicity, a character can *also* be the phrase "**nothing**." * Each rule is separated by two newlines. Each rule starts with, "**Using the character `X`, follow the following rules:**" where `X` represents a character. * Then, it says "**If there are `[amount]` neighboring `X`, turn into `Y`.**" The amount is some numbers, separated by `or`, where `X` and `Y` represent characters. It may say this multiple times. * Then it says, "Output the result after `N` iterations for the cells:" Your job is to return the result after N iterations. * Then, decode the cells given. The cells are stored with a space for empty cells, and a single character for all the other characters. Newlines separate the rows. Also, the last rule is always for `nothing`, and instead starts with "**Using nothing, follow the following rules:**" A cell will never turn into itself. (So, for `#`, "If there are 2 $, turn into #." will not happen.) Simply render "nothing" with a space, and all other characters normally. The other characters are ASCII and not a space. For the iterating, follow the instructions for each character. When it says "neighboring," it means the cells next to it (including diagonals). For the borders, "wrap around" the cells. One way to think of wrapping around is to pretend that there are 8 identical grids surrounding the current one, then updating the current ones with the new neighbors. (Sorry if my explanation was weird.) ## Test case (replace \n with a newline): ``` Using the character #, follow the following rules: If there are 0 or 1 #, turn into $. If there are 4 or 5 or 6 or 7 or 8 #, turn into nothing. Using the character $, follow the following rules: If there are 4 nothing, turn into #. If there are 4 or 5 or 6 or 7 or 8 $, turn into #. Using nothing, follow the following rules: If there are 3 #, turn into #. Output the result after 25 iterations for the cells: \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n $$$$$$$$$$ \n $$$$$$$$$$ \n # # \n # # \n $$$ $$$ $$ \n $$$ $$$ $ \n $ $$$ $$$ \n #### #### \n ## ## \n $#$#$#$#$# \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ``` ## Result: [![The Result](https://i.stack.imgur.com/z2cNu.png)](https://i.stack.imgur.com/z2cNu.png) (This code golf is inspired by [this thingy](https://ncase.me/sim/), and of course, Conway's Game of Life.) [Answer] # [Python 3.8](https://docs.python.org/3.8/), 597 bytes ``` from copy import deepcopy as p def f(r): u,g,b,e={},0,[],' ' for l in r: if g:b+=[list(l)];z=len(l);continue j=l[:1] if'T'<j:c=[e,l[20]][l[6]>'n'];u[c]=[] if'I'==j: n=[] for s in l[13:].split(' or '): n+=[int(s[0])] if s[3:]:v=[s[2],e][','<s[3:4]] u[c]+=[[v,n,[l[-2],e][l[-3]>e]]] if'O'==j:i=int(l.split()[4]);g=1 for _ in e*i: h=p(b) for k in range(len(b)*z): r,c=k//z,k%z;v={k:0 for k in u} for j in range(9):x,y=j//3-1,j%3-1;v[b[(r+y)%len(b)][(c+x)%z]]+=1 a=b[r][c];v[a]-=1 for w in u[a]: if v[w[0]]in w[1]:h[r][c]=w[2];break b=p(h) return b ``` [Try it online!](https://tio.run/##7VjBbuIwEL3nKywBctK6QArtdkPde0@97J5ca5WkDnFwnchxoFD121nbAbrsrlbdA4dKMcrYDG/mvRlHHKZa67yUk5tKbbeZKp9BWlZrwJ@rUmnwxFjlvsc1qLwnloHMV0HkgQbNUYIYfn1DY0QoggB6ICsVEIBLoAwC8AzMo@QcE8Fr7YuAzjZYMGlOs7SUmsuGGVSBBYlC6vDwG7wtohQThgS5HFNKBLmmd1BCOmtISjHZ4e4hxoXlALL1OeraUgsSTiI6rCvBtQ@BccPAIYE0UrjUfk3GNHBBVmJNDDxaYlKTS4oYJRDBW@ucUoexvCaQLJFERs5FCzKHCb1jlO4EPThBHNv8YkcekCkNZnMcto35YdWxM27F5Ljyk8BrZS9cx2I5Z75tTxKcbVrFCqV4MRpt0GKwmS3x6yIavwc0b/uyi/f4r0H0gta4GI0mFyEqBsbOliQhvjpfB4M2OyV@ev4SDDbU1BXaJDFOiKKmToON6UXrtJlXjsj4on23lmRlukeNe0VCGuVtHF6Z3s0SxeKFASamuNwUp5hulATJVrNalwADCOH3mss50DkDaR6rONVMgR4yZEKUK@dvjxalGsHqyLvPrF8xEJtnbC80tCEut2l3CfrDY8zUYq6subbmizU3xyGy1LmhGHre3wT1/0PQdJ/r1/S9Dynq/xay03LI92ENk@PibKqHRleNdrGK1Y3QIM5saZdXgJs91ryUtbtjVzoTom7v@NTrUXYsHUvH0rF0LB1Lx/LpWPqH9flZen8cPi@LbVX7nPQdO9CctJYDzUnvxay9PSXL8X6ijvX2n@5/rGPpWDqWjqVj@ceCEHrefjDn9qFilYhT5sPHRwkRgMYGnuLznB0gu6mq@8XzDuPezHew3Zy1UnYKCuGwKLmd9gbbnw "Python 3.8 (pre-release) – Try It Online") Online custom game of life simulator: [Emoji Simulator!](https://ncase.me/sim/?lz=N4IgtgpgLghiBcoAmEDOBjATgSwA5WwHsA7BEAYQHkA5AdQEEBNAcgGUACAcXoFkBRdpQBi7ADIBJIXwCEAHWIALKFFyp4AenURiAOgDu2ANZ4ISbDB2FMAc3UHj68iT0wAns1QB9TjEifCAGaeotgBEPLy5BLkANLsAGTsACIASvSc7CTsUAoQ7NY4SNmE7EiYMHrsYFZ5AQA2hHoQmKjsgDwbgBz7EcRCEBB17AGYfcXsw7h1MOh5ObUNTZjsBjnsMMSu7BDVAFbY7K6EAK5La1DsgLwbgJU7IAA0IGUVCABMdwGqCACMdxNuCFCYhwgAF87qhYFA0AgANqgbBIBAABju2HQJDIAGJbiBiL4IBisVMCCRUNDQKhsNZSPAQAAeAC8WOIhzAn1B4Ig4iSZARBPQROIJPgMJAYJgEM5ZA+WKgrlweOp1kInigStFEN5-MFUIAukDtXcZXKyKFPMQIBSFAAjKwgEFkilUkAAPgZdyZLPgABY2WKOVz4EiQISiALSSL2RLqU9pbL5SBFcrVeyNSGtbr9SBDXGTWaLdbMLaMygMDh8CGyLabrD4fAviAUWjqQASRm4sgtu7FrB4fkVu7B4lh8mUsiu7HMhDe8O+yMgaP9vmpocR-2BrNkBMqzxqvELzXQ9MG2PGoK56xWm12kUOsguxkTr0+8X+kBSvdLoVkleIo9GhVKrcdxTQchUPTNj2pHNzXPfNCyvOFnmRVFHXYVtIDIYhCBybBiGsLEu1LXtqWA0NP2vEdqTHd0EAAZifP0fyDRcQOFHdIzXCD4wApNfRItM9V-bNT2gi8Cz1ASQD0Kw6hrUBDlwJBeOpckwEOOpYDNI4STdET8wUQhCBrcADOGLFcEwQhcCsfcyLY1dvhgTAoEFBErzs1kQFwRznMRNzv3gF5PO8wUPgRVyM3JAAveVQAMJAcknQNcgtKBaJooEMqAA) --- *Commented code* ``` from copy import deepcopy as p def f(r): """Takes as input a list of lines""" # dictiornary of rules of the grid u = {} # flag to extract lines of the grid g = 0 # the grid, as a list of lists of characters b = [] # space used to represent nothing e = ' ' # PART 1 # parse the rules # loop on the input lines for l in r: if g: # extract lines of the grid b += [list(l)] # extract the lenght of the row of the grid # used for the loop n the grid z = len(l) # skip other checks continue # extract the first character for each line # not [0] since it can be an empty line j = l[:1] if 'T' < j: # line "Using the character ..." # extract the character # checking if the character is nothing c = [e, l[20]][l[6] > 'n'] # initialize an empty list for the rules associated to the character u[c] = [] if 'I' == j: # line "If there are ..." # initialize list of repetitions n = [] # the number of repetitions are split by or for s in l[13:].split(' or '): # extract the number # always the first element of the split n += [int(s[0])] # extract the character associated with the repetitions # the number is followed by the character # this means that the split string is longer if s[3:]: # character associated with the repetitons # checking if the character is nothing v = [s[2], e][',' < s[3:4]] # add the rule u[c] += [[ # character associated with the repetitons v, # list of number of repetitions n, # extract the new character to substitute # checking if the character is nothing [l[-2], e][l[-3] > e] ]] if 'O' == j: # line "Output the result ..." # extract the number of steps i = int(l.split()[4]) # set flag to extract the lines of the grid g = 1 # PART 2 # evaluate the steps on the grid # loop for i steps # e*i is an auxiliary string of length i to evaluate i steps for _ in e * i: # copy the previous grid state h = p(b) # loop on each cell of the grid # loop on height*width for k in range(len(b)*z): # extract the index of row, column from the "total" loop index r, c = k//z, k%z # initialize dictionary of count of neighbouring characters v = {k: 0 for k in u} # loop on the 3x3 square around the actual cell for j in range(9): # scale to range [-1, 0, 1] x, y = j//3 - 1, j%3 - 1 # update the count of neighbour # extracting the corresponding character in the grid v[b[(r+y)%len(b)][(c+x)%z]] += 1 # current character a = b[r][c] # remove the current cell from the count of neighbours v[a] -= 1 # check rules for w in u[a]: # if count of neighbour is in list of number of repetitions if v[w[0]] in w[1]: # substituite actual character in the grid with the new one h[r][c] = w[2] # rule found, skip others break # update the actual grid b = p(h) # return the grid after the steps return b ``` ]
[Question] [ [Part 1](https://codegolf.stackexchange.com/questions/246611/convert-to-shorthand-part-1) of the challenge revolved around converting the letters into specific unicode characters. ## Lore In this part we receive the output from the function made in Part 1, which now has to be arranged in an artistic manner. ## Aim Take 1 word as input which has already undergone transformation in the function made in Part 1 and perform the necessary transformation ## Example: A -> A ``` Λ ``` Quick -> Qck ``` 𐍉 ⩁< ``` Brown -> Brwn ``` L \ ᑎ ⌵ ``` Fox -> Fx ``` ⌽ X The presence of F's endpoint being in middle can be imagined to be shifted towards right or left. That's why it requires a white-space for alignment ``` Jumps -> Jmps ``` ᨈ ᨈ⊥⦵ )⊥⦵ OR ) In this case ⦵ has end points in middle, hence connection will be at same level as previous symbol ``` Over -> Ovr ``` ┼ OR ┼⌵\ ⌵\ ``` The -> The ``` _ | ∟ ``` Lazy -> Lzy ``` ( ᒣ ɥ ``` Dog -> Dg ``` Ꙅ T ``` Turtle -> Trtle ``` _ \_ ( ∟ ``` Of -> Of ``` ┼ ⌽ As the widths are slightly different, the joining is approximated. The presence of no whitespace before either suggests both to be in same 'column'. ``` Terror -> Tr ``` _ \ ``` ## Rules of interconnections 1. The connection must be on the end points of symbol 2. If symbol is drawn next line then spacing must be done appropriately. E.g. showing spacing with `.` ``` _ .\_ ...( ....∟ L .\.ᑎ ..⌵ ``` 3. The next character must start from it's left/top/bottom most end points and be connected to top/right/bottom most end point of previous symbol ## Visual Representation for clarity [![Handwritten Shorthand](https://i.stack.imgur.com/oArUx.png)](https://i.stack.imgur.com/oArUx.png) Forgive my handwriting and the error in the image, I have been watching iskall85 a little too much ;p ## Guide For Where To Connect The Next Symbol(The dot represents the connection point) [![Drawing Guide](https://i.stack.imgur.com/RignE.png)](https://i.stack.imgur.com/RignE.png) ]
[Question] [ I am looking for tips to code in this golfing language [Seriously](https://github.com/Mego/Seriously), and was wondering what some of the ways for golfing this language is. "Remove comments" is not a tip. [Actually](https://github.com/Mego/Seriously/releases/tag/v2.0) is also included ]
[Question] [ Although on codingame.com, Objective C and C are two of the best golfing languages there, so I would like to know some of the best golfing methods (although I am a python person, I am currently trying to learn C++/C) I am looking for general ways/tips to golf one's code (so please don't post tips such as "remove comments" and so on) Please post each tip as a separate answer. ]
[Question] [ (Based on [this Math.SE problem](https://math.stackexchange.com/questions/472908/given-a-desired-coloring-scheme-for-a-stick-how-can-i-brush-it-with-the-fewest), which also provides some graphics) I have a stick which looks kinda like this: ![enter image description here](https://i.stack.imgur.com/QbEoU.jpg) I want it to look kinda like this: ![enter image description here](https://i.stack.imgur.com/CJGRP.jpg) I'm not an expert painter, however, so before I start such an ambitious DIY project, I want to make sure that I'm not in over my head. Your program should tell me how how many steps are involved in painting this stick. Each step involves painting a continuous area with a solid color, which covers up previous layers of paint. For the above example, I could paint the left half blue, the right half red, and then the two separate green areas for a total of 4 steps (the green is not continuously painted). ![enter image description here](https://i.stack.imgur.com/R7UJl.jpg) Here it is in ASCII: ``` ------ bbb--- bbbrrr bgbrrr bgbrgr ``` There are a couple different ways to paint this stick and end up with the same result. I'm only interested in the time estimate, however, which is four steps. ## Goal Your program should output the minimum number of steps needed to paint a stick with a given color scheme. The paint scheme will be in the form of a string of characters, while output will be a number. This is code golf. Shortest program wins. ## Input Your program will receive the coloring scheme for a stick in the form of a string of letters. Each unique letter (case sensitive) represents a unique color. ``` YRYGR grG GyRyGyG pbgbrgrp hyghgy ``` ## Output These numbers are the least number of steps needed to paint the sticks. ``` 4 3 4 5 4 ``` ## Explanations This is how I arrived at the above numbers. Your program does not need to output this: ``` ----- YYY-- YRY-- YRYG- YRYGR --- g-- gr- grG ------- GGGGGGG GyyyGGG GyRyGGG GyRyGyG -------- pppppppp pbbbpppp pbbbrrrp pbgbrrrp pbgbrgrp ------ -yyyyy -ygggy hygggy hyghgy ``` Edit: I'll add more test cases if they prove to be more difficult test cases. [Answer] # [Python 3](https://docs.python.org/3/), ~~60~~ 59 bytes ``` p=lambda s:len(s)and-~min(sum(map(p,s.split(c)))for c in s) ``` [Try it online!](https://tio.run/##HcaxDsIgEADQWb@CMN0l1cWtiTM7W9M4QKtAAvQCONzir6M4vUfc/JFvvdM9mmR3I@ocnxkqmrxfPin8@k6QDAFN9VophgYbIr6OIjYRsqjYx834Khe9KC0nIV1RA8WaFf9L1tniCo17dt6xfMznE5WQGxAYxP4F "Python 3 – Try It Online") Ungolfed: ``` def paint(stick): if not stick: return 0 return 1 + min( sum(paint(part) for part in stick.split(c)) for c in stick ) ``` [Answer] ### GolfScript, 82 72 67 characters ``` .,n*{:c,,{[).2$1<*\c>+1$.,,{).2$<\3$<=},,.@>@@>]}%\;{~S)}%$0+0=}:S~ ``` Reasonably fast for a GolfScript program, examples: ``` > hyghgy 4 > pbgbrgrp 5 ``` The algorithm used works through the colors left-to-right recursively, according to the following statements: * Ignore all parts from the left which already have the required color. Overpainting them again will not provide a better answer. * If the complete stick already has the desired color, return 0 steps as result. * Otherwise, take the target color of the now leftmost part (i.e. the first not in the desired color). + Paint 1 part with the target color and recurse. + Paint 2 parts with this color and recurse.... + Paint the whole remaining stick with this color and recurse.Take the minimum of all those numbers and add 1 (for the current step). Return this as the optimal number of steps. This algorithm works, because the leftmost part has to be painted at one time anyways, so why not do it immediately - in any possible fashion. ``` .,n* # prepare the initial situation (target stick, unpainted stick) # used n instead of '-' for the unpainted parts, because it is shorter { # Define the operator S which does t c S -> n # - t: the desired target colors # - c: the stick as it is colored currently # - n: minimum number of steps required to go from c to t :c # Assign the current configuration to the variable c ,,{[ # Map the list [0 1 2 .. L-1] # We will build a list of all possible configurations if we paint # the stick with the 0th part's color (either 1 or 2 or 3 or ... parts) ). # Increase the number, i.e. we paint 1, 2, 3, ... L parts, copy 2$1< # Take the first color of the target configuration * # ...paint as many parts \c>+ # ...and keep the rest as with the current stick 1$ # take the target configuration # Top of stack now e.g. reads # h----- hyghgy (for i=0) # hh---- hyghgy (for i=1) # Next, we strip the common leading characters from both strings: .,, # Make list [0 1 2 ... L-1] { # Filter {}, all the numbers for which the first j+1 parts are the same ). # incr j 2$< # take leftmost j parts of stick A \3$< # take leftmost j parts of stick B = # are they equal? },, # The length of the result is the number of common parts. .@> # cut parts from A @@> # cut parts from B ]}% \; # Remove the target from the stack (not needed anymore) # We now have a list of possible paintings where 1, 2, ..., L parts were # painted from the left with the same color. # All configurations were reduced by the common parts (they won't be # painted over anyways) {~S)}% # Call the method S recursively on the previously prepared configurations $0+0= # $0= -> sort and take first, i.e. take the minimum, 0+ is a workaround # if the list was empty (i.e. the operator was called with a stick of length 0). }:S ~ # Execute S ``` [Answer] **JavaScript: 187 Bytes** Assuming we're allowed to just have the input and output to a function (please)! ``` function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;){l = 1;for(var k=-1;(j=k)!=m;){if((k=w.indexOf(w[i],++j))==-1)k=m;l+=p(w.substring(j,k));}if(s==-1||l<s)s=l;}return s;} ``` **157 Bytes** by doing further ugly optimization (Which is part of the point, and I found incredibly fun): ``` function p(w){var j,l,s=-1,i,m=i=w.length;if(m<2)return m;for(;i--;s<0|l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,(j=w.indexOf(w[i],j))<0?m:j++));return s} ``` **135 Bytes** I realised that the length of the input is an upper bound and I don't need to handle trivial cases separately now. ``` function p(w){var j,l,s,i,m=s=i=w.length;for(;i--;l<s?s=l:1)for(l=1,j=0;~j;)l+=p(w.substring(j,~(j=w.indexOf(w[i],j))?j++:m));return s} ``` Test cases: ``` p("YRYGR") 4 p("grG") 3 p("GyRyGyG") 4 p("pbgbrgrp") 5 p("hyghgy") 4 ``` Expanded version: ``` function paint(word) { var smallest = -1; if(word.length < 2) return word.length; for(var i = word.length; i-->0;) { var length = 1; for(var left, right = -1;(left = right) != m;) { if((right = word.indexOf(word[i],++left)) == -1) right = word.length; if(left != right) length += paint(word.substring(left , right)); } if(smallest == -1 || length < smallest) smallest = l; } return smallest; } ``` For every character of the input, calculate the length of the pattern if we paint that colour first. This is done by pretending we paint that colour and then making sub sections out of the bits that aren't that colour, and recursively calling the paint method on them. The shortest path is returned. Example (`YRYGR`): Initially, try `R`. This gives us the sub groups `Y` and `YG`. `Y` is trivially painted in one go. For `YG`: Try `G`, `Y` is trivial, length `2`. Try `Y`, `G` is trivial, length 2. `YG` is therefore length `2`. Painting `R` first therefore gives us `1 + 1 + 2 = 4` Then try `G`. This gives us the sub groups `YRY` and `R`. `R` is trivial. For `YRY`: Try `Y`: `R` is trivial, length `2`. Try `R`: `Y` and `Y` are the two groups, length `3`. `YRY` is length `2`. Painting `G` first gives `1 + 1 + 2 = 4` Then try `Y`. This gives the sub groups `R` and `GR`. `R` trivial, `GR` is length `2`. `Y` is length `4` This implementation would then check R and Y again to reduce code length. The result for `YRYGR` is therefore `4`. [Answer] ## Python, 149 chars ``` D=lambda s:0 if s=='?'*len(s)else min(1+D(s[:i]+'?'*(j-i)+s[j:])for i in range(len(s))for j in range(i+1,len(s)+1)if set(s[i:j])-set('?')==set(s[i])) ``` I use `?` to mark an area that may be any color. `D` picks a contiguous region of the stick that contains only a single color (plus maybe some `?`s), colors that region last, replaces that region with `?`s, and recurses to find all the previous steps. Exponential running time. Just barely fast enough to do the examples in a reasonable time (a few minutes). I bet with memoization it could be much faster. [Answer] ## Python 3 - 122 ``` def r(s,a):c=s[0];z=c in a;return s[1:]and min([1+r(s[1:],a+c)]+[r(s[1:],a[:a.rfind(c)+1])]*z)or(1-z) print(r(input(),'')) ``` It seems to work, but I'm still not 100% sure that this method will always find the minimum number of steps. [Answer] ## CoffeeScript - 183 247 224 215 207 ``` x=(s,c='')->return 0if !s[0]?;return x s[1..],c if s[0]is c;l=s.length;return x s[1...l],c if s[l-1]is c;i=s.lastIndexOf s[0];1+(x s[1...i],s[0])+x s[i+1..],c y=(z)->z=z.split "";Math.min (x z),x z.reverse() ``` [Demo on JSFiddle.net](http://jsfiddle.net/TimWolla/DJpe9/5/) Ungolfed version including debug code and comments: ``` paintSubstring = (substring, color = '####') -> console.log 'Substring and color', substring, color, substring[0] # no need to color here if !substring[0]? return 0 # no need to recolor the first part if substring[0] is color return paintSubstring (substring[1..]), color l = substring.length # no need to recolor the last part if substring[l-1] is color return paintSubstring substring[0...l], color # cover as much as possible index = substring.lastIndexOf substring[0] part1 = substring[1...index] part2 = substring[index+1..] console.log 'Part 1:', part1 console.log 'Part 2:', part2 # color the rest of the first half p1 = paintSubstring part1, substring[0] # color the rest of the second half, note that the color did not change! p2 = paintSubstring part2, color # sum up the cost of the substick + this color action return p1+p2+1 paintSubstringX=(x)->Math.min (paintSubstring x.split("")), paintSubstring x.split("").reverse() console.clear() input = """YRYGR grG GyRyGyG pbgbrgrp aaaaaaaa hyghgy""".split /\n/ for stick in input console.log paintSubstringX stick ``` [Answer] ## Haskell, ~~118~~ 86 characters ``` p""=0 p(a:s)=1+minimum(map(sum.map p.words)$sequence$map(a%)s) a%b|a==b=b:" "|1<3=[b] ``` Test runs: ``` λ: p "YRYGR" 4 λ: p "grG" 3 λ: p "GyRyGyG" 4 λ: p "pbgbrgrp" 5 λ: p "hyghgy" 4 λ: p "abcacba" 4 ``` This method isn't even all that inefficient! [Answer] Haskell, 143 chars ``` f s=g(r n ' ')0where{r=replicate;n=length s;g p l=minimum$n:[0|p==s]++[1+g(take i p++r(j-i)(s!!i)++drop j p)(l+1)|l<n,i<-[0..n-1],j<-[i+1..n]]} ``` This tries all possible rewritings up to the length of the string, and goes until it finds one that constructs the input pattern. Needless to say, exponential time (and then some). [Answer] A simple breadth first search. It doesn't put anything on the queue that's already been seen. It works in under a second for all of the examples but 'pbgbrgrp' which actually takes a full minute :( Now that I have something that *works* I'll be working on finding something faster and shorter. **Python - ~~300~~ 296** ``` def f(c): k=len(c);q=['0'*99];m={};m[q[0]]=1 while q: u=q.pop(0) for x in ['0'*j+h*i+'0'*(k-j-i) for h in set(c) for j in range(1+k) for i in range(1,1+k-j)]: n=''.join([r if r!='0' else l for l,r in zip(u,x)]) if n == c: return m[u] if not n in m: m[n]=m[u]+1;q.append(n) ``` ]
[Question] [ Given an unsorted list of unique, positive integers, output the shortest list of the longest possible ranges of sequential integers. # INPUT * An unsorted list of unique, positive integers + e.g. `9 13 3 11 8 4 10 15` * Input can be taken from any one of the following: + `stdin` + command-line arguments + function arguments # OUTPUT * An ordered list of ranges or individual values printed on one line to stdout or your language's closest similar output. + If two or more sequential integers (sequential by value, not by location in the list) are present, they will be denoted as an inclusive range using -, e.g. `8-11` + All other integers are simply printed with no other notation + A single space will delimit the output * Numbers not present in the input should not be in the output, e.g. `3 5 6` cannot be shortened to `3-6` because `4` is not present # EXAMPLES **Successful:** ``` IN> 9 13 3 11 8 4 10 15 6 OUT> 3-4 6 8-11 13 15 IN> 11 10 6 9 13 8 3 4 15 OUT> 3-4 6 8-11 13 15 IN> 5 8 3 2 6 4 7 1 OUT> 1-8 IN> 5 3 7 1 9 OUT> 1 3 5 7 9 ``` **Wrong:** ``` IN> 9 13 3 11 8 4 10 15 OUT> 3-15 ``` Range contains values not in the input ``` IN> 9 13 3 11 8 4 10 15 OUT> 3 4 8 9 10 11 13 15 ``` All sequential values should be represented as a range ``` IN> 9 13 3 11 8 4 10 15 OUT> 3-4 8-9 10-11 13 15 ``` Divided range, `8-9` and `10-11` should be `8-11` ``` IN> 9 13 3 11 8 4 10 15 OUT> 8-9 13 10-11 3-4 15 ``` Output not ordered correctly # RULES * [Standard loopholes are disallowed](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * If your language has a function to do this it's not allowed * You may write a full program, or a function * trailing whitespace doesn't matter # SCORING * Least bytes wins [Answer] # Python 2, ~~123~~ 120 bytes ``` N=sorted(map(int,raw_input().split(' ')));print(''.join((''if n+1in N else'-'+`n`)if n-1in N else' '+`n`for n in N)[1:]) ``` If the input can be a list as a function argument then (thanks mbomb007 and xnor for the conditionals) # ~~93~~ ~~90~~ 81 bytes ``` def f(N):print''.join((' '+`n`,`-n`*-~-(n+1in N))[n-1in N]for n in sorted(N))[1:] ``` (77 bytes if leading whitespace is acceptable - drop the final `[1:]`) [Answer] # JavaScript (ES6): ~~171~~ ~~154~~ 140 ~~137~~ bytes Thanks edc65 and vihan1086 for the tips! ~~`[...n]` is very nice~~ but it doesn't work in these cases due to multi-digit numbers. ``` f=n=>{s=e=o='';n.split` `.map(Number).sort((a,b)=>a-b).map(v=>{s=s||v;if(e&&v>e+1){o+=`${s<e?s+'-'+e:s} `;s=v}e=v});return o+(s<e?s+'-'+e:e)} ``` ## ES5 variant, ~~198~~ ~~184~~ ~~183~~ 174 bytes ``` f=function(n){s=e=o='';n.split(' ').map(Number).sort(function(a,b){return a-b}).map(function(v){s=s||v;if(e&&v>e+1){o+=(s<e?s+'-'+e:s)+' ';s=v}e=v});return o+(s<e?s+'-'+e:e)} ``` ``` f = function (n) { s = e = 0, o = ''; n.split(' ').map(Number).sort(function (a, b) { return a - b }).map(function (v) { s = s || v; if (e && v > e + 1) { o += (s < e ? s + '-' + e : s) + ' '; s = v } e = v }); return o + (s < e ? s + '-' + e : e) } // Demonstration document.body.innerHTML = f('1 2'); document.body.innerHTML += '<p>' + f('9 13 3 11 8 4 10 15 6'); document.body.innerHTML += '<p>' + f('11 10 6 9 13 8 3 4 15'); document.body.innerHTML += '<p>' + f('5 8 3 2 6 4 7 1'); document.body.innerHTML += '<p>' + f('5 3 7 1 9'); ``` [Answer] # Ruby, 70 bytes Problems like these tend to make me check the Ruby API for suitable methods, and today I discovered a new one: [`Array#slice_when`](http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-slice_when), newly introduced in Ruby v2.2 and seemingly intended for this exact situation :) ``` f=->a{puts a.sort.slice_when{|i,j|j-i>1}.map{|x|x.minmax.uniq*?-}*' '} ``` After sorting and appropriately slicing the array, it takes each sub-array and creates a string out of the highest and lowest element, and then joins this whole array into a string. Example: `f.call [9,13,3,11,8,4,10,15,6]` prints `3-4 6 8-11 13 15` [Answer] # SWI-Prolog, ~~165~~ ~~162~~ 159 bytes ``` b(Z,C,[D|E]):-Z=[A|B],(A=:=D+1,(B=[],put(45),print(A);b(B,C,[A,D|E]));(E=[],tab(1),print(A);writef('-%t %t',[D,A])),b(B,A,[A]));!. a(A):-sort(A,B),b(B,_,[-1]). ``` Pretty bad but then again Prolog is a terrible golfing language Example: `a([9,13,3,11,8,4,10,15,6]).` outputs `3-4 6 8-11 13 15` [Answer] # Ruby, ~~86~~ 84 bytes ``` s=->*a{puts a.sort.slice_when{|i,j|i+1!=j}.map{|e|e.size<2?e:[e[0],e[-1]]*"-"}*" "} # demo s[9, 13, 3, 11, 8, 4, 10, 15, 6] # => 3-4 6 8-11 13 15 ``` This is a slightly golfed version from an example in the docs for [slice\_when](http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-slice_when). [Answer] # CJam, 35 bytes ``` l~${__0=f-ee::=0+0#/((oW>Wf*S+oe_}h ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l~%24%7B__0%3Df-ee%3A%3A%3D0%2B0%23%2F((oW%3EWf*S%2Boe_%7Dh&input=%5B9%2013%203%2011%208%204%2010%2015%206%5D). ### How it works ``` l~$ e# Read a line from STDIN, evaluate it and sort the result. { e# Do: _ e# Push a copy of the array. _0=f- e# Subtract the first element from all array elements. ee e# Enumerate the differences: [0 1 4] -> [[0 0] [1 1] [2 4]] ::= e# Vectorized quality: [i j] -> (i == j) 0+ e# Append a zero. 0# e# Push the first index of 0. / e# Split the array into chunks of that size. ( e# Shift out the first chunk. (o e# Print its first element. W> e# Discard all remaining elements (if any) except the last. Wf* e# Multiply all elements of the remainder by -1. S+o e# Append a space and print. e_ e# Flatten the rest of the array. }h e# Repeat while the array is non-empty. ``` [Answer] # CJam, ~~38~~ 33 bytes New version, using ideas and code fragments suggested by @Dennis: ``` l~$_,,.-e`{~T+\_T+:T;(_2$+W*Q?S}/ ``` [Try it online](http://cjam.aditsu.net/#code=l~%24_%2C%2C.-e%60%7B~T%2B%5C_T%2B%3AT%3B(_2%24%2BW*Q%3FS%7D%2F&input=%5B9%2013%203%2011%208%204%2010%2015%5D) The input format is a CJam array in square brackets. The basic idea here is that I subtract a monotonic sequence from the sorted input sequence first: ``` 3 4 8 9 10 11 13 15 0 1 2 3 4 5 6 7 (-) ---------------------- 3 3 6 6 6 6 7 8 ``` In this difference, values that are part of the same interval have the same value. Applying the CJam RLE operator to this difference directly enumerates the intervals. The subtracted sequential values need to be added back during output. I'm not entirely happy with how that's done in my code. I suspect that I could save a few bytes with a more elegant way of handing that. For generating the output of the intervals, this uses Dennis' idea of generating a negative number for the end value, which takes care of producing a `-`, and also simplifies the logic because only one value needs to be added/omitted depending on the interval size. Explanation: ``` l~ Get input. $ Sort it. _,, Create monotonic sequence of same length. .- Calculate vector difference between the two. e` Calculate RLE of difference vector. { Loop over entries in RLE. ~ Unpack the RLE entry, now have length/value on stack. T+ Add position to get original value for start of interval. \ Bring length of interval to top of stack. _T+:T; Add length of interval to variable T, which tracks position. ( Decrement interval length. _ Copy it, we need it once for calculating end value, once for ternary if condition. 2$ Copy interval start value to top... + ... and add interval length - 1 to get end value. W* Negate end value. Q? Output end value if interval length was > 1, empty string otherwise. S Add a space. }% End loop. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ṢI’kƊ.ịⱮUQ€j€”-K ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWejxpmZh/r0nu4u/vRxnWhgY@a1mQB8aOGubre/w@3A5mR//9HW@ooGBrrKACRoaGOgoWOggmQZQDEpjoKZrE6CtEgYZCAmY4CVK0FWDlInSlIgSlMxAisCChuDpSCyhhDeEC9sQA "Jelly – Try It Online") ## How it works ``` ṢI’kƊ.ịⱮUQ€j€”-K - Main link. Takes an array L on the left Ṣ - Sort L; Call this A Ɗ - Monad. Link the previous three links together f(A): I - Forward differences ’ - Decrement k - Partition This groups consecutive runs Take A = [3, 4, 6, 8, 9, 10, 11, 13, 15] I: [1, 2, 2, 1, 1, 1, 2, 2] ’: [0, 1, 1, 0, 0, 0, 1, 1] k then partitions A at truthy elements in I’ [[3, 4], [6], [8, 9, 10, 11], [13], [15] Ɱ - For each: .ị - Take the 0.5th element For non-integer left argument, x, Jelly's ị atom takes floor(x) and ceil(x) and returns [floor(x)ịy, ceil(x)ịy] As Jelly's indexing is 1-based and modular: 0ị returns the last element 1ị returns the first element .ị returns [0ị, 1ị] U - Reverse each Q€ - Deduplicate each j€”- - Join each with "-" K - Join by spaces ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ 20 bytes ``` ;moJ'-?I§e←→ε†sġ·=←O ``` [Try it online!](https://tio.run/##yygtzv7/3zo330td197z0PLUR20THrVNOrf1UcOC4iMLD223BQr4////P9pSx9BYx1jH0FDHQsdEx9BAx9BUxywWAA "Husk – Try It Online") A bit lacking in the strings department, but does well. No matter what I tried, it somehow stubbornly stayed at 21. -1 byte from Dominic Van Essen. ## Explanation ``` ;moJ'-?I§e←→ε†sġ§=…eO O order the list ġ group the list by the following: e elements paired §= equal … the range between them? †s convert all the numbers to strings mo map each group to the following: ? ε if it's a single element: I leave as is §e←→ otherwise, move the first and last elements to a list J'- join with '-' ; nest to display in one line ``` [Answer] ## CoffeeScript, ~~178~~ 161 bytes Just like my JavaScript answer. I need to figure out if using comprehensions will result in shorter code. ``` f=(n)->s=e=o='';n.split(' ').map(Number).sort((a,b)->a-b).map((v)->s=s||v;(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(e&&v>e+1);e=v);o+(if s<e then s+'-'else'')+e ``` --- Original: ``` f=(n)->o='';s=e=0;n.split(' ').map(Number).sort((a,b)->a-b).forEach((v,i)->if!i then s=v else(o+=s+(if s<e then'-'+e else'')+' ';s=v)if(v!=e+1);e=v);o+(if s<e then s+'-'else'')+e ``` [Answer] # Python 2, ~~126~~ ~~122~~ 121 Bytes I know this can get shorter, just don't know where.. Requires input in form `[#, #, #, #, ..., #]`. ``` l=sorted(input());s=`l[0]`;c=0;x=1 while x<len(l):y,z=l[x],l[x-1];s+=(('-'+`z`)*c+' '+`y`)*(y-z>1);c=(y-z<2);x+=1 print s ``` [Answer] # Java, 191 bytes ``` void f(int[]a){java.util.Arrays.sort(a);for(int b=a.length,c=b-1,i=0,j=a[0],l=j;++i<b;){if(a[i]!=++j||i==c){System.out.print((l+1==j?l+(i==c?" "+a[c]:""):l+"-"+(i==c?j:j-1))+" ");l=j=a[i];}}} ``` Checks for ranges and prints them accordingly. Unfortunately I had to make a special case for the last element in the array since the program would terminate without printing the last number or range. [Answer] # Java, ~~171~~ 162 bytes ``` String s(int[] n){Arrays.sort(n);int p=0,b=0;String r="",d="";for(int c:n){if(c==++p)b=1;else{if(b==1){r+="-"+--p+d+c;p=c;b=0;}else{r+=d+c;p=c;}d=" ";}}return r;} ``` Takes input as an int array, returns output as a space-separated String list [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÍòÈnYÉÃ®é ¯2 Ôq- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=zfLIblnJw67pIK8yINRxLQ&input=WzkgMTMgMyAxMSA4IDQgMTAgMTUgNl0) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 120 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 15 bytes ``` s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJTfj0iLCIiLCJzOsKvx4/igb3huYXhuIvigKLqnJ3Gm+KCjWh0VVxcLWoiLCIiLCIhKC4qKSAtPiBcIiguKilcIlxuWzYsIDEsIDIsIDQsIDMsIDUsIDgsIDcsIDEwXSAtPiBcIjEtOCAxMFwiXG5bMTEsIDEwLCA2LCA5LCAxMywgOCwgMywgNCwgMTVdIC0+IFwiMy00IDYgOC0xMSAxMyAxNVwiXG5bOSwgMTMsIDMsIDExLCA4LCA0LCAxMCwgMTUsIDZdIC0+IFwiMy00IDYgOC0xMSAxMyAxNVwiXG5bNSwgOCwgMywgMiwgNiwgNCwgNywgMV0gLT4gXCIxLThcIlxuWzUsIDMsIDcsIDEsIDldIC0+IFwiMSAzIDUgNyA5XCIiXQ==) ## Explained ``` s:¯Ǐ⁽ṅḋ•ꜝƛ₍htU\-j s: # Push two copies of the input list but sorted ¯Ǐ # Forward differences of items with the first item appended - this is for making sure the length of the deltas matches the length of the input ⁽ṅḋ # Grouped by whether they are <= 1 • # Reshape the sorted input to that shape ꜝ # and remove the 0 # the top of the stack will be a list of lists of numbers that are ranges ƛ # to each range ₍htU # either get the first and last item or just the first \-j # join on "-" # S flag joins the result on spaces ``` [Answer] # [Haskell](https://www.haskell.org/), 187 bytes ``` import Data.List g p[x]=[[x]] g p(a:b:c)|let(d:e)=g p(b:c)=if p a b then(a:d):e else[a]:(d:e) p[x]=show x++" " p x=show(head x)++"-"++show(last x)++" " f=concatMap p.g(((-1==).).(-)).sort ``` [Try it online!](https://tio.run/##JY7LCoMwFET3fsVFukgwhoY@aAPZddl@gbi41WhCo4YmUBf9dxvtZmAOh2EMhpd2blns4Kd3hBtG5HcbYtaDr@ZaVSnqtRCUT9nQr9ORtFJTtbKVKNuBB4QnRKPHpLVUatAu6AprubnZNhXM9IG5KHLIMw/z1onR2MJMEy3zotiQwxD/KImdaqaxwfhAD573hJBSKEU55aSklId0ehnQjsq/7Rh33a66MnFgByYEu7AjE3smTuxcLz8 "Haskell – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 204 bytes Modified from [@steenslag's Ruby answer](https://codegolf.stackexchange.com/a/52328/110802). --- Golfed version. [Try it online!](https://tio.run/##PU9NT8QgEL3vr5g0HhiLuF0/oigmHj142nja9ICU3aC0W4GYaMNvr1OMkpkwvOG9mReN9no@vr5Zk@BZuwGmubN7iEzLpyGdotzaj902BTccWjV9ag9RaRGPIdnujpUmJX1t2@XFIlsj4rmMInrXEYttECdm@Ijqwe3ZSP26UWpkDaIRbnBJ1swIryMVBbU@WjCyXuQKkEWvRxYKP4jovu39BoPo33/3gkKI1ckUSDyf0V3kcoV5Bljs9OSM6XCIEh5D0F9/jlDCC20ACqYV0BkJTX4gF7ccmgsOFE3D4YbDJVVryisO1/g/m1VQIRI3r/L8Aw) ``` def s(a:Int*):Seq[String]={val s=a.sorted;(Seq[Seq[Int]](Seq(s(0)))/:s.sliding(2)){(c,p)=>if(p(0)+1==p(1))c.init:+(c.last:+p(1))else c:+Seq(p(1))}.map(r=>if(r.size<2)r.mkString else s"${r(0)}-${r.last}")} ``` Ungolfed version. [Try it online!](https://tio.run/##XVHRSsMwFH3fVxyKD4mrYZ1TtFjBR2G@KD6NPVzbdEaztiRB0NFvr2myDTZIQs49595zL9eWpGkY2o8vWTq8kGqwmwCVrGEZ5Xhu3CXP8d4ohyJQwA9p2NY4WfkQifg9Y16p2Ujr@QiF1apSzYbNuahbXS1l7dhSWbcKj3dZrwNme/2npIpzjh0YlWWKjpThKB6DDaBqsDHEZhxTZCiKoGCZT/F6ocZ@82lIFppsAAfFvobUVo7ikQrWJ3x/HMicjhInE1vqWGB8U6GdAIRVfxIPmPOYJrbfb874waObTS52MT7O118d0Nhhn0TjzsudbmI9eyzAEiShtX6y38/WL4uR2dgcT8bQ7yoK1@frsuw@RXadwp8sS3GXYuF/M39vUtzGmv1kGP4B) ``` object Main { def s(a: Int*): Unit = { val sorted = a.sorted val sortedRanges = sorted.sliding(2).foldLeft(List[List[Int]](List(sorted.head))) { (acc, pair) => if (pair(0) + 1 == pair(1)) acc.init :+ (acc.last :+ pair(1)) else acc :+ List(pair(1)) } val ranges = sortedRanges.map(range => if (range.size < 2) range.mkString else s"${range.head}-${range.last}") println(ranges.mkString(" ")) } def main(args: Array[String]): Unit = { s(9, 13, 3, 11, 8, 4, 10, 15, 6) } } ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), 35 bytes ``` a0r[r0Ir::u[ps`=]pl~!['-olu!]p' o]; ``` [Try it online!](https://tio.run/##y6n8/z/RoCi6yMCzyMqqNLqgOME2tiCnTjFaXTc/p1QxtkBdIT/W@v9/Q0MuQwMuMy5LLkNjLgsuYy4TLkNTAA "Ly – Try It Online") This is pretty brute force. It sorts the numbers then iterates until all the numbers have been consumed. After printing the "current" number on the stack, an inner loop consumes all the entries after that which are consequitive. Then it either appends a `-#` string or not before printing a space and iterating again. ``` # prep work... created sorted list of numbers with trailing "0" a0r a - read numbers from STDIN, sort stack 0 - push a "0" r - reverse stack # loop over all numbers, then exit [ ]; [ ] - iterate while top of stack not "0" ; - exit to avoid dumping junk on stack # remember the current number for comparison later r0Ir r - reverse stack 0I - copy bottom of stack entry to the top r - reverse the stack # print the current number, loop/consume all sequential nums on stack ::u[ps`=]p :: - duplicate top of stack twice u - print current number [ ]p - loop until top of stack is "0" p - delete previous number s - save the current number `= - increment current number, compare to next num on stack # print "-X" if needed to cover delete numbers, then print space l~!['-olu!]p' o l - load saved num (last number deleted) ~ - search stack for that number ! - negate result [ ]p - "then" code block '-o - print "-" lu - load last num in sequence (last deleted) ! - flip top of stack to "0" to exit loop ' o - print " " ``` [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 95 bytes ``` $_=join$",sort{$a-$b}@F;$b=$_,s/(\d+)\K (?=(\d+))/$2-$1-1?$":"-"/ge while$_ ne$b;s/(-\d+)+/$1/g ``` [Try it online!](https://tio.run/##HcvNCoJAFIbhW/kYzkLR08yxLErEVm2iOxBEaTBDHFGhRXTrTT@7d/G8o5361Huq8rvrBlLx7KblSTVT8zqeMmpyquJZB@U1CsszgiL/Z6gpYRKWgtRBsdKtxePW9ZYqDJaa7LvwD0aaRLfeb5Biiz0EO4iBCCRBYrB@u3Hp3DB7vqQrI8ZzPX4A "Perl 5 – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 3 years ago. [Improve this question](/posts/215747/edit) # Introduction This challenge appeared in the [2020 Estonian Open Informatics Olympiad](https://eio.ee/) and was created Sandra Schumann. I thought it was interesting because it involves symmetry and is quite hard even to brute force by hand. The problem author said that it's ok for me to post it here:[![proof](https://i.stack.imgur.com/QcE4C.png)](https://i.stack.imgur.com/QcE4C.png) # Challenge You may use a modified version of [BrainF\*\*k](https://en.wikipedia.org/wiki/Brainfuck) with the following modifications: * Using `-` on a cell containing 0 keeps the value at 0. * Using `<` on cell 0 keeps the pointer at cell 0. * The values in the cells never overflow * The code may execute at most 10 million commands. There are 5 separate tasks, for which you must write 5 separate programs: 1. Cells 0 and 1 contain the integers x and y respectively (0 <= y <= x <= 200) and all other cells contain 0. Write the difference x - y into cell 0. 2. Cell 0 contains an integer x (0 <= x <= 200) and all other cells contain 0. Write x modulo 7 into cell 0. 3. Find the number of the leftmost cell containing 0 and write this number into cell 0. The answer will not exceed 100 and no cell will contain a value greater than 50 initially. 4. Cell 0 contains an integer k (3 <= k <= 10) and cells 1 and 2 contain the integers F[1](https://i.stack.imgur.com/QcE4C.png) and F[2] (1 <= F[1](https://i.stack.imgur.com/QcE4C.png), F[2] <= 3), which are the first numbers in the sequence F[i] = F[i - 1] + F[i - 2]. Write F[k] in cell 0. 5. Cell 0 contains 0, one or several consecutive cells after it contain positive integers, and the rest of the cells contain 0. Find the greatest integer contained in a cell and write its value in cell 0. The answer doesn't exceed 50 and there are at most 100 cells with positive integers. Furthermore, each program must be in an N by N square of BrainF\*\*k code. The code doesn't have to be the same when read in the two directions, but it must solve its task correctly in both cases. The goal is to get each N to be as small as possible # Example Input and Output Let's say a task was to add the values in cells 0 and 1 intead. One possible output would be ``` >[-<+>] [++++<> <---->< +++++<< >---]>< -<><>[> ]><<<>< ``` Reading by rows: `>[-<+>][++++<><----><+++++<<>---]><-<><>[>]><<<><` Reading by columns: `>[<+>-][+-+-<>-+-+-><<+-+-<<++-+]><><><>[>]><<<><` # Winning Criteria The winner is whoever can minimize the sum of Ns over the five tasks. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/205007/edit). Closed 3 years ago. [Improve this question](/posts/205007/edit) # The task Given a folded and cut in places snowflake, "unwrap" it and output the result # Input The base folded snowflake, without any cuts, looks like: ``` |\ | \ | \ | \ | \ | \ | \ | \ |________\ ``` And the input will always resemble this. No changed or added symbols will go out of the range of this triangle, so ``` |\ | \ -| \ | \ o 0 | \ | \ | \. | \ |________\ ``` is not a valid input. ## Possible changes and additions: 1. Corner cuts ``` minimal cut: _ | \ | \ | \ | \ | \ | \ |_ \ |_____/ ``` ``` Big, different cuts with cuts in them: |\_/\ | \ | \ |___ \ _| _| |___/ ``` 2. Side cuts ``` minimal cuts, in random places on the sides: |\ | \ | \ | |_ | \ \ \ / \ | \ |____/\__\ ``` ``` Big, recursive cuts: |\ | \ \ \ \| /| | | _ / |_| \ | |\___ \ |_| \_\ ``` And, of course, both types can be present at the same time. # Output An "unfolded" snowflake. Here is an explanation of the unfold: ``` Say we have a snowflake __ | \ | \ | \ \ \ / \ | / |______/ Which we will, for the explanation, remake as: aa 1 1 2 2 3 3 b 4 b 5 1 c 2123456c Where each uncut piece of sides is numbered from 1 to 9, and each cut has its own letter. On the first unfold, you will get 123 12 a bb 1 aaa 2 1 3 2 4 3 5 b c b c 1 c 2123456c Which looks like ___ __ | \/ | __| | | | | | | | \ / / / | / |_____/ Then, on the next unfold, we get: 123 1221 321 a bb bb a aaa aaa 1 1 2 2 3 3 b cc b b c c b 1 c c 1 2123456c c6543212 Which looks like ___ ____ ___ | \/ \/ | __| |__ | | | | | | \ /\ / / / \ \ | / \ | |______/ \______| If you would want another unfold, the scheme looks fine: 123 1221 321 a bb bb a aaa aaa 1 1 2 2 3 3 b cc b b c c b 1 c c 1 2 c c 2 2 c c 2 1 c c 1 b c c b b cc b 3 3 2 2 1 1 aaa aaa a bb bb a 123 1221 321 Until you actually make it in ascii: ___ ____ ___ | \/ \/ | __| |__ | | | | | | \ /\ / / / \ \ | / \ | | / \ | | \ / | | \ / | \ \ / / / \/ \ | | | | | | __| |__ | /\ /\ | ___ ____ ___ So, for this challenge, I have chosen not to go for another unfold. ``` Here is another example on one of the snowflakes, without the scheme: ``` |\ | \ | \ | \ \ \ / \ | \ | /\ \ |_/ \__/ Then, on the first unfold turns to: ____ ____ | \/ | | / | / | \ \ \ / | | | | /\ / |_/ \__/ And then: ____ ________ ____ | \/ \/ | | /\ | | / \ | | \ / | \ \/ / / \ | | | /\ /\ | |_/ \__________/ \_| ``` Notice how, on the first unfold, the bottom side of the triangle translates to the right side of the square and, the same, with the left and top side. # Output The final result, so ``` ____ ________ ____ | \/ \/ | | /\ | | / \ | | \ / | \ \/ / / \ | | | /\ /\ | |_/ \__________/ \_| ``` for the example. This is code-golf, so lowest byte-count wins! ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Closed 3 years ago. * This site is for programming contests and challenges. **General programming questions** are off-topic here. You may be able to get help on [Stack Overflow](http://stackoverflow.com/about). * Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. [Improve this question](/posts/201041/edit) I am quite proficient in C++ and Java and want to learn competitive programming to participate in contests like Google codejam and other online contests held on sites like CodeChef and Codeforces. I would like to get information about any **free** resources including websites and courses to learn the "sport". Book suggestions are also welcome. Please suggest some courses which have some practical work included and not just flat theory. I want to work on my problem solving skills rather than just learning algorithms and data structures. [Answer] # Practice Algorithmic Thinking If there's one thing I believe programmers need to master, it's the process of dissecting a problem statement and planning their approach. By this, I mean having the ability to approach an unseen challenge and think about what is being asked. If I were you, I'd look at challenges posted around this website, ranging from trivial to difficult, and take the time to plan how you would solve the problem. That way, you'll be able to have a hands on experience with problem solving. Once you do this enough, start placing time restrictions on your thinking time. Because I know from personal experience that competitive programming is most often timed. Once you have got that nailed, you should be ready for competitions. In summary: practice. Y'all need to walk before y'all can run. I hope to see you as an active contributor around here! ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/186485/edit). Closed 4 years ago. [Improve this question](/posts/186485/edit) Not exactly sure if it belongs in this site, but I always have trouble thinking of all the certain edge cases in any kind of competitive programming or puzzles. For example, take this kind of problem > > Find the size of the smallest list of squares that add up to n > > > `f(16)-> 1 (16)` > > `f(17)-> 2 (16+1)` > > > One intuitive approach would be to take the largest square that fits into n, subtract, and taking the remainder and applying the function on that until n<4. This doesn't work as soon as you go to `f(18)-> 2 (9+9)` rather than `f(18)-> 3 (16+1+1)` While those edge cases may be easier to derive, many times edge cases will not be as intuitive. What are some general guidelines of finding such edge cases? ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/171828/edit). Closed 5 years ago. [Improve this question](/posts/171828/edit) It is 20th anniversary of [Casio's S-VPAM calculators](https://en.wikipedia.org/wiki/Casio_V.P.A.M._calculators) and it is worth celebrating. Task: Process input string as Casio S-VPAM calculator does. The infix notation and precedence of mathematical operations must be followed. Angle values are expected in radians. Since there were multiple updates, `sin 15`, `sin15` and `sin(15` are equally parsed as `sin(15)` and spaces are thus ignored. Input: String or Char array Output: Array of 8-bit numbers representing the segments states on the [7-segment display](https://en.wikipedia.org/wiki/Seven-segment_display) [![enter image description here](https://i.stack.imgur.com/9kLez.png)](https://i.stack.imgur.com/9kLez.png) ``` A B C D E F G DP | representation | visualization blank 0 0 0 0 0 0 0 0 | 0 / 00 | " " or "_" minus 0 0 0 0 0 0 1 0 | 2 / 02 | "-" 0 1 1 1 1 1 1 0 0 | 252 / FC | "0" 0. 1 1 1 1 1 1 0 1 | 253 / FD | "0." or "0," 1 0 1 1 0 0 0 0 0 | 96 / 60 | "1" 1. 0 1 1 0 0 0 0 1 | 97 / 61 | "1." 2 1 1 0 1 1 0 1 0 | 218 / DA | "2" 2. 1 1 0 1 1 0 1 1 | 219 / DB | "2." 3 1 1 1 1 0 0 1 0 | 242 / F2 | "3" 3. 1 1 1 1 0 0 1 1 | 243 / F3 | "3." 4 0 1 1 0 0 1 1 0 | 102 / 66 | "4" 4. 0 1 1 0 0 1 1 1 | 103 / 67 | "4." 5 1 0 1 1 0 1 1 0 | 182 / B6 | "5" 5. 1 0 1 1 0 1 1 1 | 183 / B7 | "5." 6 1 0 1 1 1 1 1 0 | 190 / BE | "6" 6. 1 0 1 1 1 1 1 1 | 191 / BF | "6." 7 1 1 1 0 0 0 0 0 | 224 / E0 | "7" 7. 1 1 1 0 0 0 0 1 | 225 / E1 | "7." 8 1 1 1 1 1 1 1 0 | 254 / FE | "8" 8. 1 1 1 1 1 1 1 1 | 255 / FF | "8." 9 1 1 1 1 0 1 1 0 | 246 / F6 | "9" 9. 1 1 1 1 0 1 1 1 | 247 / F7 | "9." deg 1 1 0 0 0 1 1 0 | 198 / C6 | "o" frac 0 0 1 1 0 0 0 0 | 48 / 30 | "/" A B C D E F G DC | representation | visualization ``` Input string is split in substrings as follows: `X` : number decimal separator is either dot or comma, whatever comes first. Using both results in `Syntax Error` `n` : one-digit number or result in braces `command` : string operator Special commands: * Power `X^n`: `X` to power `n` * Root `nsqrtX`: `n`th root of `X` * Exponent: `XEY` `X` times 10^`Y` * Angles: `XD` return `X` degrees in radians; `XG` return `X` grads in degrees * Degrees: `XdYdZd` return string in `MoNoXo` format. `M` is number of whole degrees(hours), `N`<60 number of whole minutes and `X` seconds (may be decimal) If part of command return as decimal value. `Xd` may be omitted returning `0oNoXo` string instead * Goniometric functions `funX`: 'function of `X`. `-h` suffix triggers hyperbolic function `a-` prefix triggers inverse function. * Logarithms: `lnX` natural logarithm of `X`; `logX` decadic logarithm of `X` * Fractions: `X\Y`,`X\Y\Z`: If `X`and`Y`and`Z` are integers return "`A`/`B`" where `A` and `B` are lowest integers possible, otherwise return default format * Combinatorics: `X!` Factorial of `X`; `XCY` [`Y`-combinations of `X`](https://en.wikipedia.org/wiki/Combination); `XPY` [`Y`-permutations of `X`](https://en.wikipedia.org/wiki/Permutation). `X` and `Y` must be integer, otherwise return `"Syntax error"` * Constants: `pi`, `e` * Random number: `Ran#` return uniformally distributed value U(0,1) * Absolute value: `AbsX` Non-necessary zeros, multiplications and trailing brackets may be omitted Test: ``` Input | Result HEX array | Result Visualized 1+6 | 00 00 00 00 00 00 00 00 00 00 E0 00 00 00 | " 7 " sin-.5pi | 00 00 00 00 00 00 00 00 00 02 60 00 00 00 | " -1 " cosh180D | 00 60 61 B6 F6 60 F6 B6 F2 DA FE 00 00 00 | " 11.59195328 " piD | 00 00 F2 C6 FE C6 DA F7 E0 F2 C6 00 00 00 | " 3o8o29.73o " -25e-4sin 1-cos 59^(5-7 | 02 61 FC F2 60 B6 E0 E0 E0 66 F2 02 60 FC | "-1.031577743-10" ``` Rules: Standard rules apply: Loopholes forbidden, the shortest answer in bytes win. ]
[Question] [ # X Marks the spot Your goal is to add a cross-hair around the capital X: ## Example Input / Output Input: ``` mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss yyyhhhsosyhhmmmmdmmm mhyhhhy y ssyhoho o shhdmmmmdmmmm hhyyyh s oo syysyyhhdysso oyhdhhhmmmmm dhysyys sdysoXoyyyyhhso syshm mmm hhyhyo o osss y shhyyhd mmmmmm yyhyyyss o oyyyydmmdmmmmmmmmm mm ysyhyhhho s osy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ``` Output: ``` mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss | yyyhhhsosyhhmmmmdmmm mhyhhhy y |ssyhoho o shhdmmmmdmmmm hhyyyh s oo s|ysyyhhdysso oyhdhhhmmmmm dhysyys -----X-----hhso syshm mmm hhyhyo o | osss y shhyyhd mmmmmm yyhyyyss |o oyyyydmmdmmmmmmmmm mm ysyhyhhho s |sy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ``` --- Input: ``` 000000000000 000000000000 0000X0000000 0000000X0000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 ``` Output: ``` | 0000|00|0000 0000|00|0000 -----X--+--00 00--+--X----- 0000|00|0000 0000|00|0000 0000000|0000 000000000000 000000000000 000000000000 000000000000 000000000000 ``` --- Input: ``` 00000000000000000 00000000000000000 00000000000000000 00000X000X0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ``` Output: ``` 00000|000|0000000 00000|000|0000000 00000|000|0000000 ----+#+++#+----00 00000|000|0000000 00000|000|0000000 00000|000|0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ``` ## Crosshair Your cross-hair should be a 3-tall and 5-wide: ``` | | | -----X----- | | | ``` ### Input Input will be at least 12x12 characters in size and will consist of only ASCII characters. It can be taken in through STDIN or function argument. The input will not always contain an X. Input will be in any shape and have an arbitrary amount of whitespace. The input will not contain any of: `+`, `-`, `#`, and `|` ### Output Output can be through STDOUT or a function's return value. Output should be the input image with the cross-hair drawn. If there is not enough space to draw the crosshair, you must add lines / spaces to draw it. Overlapping spots should be replaced with a `+`. If the `|` or `-` of the crosshairs overlaps an `X`, instead of a `+`, an `#` should appear. Trailing whitespace is not allowed *except* for a single newline at the very end. --- This is code-golf so shortest code in bytes wins! [Answer] # CoffeeScript, ~~345~~ ~~336~~  327 bytes ``` Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ``` `X` is the function to call. ### Explained: ``` # get new char. s - old char. c - '|' or '-' Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)-> # leftmost and upmost positions l=u=0 # split input into 2D array o=(r.split ''for r in s.split '\n') # for every 'X' or '#' c in'X#'&&( # for positions to left and right i-x&&( # draw horisontal line o[y][i]=Z o[y][i],'-' # update leftmost position i<l&&l=i )for i in[x-5..x+5] # for positions above and below i-y&&( # add row if necessary and draw vertical line (o[i]?=[])[x]=Z o[i][x],'|' # update upmost position i<u&&u=i )for i in[y-3..y+3] )for c,x in r for r,y in o # concatenate into string, replacing empty chars with spaces ((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ``` ### Executable: ``` <script src="http://coffeescript.org/extras/coffee-script.js"></script> <script type="text/coffeescript"> Z=(s,c)->s in'X#'&&'#'||s in'-|+'&&'+'||c X=(s)->l=u=0;o=(r.split ''for r in s.split '\n');c in'X#'&&(i-x&&(o[y][i]=Z o[y][i],'-';i<l&&l=i)for i in[x-5..x+5];i-y&&((o[i]?=[])[x]=Z o[i][x],'|';i<u&&u=i)for i in[y-3..y+3])for c,x in r for r,y in o;((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[u...o.length]).join '\n' ################################################################################ # tests follow s = [''' mdhyyyyyyyhhhddmmm mdyyssoo oooosyyyhhhdmm hsso oossoooooyyhhdhhdmmm yoooooo oo ssysssyhhdyyyhmmmm myso oso o oyo hhhdhhyhyhhm mm m mhsyhhys oss yyyhhhsosyhhmmmmdmmm mhyhhhy y ssyhoho o shhdmmmmdmmmm hhyyyh s oo syysyyhhdysso oyhdhhhmmmmm dhysyys sdysoXoyyyyhhso syshm mmm hhyhyo o osss y shhyyhd mmmmmm yyhyyyss o oyyyydmmdmmmmmmmmm mm ysyhyhhho s osy sdm m mddmmddhydmmm h oshhhyyyddhoo ooyysshdmdohdmmdmddsshmmm y oyhhhdhhsyhsssshdddsss hdddyyyhddm dyyshyyhssyyhyyyyddhhmmdmmmdy syssoosyhdm hsyyhhhhsoo sooyyhhdoohdhhyhyysoo osdm doyhhhyyyyhhhysyyy oossyyssso osydm soyhyyhhhhhhyhyyyooos ohdddm msoyyyyyyyhyyyyo ooo syyd ho oyyysooo osso osyd dhyyysssyyyyyysoosdm mmdddddmmm ''' ''' 000000000000 000000000000 0000X0000000 0000000X0000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 ''' ''' 00000000000000000 00000000000000000 00000000000000000 00000X000X0000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 00000000000000000 ''' 'X' 'XX\nXX' ] document.write '<pre>' document.write '\n\n',X x for x in s </script> ``` [Answer] # Python 3, ~~577~~ ~~519~~ ~~515~~ ~~490~~ ~~475~~ ~~467~~ 454 bytes ``` def c(g,d): R,L,V,e,b=range,list,len,'-|+','#';t,g=(lambda g,d:sum([[(i,j)for j in R(V(L(g.split('\n')[i])))if g.split('\n')[i][j]==d]for i in R(V(g.split('\n')))],[]))(g,d),[L(i)for i in g.split('\n')] for a,r in t: for j in R(a-3,a+4): if V(g)>j>-1:n=g[j][r];g[j][r]='+'if n in e else'#'if n in(d,b)else'|' for j in R(r-5,r+6): if V(g[a])>j>-1:n=g[a][j];g[a][j]='+'if n in e else'#'if n in(d,b)else'-' return'\n'.join(''.join(l)for l in g) ``` I'm not sure how much farther I can golf this. ### Usage: ``` c(g, d) ``` Where `g` is the input grid and `d` is the crosshair-marking character. [Answer] # Perl, 370 bytes ``` sub r{$h=pop;($=[$n=pop].=$"x(1+"@_"-length$=[$n]))=~s!(.{@_})(.)!"$1".($2=~/[-|+]/?'+':$2=~/[X#]/?'#':$h)!e}map{chop;push@c,[$-,pos]while/X/g;$-++}@==<>;($x,$y)=@$_,3-$x>$a?$a=3-$x:0,$x+5-@=>$b?$b=$x+5-@=:0,6-$y>$c?$c=6-$y:0 for@c;@==($",@=)for 1..$a;$_=$"x$c.$_ for@=;map{($x,$y)=@$_;$_&&r$y+$c+$_-1,$x+$a,'-'for-5..5;$_&&r$y+$c-1,$x+$_+$a,'|'for-3..3}@c;print@=,$,=$/ ``` Usage, save above as `xmarks.pl`: `perl xmarks.pl <<< 'X'` I'm not sure how much smaller I can make this, but I'm sure I'll come back to it later! I might post an explanation if anyone is interested too. Handles input of `X` and non-square inputs as well now. [Answer] # Python 2, ~~755 706 699 694 678~~ 626 Bytes Expects input on stdin, with a trailing newline. The end of input is triggered with `cmd+d`. ``` import sys;a=sys.stdin.readlines();b=max;c=len;d=enumerate;e=c(b(a,key=lambda x:c(x)))-1;a=[list(line.replace('\n','').ljust(e))for line in a];R=range;f=lambda:[[i for i,x in d(h)if x=='X']for h in a+[[]]*4];q=lambda y,z:'#'if z=='X'else'+'if z in'|-+'else y;g=f();h=j=k=l=0 for m,n in d(g): if n:h=b(3-m,h);l=b(abs(n[0]-5),l);j=b(m-c(a)+4,j);k=b(n[-1]-e+6,k) o=[' ']*(l+k+e);a=[o for _ in R(h)]+[[' ']*l+p+[' ']*k for p in a]+[o for _ in R(j)];g=f() for m,x in d(a): for i in[3,2,1,-1,-2,-3]: for r in g[m+i]:x[r]=q('|',x[r]) for r in g[m]: for i in R(5,0,-1)+R(-1,-6,-1):x[r+i]=q('-',x[r+i]) for s in a:print''.join(s) ``` Full program: ``` import sys lines = sys.stdin.readlines() # pad all lines with spaces on the right maxLength = len(max(lines, key=lambda x:len(x))) - 1 # Subtract the newline lines = [list(line.replace('\n', '').ljust(maxLength)) for line in lines] def findX(): global xs xs = [[i for i, ltr in enumerate(line) if ltr == 'X'] for line in lines+[[]]*4] # add sufficient padding to the edges to prevent wrap findX() top,bottom,right,left=0,0,0,0 for ind, item in enumerate(xs): if item: top = max(3-ind, top) left = max(abs(item[0]-5), left) bottom = max(ind-len(lines)+4, bottom) right = max(item[-1]-maxLength+6, right) clear = [' '] * (left+right+maxLength) lines = [clear for _ in range(top)] + [[' ']*left + line + [' ']*right for line in lines] + [clear for _ in range(bottom)] findX() def chooseChar(expected, curr): return '#' if curr == 'X' else ('+' if curr in '|-+' else expected) for ind, x in enumerate(lines): # try: for i in [3, 2, 1, -1, -2, -3]: for elem in xs[ind+i]: x[elem] = chooseChar('|', x[elem]) for elem in xs[ind]: for i in [5, 4, 3, 2, 1, -1, -2, -3, -4, -5]: x[elem+i] = chooseChar('-', x[elem+i]) # except:f for line in lines: print(''.join(line)) ``` I'm sure that a lot more golfing could be done on this (since I'm still learning python), so any help is appreciated. ## Edits 1. Shaved about 50 bytes from `findX` by using for comprehensions 2. Saved 7 bytes thanks to @mbomb007's suggestion about using `range` instead of a literal array 3. Removed 5 bytes by changing `findX` to a lambda 4. Saved 15 bytes by extending `xs` by 4 and eliminating the `try-except` block 5. Shaved 2 more by using tabs instead of spaces 6. Removed 5 bytes by using `h=i=j=k=l=0` instead of `h,j,k,l=0,0,0,0` 7. Thanks to @mbomb007, I removed about 40 more bytes from `chooseChar` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/171309/edit). Closed 5 years ago. [Improve this question](/posts/171309/edit) # Textbattles --- Textbattles is is strategy game about, well, text. It consists of a 10x10 grid, where each player has a position on the grid. When it is a player's turn, they can decide whether to move a step in any direction on the grid, or just stay where they are. If a player moves into another player's spot, they are both put in a battle with each other. They both will generate a piece of text. After generating it, they get a "penalty" stored, which = time in nanoseconds to generate / 80000. Then, each player sends the first *n* characters of their text to eachother, where *n* is the penalty. After that, both player have two choices: 1. Guess the other player's text, using the portion given to them. 2. Surrender (this can also be done after trying to guess multiple times) Surrendering is an instant elimination from the game, guessing before the other player eliminates the other player. To participate in the challenge you will have to code your player, here is how your code should look in **Java**: ``` public class MyPlayer extends Player { @Override public Move move() { return Move.LEFT, Move.RIGHT, Move.UP, Move.DOWN, or Move.NONE } @Override public void guess(String clue, Checker checker) { if(checker.guess("I think this is the right one!")) { // Got it right! return; } checker.surrender(); } @Override public String generate(Deducter ded) { ded.use(); // Read below return "SecretCode404"; } // Other methods you have access to: getGrid: a 2d-array of booleans, each element being true if there is a player there, getRandom: a java.util.Random object to generate random numbers, by the rules of this challenge, you aren't allowed to use any other random number generator than this one. } ``` Each time you win a battle, you get a *point*, and the next time you get in to a battle, you have the choice to deduct the amount of points from your penalty as shown above. --- # FAQ --- * What stops me from adding the entire Lorem Ipsum to my text? Other people can look at your answer and compensate for it by adding Lorem Ipsum too. * What if none of the two battlers never find eachother's text? They will. In most cases anyways, if they don't find it in 5 minutes, it is considered a tie and nobody is eliminated * What if all players keep avoiding eachother? There are random events that teleport players to eachother. ]
[Question] [ **This question already has answers here**: [Write an interactive Deadfish interpreter](/questions/16124/write-an-interactive-deadfish-interpreter) (36 answers) Closed 6 years ago. > > Please participate in the ***[meta discussion about reopening this challenge](https://codegolf.meta.stackexchange.com/q/14830/59487)*** before casting a vote. > > > # Introduction This challenge was inspired by [semicolon-#](/questions/tagged/semicolon-%23 "show questions tagged 'semicolon-#'"). [Deadfish](http://esolangs.org/wiki/Deadfish) is a non-Turing-complete programming language, created by Jonathan Todd Skinner. It has an accumulator register and contains 4 commands, `i`, `d`, `s`, and `o`, standing for increment, decrement, square, and output, respectively. While this seems simple enough, the original implementation has some quirks that must be present in your interpreter. Unlike a similar challenge [here](https://codegolf.stackexchange.com/questions/16124/write-an-interactive-deadfish-interpreter), this does not require the interpreter to be interactive. # Challenge The challenge is to write a fully functional Deadfish interpreter, quirks included. The following requirements must be met: * The accumulator must be more than 8 bits wide. * When an `i` is encountered, increment the accumulator by 1. * When a `d` is encountered, decrement the accumulator by 1. * When an `s` is encountered, square the value of the accumulator. * When an `o` is encountered, print the value of the accumulator along with a newline. * When any other character is encountered, including control characters and whitespace but not a newline, print a newline. * If and only if the accumulator equals `-1` or `256`, set the accumulator to `0`. # Test cases From the [esolangs article](http://esolangs.org/wiki/Deadfish): ``` iissso -> 0 diissisdo -> 288 iissisdddddddddddddddddddddddddddddddddo -> 0 ``` # Rules * Input may be accepted through STDIN or as argument(s). * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins [Answer] # [Proton](https://github.com/alexander-liao/proton), 114 bytes ``` a=0s={"i":(a=>a+1),"d":(a=>a-1),"s":(a=>a*a),"o":(a=>[print(a),a][1])}for i:input(){a=s[i](a)if a in[-1,256]{a=0}} ``` [Try it online!](https://tio.run/##LclBCsMgEEbhq4grbROIhXYRsBcRFwMS@DeOOHYVPLu1NMvvvVK5cR6D/Cb@1NC7If@mu7OLThfWH@TCjSb4j1AqcjOzUAwu2n5wVdiRy6cZe5KXgDg3DkUKOaxueTxfcY6t9zESIAJJ/AU "Proton – Try It Online") The fact that this even parses correctly demonstrates how weird Proton 1 is o\_O ]
[Question] [ This challenge is to score a Cribbage hand. If you don't play Cribbage, you've got some learning to do. We play with a standard poker deck, and a hand consists of four cards plus the "up card". There are two types of hand: normal, and a 'crib hand'. Cards come in the format `vs` where `v` is one of: `A23456789TJQK` (T for ten) and `s` is one of `SCDH`. A hand will be given in the form (for example) ``` AS 2D 3H JS | 4S ``` where `4S` is the up card. A crib hand will have the format ``` JD 3C 4H 5H | 5S ! ``` Face cards have a value of 10, and the ace has a value of 1. Scoring is performed as follows. * Fifteens: for each subset of five cards whose sum is 15, add two points. * Pairs: for each pair of cards with the same rank (not value), add two points. * Runs: for each maximal run of consecutive cards of length longer than 2, add the length of the run in points. * Flush: if all five cards are the same suit, add five points. Otherwise, if all but the up card are the same suit, add four points. If this is a crib hand, the four-point variant is not counted. * Nobs: if there is a jack in hand with the same suit of the up card, add one point. **Notes:** * Triples and fours of a kind are not special -- there are three pairs in a triple, so a triple is worth 6 points. * Runs can overlap. For example, `AS AH 2D 3C | 2C` (a double double run) has four runs of length 3 and two pair, so is worth 3+3+3+3+2+2 = 16 points. * Only maximal runs are counted, so `KS QD JD TC | 9S` is worth 5 points, since it is a run of 5. The sub-runs are not counted. **House Rule:** It's impossible to score 19 points in a hand. Instead of zero, report a score of 19. **Examples:** ``` 5S 5H 5D JS | KS 21 AS 2D 3H JS | 4S ! 9 JD 3C 4H 5H | 5S 12 9S 8S 7S 6S | 5H ! 9 9S 8S 7S 6S | 5H 13 8D 7D 6D 5D | 4D ! 14 8D 7D 6D 5D | 4D 14 AD KD 3C QD | 6D 19 ``` This is code golf. Shortest solution wins. [Answer] ## C, 364 388 chars It's big and ugly (though not as big as it once was): ``` char*L="CA23456789TJQKDHS",b[20],p[15],r[5],s[5],v,i=4,t,m,q; g(j){++p[r[i]=strchr(L,b[j])-L];s[i]=strchr(L,b[j+1])-L;} f(j,u){u==15?v+=2:++j<5&&f(j,u,f(j,u+(r[j]>9?10:r[j])));} main(){gets(b);for(g(14);i--;r[i]^11|s[i]^s[4]||++v)g(i*3); for(f(i,0);++i<15;v+=q?q*q-q:t>2?t*m:0,t=q?t+1:0,m=q?m*q:1)q=p[i]; while(++t<5&&s[t]==*s);v+=t>4-!b[16]?t:0;printf("%d\n",v?v:19);} ``` (Line breaks were added to make it easier to read; those aren't included in the above tally.) The problem description didn't specify if the code needed to check for invalid input, so naturally I assumed that the program was free to misbehave at will if the input, say, contained extra whitespace. Here's the ungolfed version: ``` #include <stdio.h> #include <string.h> /* A-K correspond to values 1-13. Suit values are arbitrary. */ static char const *symbols="CA23456789TJQKDHS"; /* Used as both an input buffer and to bucket cards by rank. */ static char buf[20]; /* The cards. */ static int rank[5], suit[5]; /* The cards broken down by rank. */ static int buckets[15]; static int score; static int touching, matching, i; /* Read card number i from buf at position j. */ static void getcard(int j) { rank[i] = strchr(symbols, buf[j]) - symbols; suit[i] = strchr(symbols, buf[j+1]) - symbols; ++buckets[rank[i]; } /* Recursively find all combinations that add up to fifteen. */ static void fifteens(int j, int total) { for ( ; j < 5 ; ++j) { int subtotal = total + (rank[j] > 9 ? 10 : rank[j]); if (subtotal == 15) score += 2; else if (subtotal < 15) fifteens(j + 1, subtotal); } } int main(void) { fgets(buf, sizeof buf, stdin); score = 0; /* Read cards from buf */ for (i = 0 ; i < 4 ; ++i) getcard(i * 3); getcard(14); /* Score fifteens */ fifteens(0, 0); /* Score any runs and/or pairs */ touching = 0; matching = 1; for (i = 1 ; i < 15 ; ++i) { if (buckets[i]) { score += buckets[i] * (buckets[i] - 1); ++touching; matching *= buckets[i]; } else { if (touching > 2) score += touching * matching; touching = 0; matching = 1; } } /* Check for flush */ for (i = 1 ; i < 5 && suit[i] == suit[0] ; ++i) ; if (i >= (buf[17] == '!' ? 5 : 4)) score += i; /* Check for hisnob */ for (i = 0 ; i < 4 ; ++i) if (rank[i] == 11 && suit[i] == suit[4]) ++score; printf("%d\n", score ? score : 19); return 0; } ``` [Answer] ## Ruby 1.9, 359 356 It's far too long - almost as much as the C solution. ``` R='A23456789TJQK' y=gets f=y.scan /\w+/ o=f.map(&:chr).sort_by{|k|R.index k} s=0 2.upto(5){|i|o.combination(i){|j|t=0 j.map{|k|t+=k==?A?1:k<?:?k.hex: 10} (t==15||i<3&&j.uniq!)&&s+=2}} m=n=l=1 (o+[z=?_]).map{|k|k[z]?n+=1:R[z+k]?(m*=n l+=n=1):(l>2&&s+=l*m*n l=n=m=1) z=k} x=f.take_while{|k|k[y[1]]}.size x>(y[?!]?4:3)&&s+=x y[?J+f[4][1]+' ']&&s+=1 p s>0?s:19 ``` [Answer] # Something to begin with.. Ruby, ~~422 365 355~~ 352 ``` c=gets a,b=c.scan(/(\w)(\w)/).transpose f=->x{x.uniq.size<2} s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0 c[/J(.).*\1 ?!?$/]&&s+=1 s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0 a.map{|x|s+=a.count(x)-1} 2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}} p s<1?19:s ``` Slightly ungolfed: ``` def t(c) s=0 if c.scan(/[SDHC]/).uniq.size<2 # Flush s+=5 elsif c[0..9].scan(/[SDHC]/).uniq.size<2 && c[-1]!=?! # Flush s+=4 end s+=1 if c =~ /J(.).*(\1$|\1\s.$)/ # Nobs c=c.scan(/[^ \|]+/).map{|x|x[0]}[0..4] d = (3..5).map{|i|c.permutation(i).map{|x| 'A23456789TJQK'.include?(x*'') ? i : 0}.inject(:+)}.reverse.find{|x|x>0} || 0# Runs s+=d c.map{|x|s+=c.count(x)-1} # Pairs c.map!{|x|x.tr('A','1').gsub(/[JQK]/,'10').to_i} (2..5).map{|i|s+=2*c.combination(i).count{|x|15==x.inject(:+)}} # 15s s<1 ? 19 : s end ``` Unit tests for golfed version: ``` require "test/unit" def t(c) c=gets a,b=c.scan(/(\w)(\w)/).transpose f=->x{x.uniq.size<2} s=f[b]?5:!c[/!/]&f[b[0,4]]?4:0 c[/J(.).*\1 ?!?$/]&&s+=1 s+=[5,4,3].map{|i|a.permutation(i).map{|x|'A23456789TJQK'[x*'']?i:0}.inject :+}.find{|x|x>0}||0 a.map{|x|s+=a.count(x)-1} 2.upto(5){|i|s+=2*a.map{|x|x.tr(?A,?1).sub(/\D/,'10').to_i}.combination(i).count{|x|x.inject(:+)==15}} p s<1?19:s end class Test1 < Test::Unit::TestCase def test_simple assert_equal 21, t("5S 5H 5D JS | KS") assert_equal 21, t("JS 5H 5D 5S | KS") assert_equal 12, t("JD 3C 4H 5H | 5S") assert_equal 13, t("9S 8S 7S 6S | 5H") assert_equal 14, t("8D 7D 6D 5D | 4D") assert_equal 19, t("AD KD 3C QD | 6D") assert_equal 9, t("AS 2D 3H JS | 4S !") assert_equal 9, t("JS 2D 3H AS | 4S !") assert_equal 14, t("8D 7D 6D 5D | 4D !") assert_equal 9, t("9S 8S 7S 6S | 5H !") end end ``` Results: ``` % ruby ./crib.rb Run options: # Running tests: 21 21 12 13 14 19 9 9 14 9 . Finished tests in 0.014529s, 68.8281 tests/s, 688.2813 assertions/s. 1 tests, 10 assertions, 0 failures, 0 errors, 0 skips ``` [Answer] # Python, 629 characters I'm only posting mine because no one else has. It's pretty long :( ``` g=range i=raw_input().split() r,u=zip(*[tuple(x)for x in i if x not in'!|']) v=map(int,[((x,10)[x in'TJQK'],1)[x=='A']for x in r]) z=list(set(map(int,[(x,dict(zip('ATJQK',[1,10,11,12,13])).get(x))[x in'ATJQK']for x in r]))) z.sort() z=[-1]*(5-len(z))+z s=p=l=0 for a in g(5): for b in g(a+1,5): s+=2*(v[a]+v[b]==15) p+=2*(r[a]==r[b]) if z[a:b+1]==g(z[a],z[b]+1)and b-a>1:l=max(l,b+1-a) for c in g(b+1,5):s+=2*(v[a]+v[b]+v[c]==15) for d in g(5):s+=2*(sum(v)-v[d]==15) n=len(set(u)) s+=4*(n==2 and u[-1] not in u[:4] and i[-1]!='!')+5*(n<2)+('J'+u[4]in i[:4])+2*(sum(v)==15)+p+((l*3,l*p)[p<5]or l) print(s,19)[s<1] ``` [Answer] ### GolfScript, 187 178 174 characters ``` :c"J"c{"SCDH"?)},1/:s-1=+/,([s)-!5*s);)-!4*c"!"?)!*]$-1=+0.14,{c{"A23456789TJQK"?)}%{},:v\{=}+,,.{@*\)}{;.2>**+1 0}if}/;;5-v{{=+}+v\/}/[0]v{.9>{;10}*{1$+}+%}/{15=},,2*+.!19*+ ``` Since I never played cribbage I don't know any fancy scoring tricks. Therefore I thought the only way to compete (at least a little bit) is using a golf language. The code is pretty plain GolfScript, the test cases can be found [here](http://golfscript.apphb.com/?c=ewo6YyJKImN7IlNDREgiPyl9LDEvOnMtMT0rLywoW3MpLSE1KnMpOyktITQqYyIhIj8pISpdJC0xPSswLjE0LHtjeyJBMjM0NTY3ODlUSlFLIj8pfSV7fSw6dlx7PX0rLCwue0AqXCl9ezsuMj4qKisxIDB9aWZ9Lzs7NS12e3s9K30rdlwvfS9bMF12ey45Pns7MTB9KnsxJCt9KyV9L3sxNT19LCwyKisuITE5KisKfTpDT0RFOwoKOyI1UyA1SCA1RCBKUyB8IEtTIglDT0RFIHAJIyAyMQo7IkFTIDJEIDNIIEpTIHwgNFMgISIJQ09ERSBwCSMgOQo7IkpEIDNDIDRIIDVIIHwgNVMiCUNPREUgcAkjIDEyCjsiOVMgOFMgN1MgNlMgfCA1SCAhIglDT0RFIHAJIyA5CjsiOVMgOFMgN1MgNlMgfCA1SCIJQ09ERSBwCSMgMTMKOyI4RCA3RCA2RCA1RCB8IDREICEiCUNPREUgcAkjIDE0CjsiOEQgN0QgNkQgNUQgfCA0RCIJQ09ERSBwCSMgMTQKOyJBRCBLRCAzQyBRRCB8IDZEIglDT0RFIHAJIyAxOQo%3D). The code in a more readable fashion (*reformatted and ungolfed a little*): ``` # Save cards to <c> :c; # Is it a non-crib hand? <r> c"!"?)!:r; # Values go to <v> c{"A23456789TJQK"?)}%{},:v; # Suits go to <s> c{"SCDH"?)},1/:s; # Print score for Fifteens [0]v{.9>{;10}*{1$+}+%}/{15=},,2* .p # Print score for Pairs -5v{{=+}+v\/}/ .p # Print score for Runs 0..14,{v\{=}+,,.{*\)\}{;\.2>**+0 1}if}/;; .p # Print score for Flush [s)-!5*s);)-!4*r*]$-1= .p # And finally print the score for Nobs c"J"s-1=+/,( .p # Sum up the sub-scores and if score is zero set to 19 ++++ .!19*+ ``` *Edit:* Changed logic for fifteens and flushes. [Answer] # Python 2, ~~606~~ 584 bytes Saved 22 bytes due to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)'s golfing. ``` from itertools import* s,S,C,E=sum,sorted,combinations,enumerate def f(a):a=a.split();a.pop(4);e=a.pop(5)if a[-1]<"$"else 0;b=S("A23456789TJQK".index(i)for i,j in a);d=S(set(b));h=[j for i,j in a];z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2+s(2for i,j in C(b,2)if i==j)+[4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2)+(a[4][1]in[j for i,j in a[:4]if i=="J"])+s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2]);return z or 19 ``` [Try it online!](https://tio.run/##fZLNbqMwFIX3eYpbNAs7caNAIX@EkapQKUpWFbOzvIDgNCZgkDESqfruGUw6UdLF7Ozz3eN7fO3qrI@ldC6XgyoLEJorXZZ5DaKoSqWHg5pEZE3egropSN0pPCX7skiEjLUoZU24bAquYs0HKT/AAcV4GQfxuK5yoRH243FVVsjFPg@uSw@LA8T02WYr65fF85rDxE@CCFmvzovrTWfzxZ/t@84aC5nyFgl8KBUIkoGQEGM/7SprrlGCsX8MaAb3mPmfQc4lojU69T5lZBXLD46mvXAywhpRak/IaWQzelrZE3YjCSPK5DP@ILA9hofOqEbOXZM1SohjakQQZHhE3SHiKxsTj1HT2mQ7Yrxy2BDd9nTpMqPhEYqpy6jNhPwR3ZRcD7W2FsNdU8XTZs9RHhdJGkNLzst2eCY0Ge/LRurvC/apiy6m6VX0UveIkqbdCFq6FAwv/y1GWX/P1uA@ai5qjTj@HjA3J32osqmSM8qexX26N5RizNiD0poZZL8dhn3FdaMkfELH7cWlUkLq7idYXgTeBrwQthF8wS6y8ODGXiNwQnjZXJkbwdM93XZoDe7G@L/Ae3AuIphHMItgapxdwdP/6D2bhzALYRqaSF3P8NH5kz6kDWHXR3o3bNqxy18 "Python 2 – Try It Online") Slightly shorter than [grc](https://codegolf.stackexchange.com/a/5581/73368)'s answer, and takes a different route to get there. ## Explanation: ``` # import everything from "itertools" library. We only need "combinations" and "groupby". from itertools import* # alias functions to shorter names s,S,C,E=sum,sorted,combinations,enumerate # function f which takes the hand+up card+crib string as its argument def f(a): # convert space-separated string into list of items. a=a.split() # remove the 4th index, which is always "|". a.pop(4) # change golfed by Jo King # if the final item in the list is a "!" (if it is <"$"), remove it from the list and assign it to variable "e". # otherwise, assign 0 to variable "e". # a non-empty string will evaluate to True and 0 will evaluate to False in IF checks later. e=a.pop(5)if a[-1]<"$"else 0 # for each card in the list, split the identifiers into the value(i) and the suit(j). # return the value's index in the string "A23456789TJQK". # so, ["5S", "5H", "5D", "JS", "KS"] will return [4, 4, 4, 10, 12]. # using the aliased built-in function sorted(), sort the list numerically ascending. b=S("A23456789TJQK".index(i)for i,j in a) # get the unique items in b, then sort the result numerically ascending. d=S(set(b)) # for each card in the list, split the identifiers into the value(i) and the suit(j). # return the suits. h=[j for i,j in a] # fifteens # changes golfed by Jo King # generate pairs of (10, value + 1) for all cards (since they are zero-indexed) # since True and False evaluate to 1 and 0 in python, return 10 if k>=10 # and reduce all values >10 to 10 # get all unique combinations of cards for 5 cards, 4 cards, 3 cards, 2 cards, and 1 card # add the values of all unique combinations, and return any that equal 15 # multiply the number of returned 15s by 2 for score z=len([s(k)for r in range(6)for k in C([[10,k+1][k<10]for k in b],r)if s(k)==15])*2 + # pairs # using itertools.combinations, get all unique combinations of cards into groups of 2. # then, add 2 for each pair where both cards have an identical value. s(2for i,j in C(b,2)if i==j) + # flush # changes golfed by Jo King # using list indexing # [4 * (0 if crib else 1), 5], get item at index [0 if more than one suit in hand+up card else 1] # -> 4 if not crib and not all suits same # -> 5 if all cards same # -> 0 otherwise # * (0 if more than one suit in hand else 1) # -> 4 * 0 if not crib and not all suits same # -> 4 * 1 if not crib and all suits same # -> 5 * 1 if all cards same # -> 0 otherwise [4*(e<1),5][len(set(h))<2]*(len(set(h[:4]))<2) + # nobs # check if the suit of the 5th card (4, zero-indexed) matches the suit of any of the other 4 cards, and if it does is that card a Jack (a[4][1]in[j for i,j in a[:4]if i=="J"]) + # runs s(reduce(lambda x,y:x*y,[b.count(k)for k in m])*len(m)for m in[d[s(x[:i]):s(x[:i])+j]for x in[[len(list(e))for i,e in groupby(j-i for i,j in E(d))]]for i,j in E(x)if j>2]) # since only 0 evaluates to false, iff z==0 return 19, else return z. print z or 19 ``` ## Explanation for runs logic specifically: ``` # for each index and value in the list, add the value minus the index # since the list is sorted and reduced to unique values, this means adjacent values will all be the same value after offset # ex: "JD 3C 4H 5H | 5S" -> [2, 3, 4, 10] - > [2, 2, 2, 7] z = [] for i,j in enumerate(d): z.append(j-i) # group the values by unique value # then add the length of the groups to the list # ex: [2, 2, 2, 7] -> [2:[2,2,2], 7:[7]] # [2:[2,2,2], 7:[7]] -> [[3], [1]] w = [] for i,e in groupby(z): w.append([len(list(e))]) # list is double-nested so that the combined list comprehension leaves "x" available in both places it is needed z = [] for x in w: for i,j in enumerate(x): if j>2: # if the group length is larger than 2 # slice the list of unique card values to obtain only run values # since the run can be anywhere in the list, sum the preceding lengths to find the start and end index a = d[ sum(x[:i]) : sum(x[:i])+j ] z.append(a) w = [] for m in z: # get the number of times the value is in the entire hand # ex: "JD 3C 4H 5H | 5S" -> [2,3,4,4,10] and (2,3,4) -> [1, 1, 2] a = [b.count(k)for k in m] # multiply all values together # [1, 1, 2] = 1*1*2 = 2 a = reduce(lambda x,y:x*y, a) # length of the run * number of duplicate values a *= len(m) w.append(a) # sum the results of the runs return sum(w) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 106 bytes ``` Çí╬Δ╓↔╥.L§º♦½┌§└─»◄G≤n▒HJ♀p$¼♥,Q¢▲»Δ÷♠º≈r↑Vo\b■┌4Üé∟]e:┬A½f║J4σ↔└ΓW6O?╧φ¡╫╠├√├ùß5₧k%5ê╜ò/Φ/7w╠█91I◘┬n≥ìk♂╪ ``` [Run and debug online!](https://staxlang.xyz/#p=80a1ceffd61dd22e4c15a704abda15c0c4af1147f36eb1484a0c7024ac032c519b1eaffff606a7f77218566f5c62feda349a821c5d653ac241ab66ba4a34e51dc0e257364f3fcfedadd7ccc3fbc397e1359e6b253588bd952fe82f3777ccdb39314908c26ef28d6b0bd8&i=5S+5H+5D+JS+%7C+KS%0AAS+2D+3H+JS+%7C+4S+%21%0AJD+3C+4H+5H+%7C+5S%0A9S+8S+7S+6S+%7C+5H+%21%0A9S+8S+7S+6S+%7C+5H%0A8D+7D+6D+5D+%7C+4D+%21%0A8D+7D+6D+5D+%7C+4D%0AAD+KD+3C+QD+%7C+6D&a=1&m=2) Bonus for CP437: See those suits symbol in the packed Stax? Too bad that the clubs do not appear ... The ASCII equivalent is ``` jc%7<~6(4|@Y{h"A23456789TJQK"I^mXS{{A|mm|+15=_%2=_:u*+f%HxS{{o:-u1]=f{%mc3+|Msn#*+y{H"SHCD"ImY:uc5*s!yNd:u;**HH++yN|Ixs@11#+c19? ``` ## Explanation ``` jc%7<~6(4|@Y...X...Y...c19? j Split on space c%7<~ Is it a crib hand? Put it on input stack for later use 6( Remove "!" if it exists 4|@ Remove "|" Y Store list of cards in y ...X Store ranks in x ... Perform scoring for ranks Y Store suits in y ... Perform scoring for suits c19? If the score is 0, change it to 19 {h"..."I^mX { m Map each two character string to h The first character "..."I^ 1-based index of the character in the string S{{A|mm|+15=_%2=_:u*+f%H S Powerset { f%H Twice the number of elements that satisfy the predicate {A|mm Value of card. Take the minimum of the rank and 10 |+15= Sum of values equal 15 (*) _%2= Length is 2 (**) _:u All elements are the same (***) *+ ( (***) and (**) ) or (*) xS{{o:-u1]=f{%mc3+|Msn#*+ xS Powerset of ranks { f Filter with predicate {o Sort :-u Unique differences between elements 1]= Is [1] {%mc Length of all runs 3+|M Maximum of all the lengths and 3 sn# Number of runs with maximal length * Multiplied by its length + Add to score y{H"SHCD"ImY y{ mY For each two character string H"SHCD"I 0-based index of the second character in the string "SHCD" :uc5*s!yNd:u;**HH++ :uc5* 5 points if all cards have same suit s! Not all cards have same suit (#) yNd:u First four cards have same suit (##) ; Not a crib hand (###) **HH++ 4 points if (#) and (##) and (###), add to score yN|Ixs@11#+ yN|I Index of cards with the same suit of last card (not including itself) xs@ The rank at these indices 11# Number of Jacks with the same suit of last card + Add to score ``` ]
[Question] [ As part of its compression algorithm, the JPEG standard unrolls a matrix into a vector along antidiagonals of alternating direction: [![enter image description here](https://i.stack.imgur.com/KU5Iu.png)](https://i.stack.imgur.com/KU5Iu.png) Your task is to take the unrolled vector along with the matrix dimensions and reconstruct the corresponding matrix. As an example: ``` [1, 2, 5, 9, 6, 3, 4, 7, 1, 2, 8, 3], 4, 3 ``` should yield ``` [1 2 3 4 5 6 7 8 9 1 2 3] ``` whereas dimensions `6, 2` would give ``` [1 2 6 3 1 2 5 9 4 7 8 3] ``` ## Rules You may choose to take only one of the dimensions as input. The individual inputs can be taken in any order. You may assume that the width and height are positive and valid for the given vector length. You may assume that the vector elements are positive integers less than `10`. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. The input vector may be given in any convenient, unambiguous, flat list or string format. The output matrix may be in any convenient, unambiguous, nested list or string format, or as a flat list along with both matrix dimensions. (Or, of course, as a matrix type if your language has those.) Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases Each test case is of the form `vector width height => matrix`. ``` [1] 1 1 => [[1]] [1 2 3 1] 2 2 => [[1 2] [3 1]] [1 2 3 1] 4 1 => [[1 2 3 1]] [1 2 5 9 6 3 4 7 1 2 8 3] 3 4 => [[1 2 3] [5 6 4] [9 7 8] [1 2 3]] [1 2 5 9 6 3 4 7 1 2 8 3] 4 3 => [[1 2 3 4] [5 6 7 8] [9 1 2 3]] [1 2 5 9 6 3 4 7 1 2 8 3] 6 2 => [[1 2 6 3 1 2] [5 9 4 7 8 3]] [1 2 5 9 6 3 4 7 1 2 8 3] 12 1 => [[1 2 5 9 6 3 4 7 1 2 8 3]] [1 2 5 9 6 3 4 7 1 2 8 3] 1 12 => [[1] [2] [5] [9] [6] [3] [4] [7] [1] [2] [8] [3]] ``` ## Related Challenges * [Zigzagify a Matrix](https://codegolf.stackexchange.com/q/75587/8478) (the somewhat simpler inverse transformation) * [Rotate the anti-diagonals](https://codegolf.stackexchange.com/q/63755/8478) [Answer] # Jelly, ~~18~~ 13 bytes ``` pS€żị"¥pỤỤị⁵s ``` Takes number of rows, number of columns and a flat list as separate command-line arguments. My code is almost identical to [the one in the twin challenge](https://codegolf.stackexchange.com/a/75590). The only differences are an additional `Ụ` (which inverts the permutation of the indices) and an `s` (to split the output into a 2D array). [Try it online!](http://jelly.tryitonline.net/#code=cFPigqzFvOG7iyLCpXDhu6Thu6Thu4vigbVz&input=&args=NA+Mw+WzEsIDIsIDUsIDksIDYsIDMsIDQsIDcsIDEsIDIsIDgsIDNd) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 29 bytes ``` :!i:+-1y^8MtsQ/*-X:4#S2$S1GZC ``` Input is `height`, `width`, `vector` separated by newlines. This reuses part of the code in [my answer to the related challenge](https://codegolf.stackexchange.com/a/75595/36398). [**Try it online!**](http://matl.tryitonline.net/#code=OiFpOistMXleOE10c1EvKi1YOjQjUzIkUzFHWkM&input=Mwo0ClsxIDIgNSA5IDYgMyA0IDcgMSAyIDggM10) ### Explanation ``` :! % take number of rows, r, as input. Generate column vector [1;2;...;r] i: % take number of columns, c, as input. Generate row vector [1,2,...,c] + % add with broadcast. Gives 2D array -1 % push -1 y^ % duplicate previous 2D array. Compute -1 raised to that 8M % push [1;2;...;r] again tsQ/ % divide by its sum plus 1 * % multiply - % subtract X: % linearize 2D array into column array 4#S % sort and push the indices of the sorting. Gives a column vector 2$S % take vector as input. Sort it according to previous column vector 1G % push r ZC % reshape into columns of r elements ``` [Answer] # J, 24 bytes ``` ]$({~[:/:@;[:<@|.`</.i.) ``` Also uses the oblique adverb `/.` to perform zigzagify as in the J [answer](https://codegolf.stackexchange.com/a/75594/6710) from that [challenge](https://codegolf.stackexchange.com/questions/75587/zigzagify-a-matrix). ## Usage Input is with the array on the LHS and the dimensions `[height, width]` on the RHS. ``` f =: ]$({~[:/:@;[:<@|.`</.i.) 1 f 1 1 1 1 2 3 1 f 2 2 1 2 3 1 1 2 5 9 6 3 4 7 1 2 8 3 f 4 3 1 2 3 5 6 4 9 7 8 1 2 3 1 2 5 9 6 3 4 7 1 2 8 3 f 3 4 1 2 3 4 5 6 7 8 9 1 2 3 1 2 5 9 6 3 4 7 1 2 8 3 f 2 6 1 2 6 3 1 2 5 9 4 7 8 3 1 2 5 9 6 3 4 7 1 2 8 3 f 1 12 1 2 5 9 6 3 4 7 1 2 8 3 1 2 5 9 6 3 4 7 1 2 8 3 f 12 1 1 2 5 9 6 3 4 7 1 2 8 3 ``` ## Explanation ``` ]$({~[:/:@;[:<@|.`</.i.) Input: list A (LHS), dimensions D (RHS) i. Range shaped to D [:<@|.`</. Zigzagify that matrix [: ; Raze the boxes to get a zigzagify permutation /:@ Invert that permutation to get an unzigzagify permutation {~ Apply that permutation to A ] Get D $ Shape that permutation to D and return ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes ``` {y#x@<,/((#c)#(|:;::))@'c:.=+/!y:|y} ``` [Try it online!](https://ngn.codeberg.page/k#eJyFj1EKgzAQRP/3FFv8MKGhsjFa3bTgT2/gDQTPUNH27N0VCwrVfu68TGam53FIns3NZcYknU3MxJHZ2ibt+HI/Z6eBp+EF0LIxjiIhWUA0hB5zpOjRb+6w4gXWWIoa8Ip6V5hHuQ55wPyQl6u8X5z8nwIywFsL8GDjHMH8UFqpyS0jYJkTC3GHWIu7irNiv0hkhQpq3CDN0y81W3OrGbmdOkLSHaQd332TpS18APpFSKA=) Basically the same as [Zagify a matrix](https://codegolf.stackexchange.com/a/254384/111844) but with a grade. ]
[Question] [ # Background The nuclear industry has term, [SCRAM](https://www.nrc.gov/reading-rm/basic-ref/glossary/scram.html), used to describe a quick shutdown of the reactor. There's a fun myth that it stands for "Safety Control Rod Ax Man," the role which served to shut down the Chicago Pile if it got too hot by literally cutting a rope with an ax (although this was [debunked](https://public-blog.nrc-gateway.gov/2011/05/17/putting-the-axe-to-the-scram-myth/)). The US Nuclear Regulatory Commission (NRC) publishes a daily list of events at every licensed facility in the country. This includes power reactors, as well as research reactors, uranium mines, fuel fabrication facilities, and certain hospitals; we only care about power reactors. There are many possible reports, most fairly boring, but each report is given a SCRAM Code, which is what you will be searching for. One example is shown below: [![enter image description here](https://i.stack.imgur.com/FfkxE.png)](https://i.stack.imgur.com/FfkxE.png) The SCRAM Code is "A/R" to indicate it was an automatic reactor SCRAM, but other codes are possible. An "N" code indicates the event is not a SCRAM and can be ignored. Your task is to find all of the SCRAMS which occurred at US Nuclear power reactors in 2017. # Challenge * Your answer may take no input * Search through all daily event reports found [here](https://www.nrc.gov/reading-rm/doc-collections/event-status/event/2017/) * Find all reports which have a SCRAM Code other than "N" * Reports must be at facility type "Power Reactor" * Output (STDOUT, nearest equivalent, function return, or sensible alternative) each SCRAM (in chronological order), identified by Facility Name, Event Number, Event Date, and SCRAM Code. Each field must be delimited in some fashion, and each SCRAM must be delimited by a separate delimiter. Other than this, output format is flexible. * Only a sample of a minimum of 5 SCRAMS needs to be included in your answer, or you can post the full list if you'd like. * Some SCRAMs will have reports on multiple days due to follow-up reporting, your answer should weed out duplicate SCRAMs. * Some sites have multiple reactors (units) which can SCRAM separately. You should determine SCRAMs at both units, but do not need to report which unit it came from. Required behavior for multiple unit simultaneous SCRAMs is not defined. * Note that not all 365 days of the year have reports, your answer must handle this. * This challenge is Code Golf, so shortest answer wins. [Standard caveats and loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * In case the NRC changes the format of the webpage, your answer obviously doesn't need to handle this. # Sample Output ``` Field1 Field2 Field3 Field4|Field1 Field2 Field3 Field4|.... ------- Field1 Field2 Field3 Field4\n Field1 Field2 Field3 Field4\n ... ------ [["Field1","Field2","Field3","Field4"],["Field1","Field2","Field3","Field4"],...] ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/144533/edit). Closed 6 years ago. [Improve this question](/posts/144533/edit) The problem #6 of IMO 2009 reads: > > Let **a 1, a 2, a 3, ..., a n**, be distinct positive integers and let **T** be a set of n-1positive integers not containing **a 1+a 2+a 3+...+a n**, A grasshopper is to jump along the real axis, starting at the point **0** and making **n** jumps to the right with lengths **a 1, a 2, a 3, ..., a n** in some order. Prove that the order can be chosen in such a way that the grasshopper never lands on any point in **T**. > > > Your task is to replicate it. --- ## Input Two sets **S, T** positive integers, with: 1. **S** having **n** distinct elements 2. **T** having **n-1** elements not containing the sum of the numbers in **S** ## Output A montonically increasing sequence of positive integers **J = b1, b 2, b 3, ..., b n**, such that: 1. The numbers **b1, b 2-b 1, , b 3-b 2, ..., b n-b n-1** are permutation of the elements of **S** 2. **J** and **T** are disjoint --- 1. Your code should use **O(P(t))** search time, where **P(t)** is a polynomial with degree **<4** 2. This is a code golf, so shortest maintaining the rule wins. Good luck golfing ! Thanks to @MartinEnder for the suggestion ! ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 6 years ago. [Improve this question](/posts/124014/edit) ## DONT EVALUATE YET, ALMOST FINISHED, NEED A CLEAR WINNING CRITERION ## Make me rich in minecraft Minecraft is a 3D game made of blocks that you can destroy and place. There are some interesting farms you can build to provide you with game resources. In this problem, we will only have a look at pumpkin and melons farms. Here's a melon stem on the right that produced a melon block on the left. [![Melon block](https://i.stack.imgur.com/BQAQ5.png)](https://i.stack.imgur.com/BQAQ5.png) When the melon block grows, you can break it and the stem will produce another one later. Pumpkins farms have exactly the same behavior. On some servers there's an economy going on where you can sell your items such as melons and pumpkins. The motivation behind this problem is to get rich selling pumpkins and melons. --- ## Types of blocks Since we're only gonna farm melons and pumpkins, we are not gonna take a look at the couple hundreds of blocks in the game. We will just focus on: * **Dirt** : Basic block, does not impact growth rate but provides a place when pumpkins/melons can grow * **Farmland**: Tiled dirt where you can plant stems * **Hydrated farmland**: Basically farmland but with water nearby. See irrigation section just below. * **Stem**: Money making magic plant. * **Melon or pumpkin**: Things your stems grow and you sell. They will appear around the stem. **Irrigation** Water can irragate farmland to hydrated farmlands if it's close enough. The water irrigates all blocks in a 9x9 grid centered on the source. [![Irrigation](https://i.stack.imgur.com/NZuPP.jpg)](https://i.stack.imgur.com/NZuPP.jpg) Note that the water will irrigate that grid no matter what is composing it. If there is a wall all around the water, it will still irrigate a 9x9 grid. --- ## Stem behavior A stem can only grow a fruit above dirt or farmland if the space is innocupied. To grow a fruit, the stem follows a complex game mechanic. Hang out for the next part, it's getting complicated. **Game mechanic** Each second, 400 blocks are choosen at random in a `16x16x128` area, they will receive an update. When a fully grown stem is choosen, it will have a chance to grow a fruit. In the first time, the game select at random a block next to the stem (on his 4 sides, diagonals excluded). If the block choosen is dirt or farmland AND there is nothing above, it will then try to grow a fruit on this block. (Please note that if a fruit grows on a farmland, it turns it into dirt.) The chance of a fruit growing depends on the score `s` of the stem. The score is calculated as following: * If the stem is planted in an hydrated farmland, the initial value of `s` is `4`. If it is not hydrated, it is `2`. * For each farmland in a 3x3 grid centered on the stem, the score gains `0.75`. This also applies if the farmland has a stem growing in. If it's not hydrated farmland, the score gains `0.25`. The chance of trying to grow a fruit is then `1/(floor(25/s)+1)` **Overfarming penalties**: Stems don't like having neighboors. If there is another stem, of the same type only, in the 3x3 grid around it, the score `s` is halved. There is only one exception, if the stems are in a row, it's not halved. Note that if there are 8 stems around, the score is only halved once. Here's a pic to illustrate that rule, green stems have normal growth, orange ones are halved. [![Stem layouts](https://i.stack.imgur.com/tHeGO.png)](https://i.stack.imgur.com/tHeGO.png) ## An example to determine the income from a given layout [![One stem and his neighboors](https://i.stack.imgur.com/FMGXt.png)](https://i.stack.imgur.com/FMGXt.png) For this case, the stem is planted in an hydrated farmland (consider a water source nearby not represented). It is surrounded by 4 hydrated farmlands. The four others blocks are just dirt. There are 3 dirt blocks available for the fruit to grow on (the 3 on its sides), so the stem has a `3/4` chance to choose a valid spot. The stem is planted on an hydrated farmland so the score is `4`. There are 4 others farmlands in a 3x3 grid around the stem so the total score is `s = 4 + 0.75*4 = 7`. The chance to succeed the attempt is `P = 1/(floor(25/s)+1) = 1/4`. So the chance for the fruit to grow is then `3/4 * 1/4 = 3/16` Now let's calculate the average number of fruit per hour this single stem can provide. Each second the stem has a `400 /(16x16x128)` chance of being choosen. So in an hour, the block is choosen `3600x400 /(16x16x128) = 43.945` times on average. Each time it is choosen, the plant grows with a probability of `3/16`. In an hour, the stem will then provide `43.945x3/16 = 8.24` fruits on average. --- ## Rules **Money making** Each melon that grows is sold **5$**. For the minecraft fans out there, a melon block drops on average 5 melon slices each one worth 1$. Each pumpkin that grow is sold **8$**. **Specifications** * Stems can produce an infinite amount of fruits without ever breaking. * The fruit is always produced next to the stem (sides, not diagonals) on a dirt block. * The fruit is harvested instantly. Usually when the block grow, you are supposed to break it before the stem can produce another one. Here we will consider that all the fruits are harvested whenever they grow. * Since fruit production is random, we will only work with the average production. * Stems grow on farmland only but no fruit can grow above farmland (with ou without stem), since after a fruit grows it will turn farmland into dirt! Dirt is then the only valid spot for a fruit to grow on. * If a stem has another stem in a 3x3 grid, it is counted as a farmland for the score calculation. If the stem is not of the same type (like one melon and one pumpkin stem), there is no score penalties. * All stems are already in their final stage. In the game, to have a stem you need to plant a seed that will grow to its final stage and that will then stay this way and start producing fruits. We assume that when seeds are planted, they are already fully grown stems. * Water irrigates a 9x9 grid no matter what's around. So water can irrigate farms through walls. --- ## Goal In a given space, you need to design the best layout to produce the maximum amount of money per hour. **Input** You are given a grid containing 0 and # that represent the space allowed for your layout. # for occupied blocks where you can't place anything, 0 for the spot where you can place dirt/farmland/stem. **Output** Your program should return the maximum amount of money per hour you can make with this space allowed, and the layout that yields this result. The layout is composed of numbers that follow this code: * 0: Dirt block * 1: Farmland (blocked, no fruit can grow on it) * 2: Pumpkin stem * 3: Melon stem * 9: Water source --- ## Test cases Input ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Outputs ``` 325.927734375 2 0 2 0 0 3 0 3 2 0 2 0 0 3 0 9 ``` Here 0 means dirt, 1 blocked farmland, 2 pumpkin stem, 3 melon stem, 9 water. [![results](https://i.stack.imgur.com/8z93b.png)](https://i.stack.imgur.com/8z93b.png) --- ## Winning criterion Your are given txt files that corresponds to inputs. There are labelled Level-3 to Level-20, where the number represent the size of the input. The level 6 for instance is a 6x6 input grid. The goal is to find the best solutions for each layout. Since I don't have the solution to all the layouts (I could just compute the first ones in bruteforce), the goal is not to find **THE OPTIMAL** solution, but a better solutions than all the ones already found. Hence, metaheuristics and original solutions are greatly appreciated. Then, you should provide along with your solution all the results you get for each level. If any of them is above the best solution we found, it will be verified in the snippet and updated in the post. Here is the snippet that will help you building your fitness function and that will be used to verify your layouts. ``` <!DOCTYPE html> <html> <body> <p>Input your layout and select your size:</p> <textarea rows="10" cols="40" id="myTextarea">2 0 2 0 0 3 0 3 2 0 2 0 0 3 0 9</textarea><br> <select id="mySelect"> <option value="16">16</option> <option value="32">32</option> <option value="64">64</option> </select> <button onclick="DrawCanvas()">Test it</button> <img id="source" src="https://img15.hostingpics.net/pics/668575stem.png" width="65" height="33" hidden> <p>The income is: <span id="result">None</span>.<br>Scroll down to see a graphical representation of your layout.</p> <script> <!DOCTYPE html> <html> <body> <p>Input your layout:</p> <textarea rows="10" cols="40" id="myTextarea">2 0 2 0 0 3 0 3 2 0 2 0 0 3 0 9</textarea><br> <select id="mySelect"> <option value="16">16</option> <option value="32">32</option> <option value="64">64</option> </select> <button onclick="DrawCanvas()">Test it</button> <img id="source" src="https://img15.hostingpics.net/pics/546130stem.png" width="161" height="65" hidden> <p>The income is: <span id="result">None</span></p> <script> function DrawCanvas() { var s = document.getElementById("mySelect").value; var t = document.getElementById("myTextarea").value; var n = t.split("\n")[0].split(" ").length; var m = t.split("\n").length; if (n != 0 && m != 0) { var x = document.getElementById("myCanvas"); if (x) { document.getElementById("myCanvas").remove(); } var canvas = document.createElement("canvas"); canvas.id = "myCanvas"; canvas.width = s*n; canvas.height = s*m; canvas.style.border = "1px solid"; document.body.appendChild(canvas); var arr = GetLayout(t); var income = GetIncome(arr,canvas,s); document.getElementById("result").innerHTML = income; } } function DrawLayout(arr,c) { var s = document.getElementById("mySelect").value; var ctx = c.getContext("2d"); var img = document.getElementById("source"); for (var i=0;i<arr.length;i++) { for (var k=0;k<arr[i].length;k++) { if (arr[i][k] != "#") { if (arr[i][k] == 0) { ctx.drawImage(img, 0, 0,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 1) { ctx.drawImage(img,32, 0,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 2) { ctx.drawImage(img,64, 0,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 3) { ctx.drawImage(img,96, 0,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 5) { ctx.drawImage(img,32,32,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 6) { ctx.drawImage(img,64,32,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 7) { ctx.drawImage(img,96,32,32,32,s*k,s*i,s,s); } else if (arr[i][k] == 9) { ctx.drawImage(img, 0, 32,32,32,s*k,s*i,s,s); } } else { ctx.drawImage(img, 128, 0,32,32,s*k,s*i,s,s); } } } } function GetLayout(t) { var arr = t.split("\n"); for (var i=0;i<arr.length;i++) { arr[i] = arr[i].split(" "); for (var k=0;k<arr[i].length;k++) { if (arr[i][k] != "#") { arr[i][k] = parseInt(arr[i][k]); } } } return arr; } function GetIncome(arr,c) { arr = irrigate(arr); var n = arr[0].length; var m = arr.length; var s = 0; for (var i=0;i<arr.length;i++) { for (var k=0;k<arr[i].length;k++) { if (arr[i][k] == 2 || arr[i][k] == 6 ) { s += 8*EvalStem(arr,i,k,n,m); } else if (arr[i][k] == 3 || arr[i][k] == 7 ) { s += 5*EvalStem(arr,i,k,n,m); } } } DrawLayout(arr,c); console.log(s*400*3600/(16*16*128)); return s*400*3600/(16*16*128); } function EvalStem(arr,i,k,n,m){ // returns the chance of a fruit to grow var nbs = 0; var sc = 2; var half = false; var row = [1,1]; if (arr[i][k] > 5) {sc += 2; } for (var y = Math.max(i-1,0); y <= Math.min(i+1,m-1) ; y++) { for (var x = Math.max(k-1,0); x <= Math.min(k+1,n-1) ; x++) { if (x != k || y != i) { if ( arr[y][x] == 1 || arr[y][x] == 2 || arr[y][x] == 3 ) { sc += 0.25; } else if ( arr[y][x] == 5 || arr[y][x] == 6 || arr[y][x] == 7 ) { sc += 0.75; } if ( (Math.abs(x-y)%2 == 1 && (i+k)%2 == 0) || (Math.abs(x-y)%2 == 0 && (i+k)%2 == 1) ) { if ( arr[y][x] == 0 ) { nbs += 1; } if ( Math.abs(arr[y][x] - arr[i][k]) == 4 || arr[y][x] == arr[i][k] ) { if (row[0] == k+x || row[1] == i+y) { row = [x,y] } else { console.log(row, k, x, i, y); half = true; } } } else { if ( Math.abs(arr[y][x] - arr[i][k]) == 4 || arr[y][x] == arr[i][k] ) { half = true; console.log(x,y,k,i) } } } } } if (half == true) { sc /= 2.0; } console.log("STEM: "+i+","+k,"SCORE: "+sc,"NEIGHB: "+nbs,"HALVED: "+half,"CHANCE :"+ 1.0/(Math.floor(25/sc)+1) * (nbs/4.0)); return (1.0/(Math.floor(25/sc)+1) * (nbs/4.0)); } function irrigate(arr){ var n = arr[0].length; var m = arr.length; for (var i=0;i<arr.length;i++) { for (var k=0;k<arr[i].length;k++) { if (arr[i][k] == 9) { for (var y = Math.max(i-4,0); y <= Math.min(i+4,m-1) ; y++) { for (var x = Math.max(k-4,0); x <= Math.min(k+4,n-1) ; x++) { if ( arr[y][x] == 1 || arr[y][x] == 2 || arr[y][x] == 3 ) { arr[y][x] += 4; } } } } } } return arr; } Element.prototype.remove = function() { this.parentElement.removeChild(this); } NodeList.prototype.remove = HTMLCollection.prototype.remove = function() { for(var i = this.length - 1; i >= 0; i--) { if(this[i] && this[i].parentElement) { this[i].parentElement.removeChild(this[i]); } } } </script> </body> </html> ``` --- ## Levels and highscores It starts from this zip: <https://file.io/IvA6rf> ``` Level 3: 6.223 by ME Level 4: 0 Level 5: 0 Level 6: 0 Level 7: 0 Level 8: 0 Level 9: 0 Level 10: 0 Level 11: 0 Level 12: 0 Level 13: 0 Level 14: 0 Level 15: 0 Level 16: 0 Level 17: 0 Level 18: 0 Level 19: 0 Level 20: 0 ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 6 years ago. [Improve this question](/posts/123426/edit) This is a challenge about the the tricks and optimizations that can be used when golfing in CJam. CJam golfers may recognize many of the tricks involved. However, unfamiliar approaches and constructs may be involved, so take a look at the [CJam tips](https://codegolf.stackexchange.com/q/39731/61384) as well as the [CJam instruction reference](https://sourceforge.net/p/cjam/wiki/Operators) if you get stuck. Solutions may be tested on [TIO](https://tio.run/nexus/cjam) or with the [JavaScript interpreter](https://cjam.aditsu.net). **Goal:** There are 10 problems, each with a CJam snippet for you to optimize. Your goal is to create something equivalent but shorter. The reference solutions total 148 bytes. Your goal is to beat that by as much as possible. The winner will go to the submission that solves all 10 problems with the smallest total number of bytes. Tiebreaker is earlier post. **Answering:** Please spoiler your entire answer, except for your total score. It is intended that you do not look at other people's answers before submitting your own. Each submission should answer every problem and give the corresponding byte count, but feel free to use the reference implementation if you cannot improve it. **Details:** All answers will take input via the stack and output to the stack. You can assume that the input will be the only thing on the stack (or, if there is no input, the stack will be empty). **Problem 1:** Add one to every element in a list ([link](https://tio.run/nexus/cjam#izZUMFIwVjBRMI39X22oXav6P@E/AA)): ``` e# 5 bytes {1+}% ``` **Problem 2:** Given a list, create a list of partial sums. For example, `[1 2 3]` becomes `[1 3 6]` ([link](https://tio.run/nexus/cjam#izZUMFIwVjBRMI39H68Tk6iVmlpdF6NpY6Vdq/o/4T8A)): ``` e# 16 bytes _,\a*ee{~\)<:+}% ``` **Problem 3:** Create the following "times table" array (it doesn't need the whitespace, it's just there to make it look better): ``` [[1 2 3 4 5 6 7 8 9] [2 4 6 8 10 12 14 16 18] [3 6 9 12 15 18 21 24 27] [4 8 12 16 20 24 28 32 36] [5 10 15 20 25 30 35 40 45] [6 12 18 24 30 36 42 48 54] [7 14 21 28 35 42 49 56 63] [8 16 24 32 40 48 56 64 72] [9 18 27 36 45 54 63 72 81]] ``` Reference ([link](https://tio.run/nexus/cjam#@29ZrWkVYg0kQ7RqVWtV/yf8BwA)): ``` e# 15 bytes 9{):T;9{)T*}%}% ``` **Problem 4:** Add one to each element in a nested array ([link](https://tio.run/nexus/cjam#izZUMFKINlYwUYg2jVUwi1WINlewiFWwjP1fXR2fYGCrHm1bHVJbrVlrX6taaxVS9z/hPwA)): ``` e# 22 bytes {{_`0='[={T}{)}?}%}:T~ ``` **Problem 5:** Given a list with an odd number of elements, delete the center one ([link](https://tio.run/nexus/cjam#izZUMFIwVjBRMI39Hx@vY6Qf72Dj4BCuZaf9P@E/AA)): ``` e# 14 bytes __,2/_@<@@W*>+ ``` **Problem 6:** Given a list of bits (1 or 0), remove all leading zeroes ([link](https://tio.run/nexus/cjam#izZQMFAwhGIwGfs/3lDbUNnuf8J/AA)): ``` e# 6 bytes _1+1#> ``` **Problem 7:** Given a list of positive numbers, return the same list, but with every element replaced by 1 ([link](https://tio.run/nexus/cjam#izZUMFIwVjBRMFUwi/1fbW1Yq/o/4T8A)): ``` e# 5 bytes {;1}% ``` **Problem 8:** Generate the list `[1 2 3 4 5 4 3 2 1]` ([link](https://tio.run/nexus/cjam#izZUMFIwVjBRMFUwi/0fERkFYplERUbE/k/4DwA)): ``` e# 12 bytes XYZ4 5 4ZYX] ``` **Problem 9:** Generate the list `[[[0 1] [1 2] [2 0]] [[0 0] [1 1] [2 2]] [[0 2] [1 0] [2 1]]]` ([link](https://tio.run/nexus/cjam#HcjBCQBBEALBJH0o0nD5JzEr96w6mTo0glaaNsmvvTcxcN89)): ``` e# 41 bytes TX][XY][YT]][[TT][XX][YY]][[TY][XT][YX]]] ``` **Problem 10:** Take two arrays on the stack and "interleave" them, so `"foo" "bar"` becomes `"fboaor"`. You can assume the arrays have the same length ([link](https://tio.run/nexus/cjam#U0rLz1dSUEpKLFL6HxtvYKujE5OWZmul/T/hPwA)): ``` e# 12 bytes ]_0=,,\ff=:+ ``` Note: Most of this challenge was stolen from [Pyth practice](https://codegolf.stackexchange.com/q/53210/61384). ]
[Question] [ **This question already has answers here**: [Recognise Stack Exchange Sites by Their Icon](/questions/42242/recognise-stack-exchange-sites-by-their-icon) (5 answers) Closed 8 years ago. Currently, the Stack Exchange network has nearly 150 sites. These sites are as follows: ``` Computer Graphics Portuguese Language elementary OS Open Source Law Русский язык Mythology Health Stack Overflow на русском CiviCRM Woodworking Music Fans Vi and Vim Coffee Engineering Lifehacks Economics History of Science and Mathematics Emacs スタック・オーバーフロー Worldbuilding Startups Community Building Hinduism Buddhism Craft CMS Puzzling Data Science Joomla Earth Science Mathematics Educators Expatriates Arduino Software Recommendations Beer Ebooks Aviation Stack Overflow em Português Italian Language Amateur Radio Pets Tor Astronomy Space Exploration Blender Freelancing Open Data Network Engineering Reverse Engineering Tridion Sustainable Living English Language Learners Magento Anime & Manga Politics ExpressionEngine® Answers Robotics Genealogy & Family History Ask Patents Salesforce Islam Russian Language Raspberry Pi Chess Chemistry Windows Phone The Workplace Computer Science Academia Sports Martial Arts The Great Outdoors Cognitive Sciences Mathematica Poker Biology Chinese Language Movies & TV Computational Science Spanish Language LEGO® Answers History Biblical Hermeneutics Linguistics Bitcoin Christianity French Language Signal Processing Cryptography Personal Productivity Travel Gardening & Landscaping Philosophy Japanese Language German Language Mi Yodeya Software Quality Assurance & Testing Music: Practice & Theory SharePoint Parenting Motor Vehicle Maintenance & Repair Drupal Answers Physical Fitness Skeptics Project Management Quantitative Finance Programming Puzzles & Code Golf Code Review Science Fiction & Fantasy Graphic Design Database Administrators Video Production Writers Information Security Sound Design Homebrewing Physics Board & Card Games Electrical Engineering Android Enthusiasts Programmers Bicycles Role-playing Games Ask Different Theoretical Computer Science WordPress Development Unix & Linux User Experience English Language & Usage Personal Finance & Money Ask Ubuntu TeX - LaTeX Geographic Information Systems Home Improvement Mathematics Cross Validated Photography Game Development Seasoned Advice Webmasters Arqade Web Applications Stack Apps MathOverflow Super User Meta Stack Exchange Server Fault Stack Overflow ``` ## Your Task: * Write a program that prints out all of the sites in Stack Exchange, including those with non-ASCII characters (It doesn't need to be in any specific order). * The program must accept no input, and must output each site on its own line (optional leading/trailing newlines). * No standard loopholes. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program, measured in bytes, wins. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~1227~~ 1197 bytes ``` 0000000: 65 55 37 7a 2b 37 10 ee 71 0a 54 ee de 05 dc 29 4b fe eU7z+7..q.T....)K. 0000012: 44 8b 56 b4 cb e1 62 48 8e 85 05 d6 00 96 d4 be e6 05 D.V...bH.......... 0000024: 75 ce b1 77 eb ec ca 39 fb 02 d4 19 78 11 ff 00 c3 47 u..w...9....x....G 0000036: fa 29 10 3f 06 33 98 f4 63 38 7f fe f3 fc f9 9f f3 fb .).?.3..c8........ 0000048: fb f9 f3 ef e6 f7 bf ce 9f 7f 39 bf ff 6d 7e ff 61 f9 ..........9..m~.a. 000005a: fc 6c 7e ff 0d 80 da a9 c8 70 2d a4 76 6a 4a dc 06 7d .l~......p-.vjJ..} 000006c: 4e 46 bc da 71 26 78 31 fa c0 a5 71 1b 85 62 8a 90 49 NF..q&x1...q..b..I 000007e: cd fa 25 dd 23 37 82 7e 30 ad 38 8f f5 2d dc a0 76 e2 ..%.#7.~0.8..-..v. 0000090: ad de 97 e1 90 03 bb 54 76 7d 4a 80 b1 e0 ab 41 eb 52 .......Tv}J....A.R 00000a2: 0b 98 82 77 be ee d4 ce 44 28 89 77 6a 97 39 a8 5d 19 ...w....D(.wj.9.]. 00000b4: 58 a9 c8 ea 63 0e 35 3b 6e 93 54 11 d2 aa ab 2c 67 e0 X...c.5;n.T....,g. 00000c6: ad 1f 75 58 53 e5 05 36 96 9d c9 66 9e 82 41 40 7b 79 ..uXS..6...f..A@{y 00000d8: 39 a2 3a ab b6 c6 8c 25 d6 6a 6f 8c ac e0 ae cb 28 46 9.:....%.jo.....(F 00000ea: 7c 8a e3 c8 fa 14 c1 b7 34 62 08 02 ce 85 9c 24 e8 c8 |.......4b.....$.. 00000fc: 44 f6 ce 7b 6a cf 1b d6 e7 3c 11 9e 02 23 1b c6 32 82 D..{j....<...#..2. 000010e: 8a 4c 58 5f 54 c2 ae e2 08 51 5d b7 d9 4e ef b6 62 8d .LX_T....Q]..N..b. 0000120: b8 51 16 35 6d 2a 29 91 5d 69 2e a5 1c f4 51 a0 66 9c .Q.5m*).]i....Q.f. 0000132: 73 5a 4b d6 2a 81 86 49 ef f5 2e 80 7c 8c fa 9a ac 18 sZK.*..I....|..... 0000144: 4a 6c b0 ef 9a e4 47 d9 b2 53 fb 94 68 40 88 7f c7 d4 Jl....G..S..h@.... 0000156: e2 72 62 94 7c 88 45 be be 6b 3f b4 0d bc ef b8 38 65 .rb.|.E..k?.....8e 0000168: 9c cd 3e 7f b8 7f 78 f6 f0 6c f6 cb ec a7 d9 cf fa e1 ..>...x..l........ 000017a: 83 d9 8f 0f ef cc 7e 51 07 14 d2 78 6d 74 30 f0 fe 36 ......~Q...xmt0..6 000018c: aa 83 2a 37 46 2a 20 cb 55 0a a5 1d 07 6e 84 aa 71 c8 ..*7F* .U....n..q. 000019e: 19 b2 65 b4 26 51 e8 f4 d9 85 3a a8 09 aa 9b e7 c0 56 ..e.&Q....:......V 00001b0: e2 78 5d 60 7d ca 14 1c e2 78 e1 04 1d bb 8a 58 d5 c1 .x]`}....x.....X.. 00001c2: 5d 43 f0 84 6c 63 c6 01 7d 42 fd 16 97 fe f3 ed 3a 8f ]C..lc..}B......:. 00001d4: c3 c0 6c c9 55 f0 92 b1 ab d6 57 b1 ca 5d d7 fb 3c 61 ..l.U.....W..]..<a 00001e6: eb 9b 1c 1e 04 c1 b0 83 2a bc 40 cb c4 8a 9a 6c 78 c4 ........*[[email protected]](/cdn-cgi/l/email-protection). 00001f8: 8e 29 b3 08 f2 43 aa c5 76 fa 18 65 f4 a1 c3 d1 a2 ca .)...C..v..e...... 000020a: 52 e9 13 37 f4 a1 2e 6d d4 17 5d 4c 5c 47 1c 43 e2 36 R..7...m..]L\G.C.6 000021c: 5c 2e 74 e1 35 ca c8 a9 63 5c 9b c6 ea 58 9c 69 33 f1 \.t.5...c\...X.i3. 000022e: 96 b7 ae 56 ed 87 ab 52 6b 84 83 c7 93 c0 4c 2a 04 3f ...V...Rk.....L*.? 0000240: f6 35 0f 02 4f 11 5f c1 fa a4 6e 82 9f 70 49 64 2b 14 .5..O._...n..pId+. 0000252: ae da 90 79 7a 12 2d d5 ea 24 91 95 cd 90 5e a1 86 36 ...yz.-..$....^..6 0000264: d9 0d 89 f7 b5 25 75 4a 53 75 7a 70 74 b6 51 cd 53 19 .....%uJSuzpt.Q.S. 0000276: f2 98 aa db 8c a0 2c b1 84 d2 83 91 4b 1e 6b 48 92 39 ......,.....K.kH.9 0000288: 14 12 84 eb 58 69 03 c7 4d ac 0f 4c 5b 15 2a 16 e9 d9 ....Xi..M..L[.*... 000029a: 84 c3 d0 fa a9 ea 71 e6 65 82 1f 7d 70 57 8d 11 16 ab ......q.e..}pW.... 00002ac: 9e e8 37 bc e1 0e 97 79 58 e8 6b 46 19 2d a3 24 e2 12 ..7....yX.kF.-.$.. 00002be: 3b 74 38 53 e3 9c 1b 92 00 95 89 70 c4 fe f2 5a f5 da ;t8S.......p...Z.. 00002d0: 28 15 ba e6 e2 02 be ac fb 81 2a b8 e7 7c 3e e6 5c ee (.........*..|>.\. 00002e2: 5e 97 c6 8b 29 f1 2a a7 a9 0f b7 5b e4 3d 6b d8 e9 fc ^...).*....[.=k... 00002f4: 56 16 e8 c2 b7 01 d4 ef 53 1e 56 f9 bc cf 21 96 97 7b V.......S.V...!..{ 0000306: 28 ab 38 7a de 71 b7 3e 80 47 8f 4c 31 07 24 65 29 aa (.8z.q.>.G.L1.$e). 0000318: d3 1f 8b f5 d1 e3 75 02 fa d5 4b 05 ee 10 62 b9 2a a1 ......u...K...b.*. 000032a: 27 71 29 c0 ea 6f 39 e0 d3 4a 5a 6c 43 6a 47 ed 56 d7 'q)..o9..JZlCjG.V. 000033c: e0 04 b7 d4 35 9c ae 71 a6 72 bf 7d fc d8 96 6a 94 01 ....5..q.r.}...j.. 000034e: 75 e4 ed 30 9f bf c9 55 ca d3 18 a6 85 32 45 2d a7 f3 u..0...U.....2E-.. 0000360: 5a 4b c8 2b 11 c2 e5 55 4a ea 9c 62 33 e0 00 4a f6 45 ZK.+...UJ..b3..J.E 0000372: 61 c6 c1 09 6f 15 e9 dc 0f 7c 0e 0d c0 f2 a3 c6 52 07 a...o....|......R. 0000384: 69 99 ab 10 b5 31 6e 51 ee 82 10 d0 d0 e7 32 2e e9 0d i....1nQ......2... 0000396: 47 55 66 6b 79 60 2e 51 ec d4 05 13 aa c7 06 53 6b 22 GUfky`.Q.......Sk" 00003a8: 59 93 03 dc e2 b8 b5 49 5d 8c 29 70 df 8b 03 94 d1 b2 Y......I].)p...... 00003ba: c6 15 2a 96 63 b9 b8 e5 a6 c4 72 e1 87 69 0a 45 8d 9c ..*.c.....r..i.E.. 00003cc: 6c 1e b9 3b 31 b6 61 d9 a3 4b 8e a5 7d 6b a5 73 ae 3c l..;1.a..K..}k.s.< 00003de: ca e7 4c 79 37 d9 ba 75 66 f5 52 2f 1a 82 15 06 8d f5 ..Ly7..uf.R/...... 00003f0: a1 9c 67 89 db 9c 4c 10 f8 4c fc 05 71 77 9a 66 05 d7 ..g...L..L..qw.f.. 0000402: bc de de ea d9 ef b3 ef f5 c3 d3 f5 9c fd 63 f6 db ff ..............c... 0000414: 55 b8 d6 cb 56 ff fb 65 b9 0e b8 01 68 1b 0e 98 83 1c U...V..e....h..... 0000426: 00 63 22 34 69 60 41 05 99 e4 84 2e f9 75 fd 08 61 61 .c"4i`A......u..aa 0000438: 55 20 b8 3e 0a 4c 49 9f b5 c9 f8 fc d4 0a e7 39 15 9a U .>.LI........9.. 000044a: bd f0 8d 92 f5 6f f0 00 d0 c0 bc f3 41 5d 06 c2 80 c4 .....o......A].... 000045c: 22 26 67 7d e5 e4 2e 4f 47 71 ed 9d ca 11 e4 9a 70 58 "&g}...OGq......pX 000046e: 58 5f 4b 19 53 d7 52 03 1a f6 6b e2 c3 f0 86 07 b9 28 X_K.S.R...k......( 0000480: 56 aa 65 79 21 a8 29 c2 39 a0 38 e3 a7 51 e3 29 38 56 V.ey!.).9.8..Q.)8V 0000492: 37 de 9b fc 08 91 0b 70 30 fd 3c db b7 e6 34 a4 d6 0c 7......p0.<...4... 00004a4: 56 5f 9f 37 41 ca 2d ff 01 V_.7A.-.. ``` Prints a sorted list of SE sites. Compression has been done with [zopfli](https://github.com/google/zopfli), which uses the DEFLATE format but obtains a much better ratio than (g)zip. [Answer] # Python3, ~~1754~~ ~~1728~~ 1662 bytes ~~Python3 includes the `lzma` module, which allowed me to obtain a really decent compression ratio.~~ (I have switched to `gzip`.) I was originally going to use base64 to encode the output but realized I could squeeze some more bytes out using base85 (ascii85). I avoided the issue with escaping `'` by using a triple-quoted string and avoided the issue with escaping `\` characters by using the `r""` prefix. ``` import base64,gzip print(gzip.decompress(base64.a85decode(r'''+,^C)B/BZj!rlh3]9_20&FK!&W8.1RdSX2MG($0f,4;Ut&gBgi+qS,^:g1Gf=(R8b8Y=`"jO#8sSE-4$#Gc:bO5pd"a]c<M-kMcVF75Ychj%1^aigAZ<M?`A-I0YX;,\St;Kbp<"UQq`P)[UCng5)1'j6s9g1M[#C+ZkYm5DT.]@Ye]gHW,bjmN$5n%8%sn&2_mKemVoLau@M(*\_f>KWEMq71K\\c$=@S(rF=3rJaG^$+dImSCm_V/uIdq5(M-0s6/SjJB.JghWm*0(3p3qJJJE&d,bmQH8[;Oe,L&'L<-_B3iX@>j2e?E4`YS1JKd&2SrS8Jk?c'bFhgZmN:?S+91#42Z(O%pR=DAO)O`]p\W2GmISBsk%D=,Q8eW@egBR-W!?R-!EdLM[Q6=PGPlW\D-lO)MI)k:"i']CRRc$QVd`Q=H=_?MKo5.$9>#5H1eJ/fZT'P.iKSu-c4l-:ieL,pY>qA@&s#0+M:Bf1>'Z90aoI35N`-FXotZS)ba\bga\'%C+%nnr4Que%Rinl/10W?AqBnNn[?jgWCF:GCK=H&1,U%Kr\IiPP5V-:\kIUj[!sD/Bl%tA))40(rLMIZt;e1%4\U%0U)S#3_mFLU9Kj0>2ZrJma=2H0VKPa26iWN/>89p+!i+rG#3g!NMP'dJ9m6\Y@7X&l;<1ZEAfIkXf^W=?J24pDMR;;O*ahk?f/rj;=;O^,sN.dplEWS9Q84]#>0R):Xf>4C`9PXbpB5X_92'WV6::04$aNMmBYn61H4Q=pX:'tW*g_M0oY@V:\-!RBbbbGi79]\74^bqA9.XfghaFsT_fqBc.j\6b:`uaKW"WXLCFGpdVbf"TSTh\C-%GEI#`-KCah+CU2osaZ#.'9SlGJjU*m5b2U1`5)>EI$WGVe62?NP$GG=&Rie4G&6"O7p8bA*1-%#gY#Y)i8uQZa8kp??#UpG8Z;D"8%"?7CV3ce\IA4\AJNX$0pXq[pH2XLnXB"=e%c@#agB@<?,FFB]F^)o.Lg#H,@?.E6jdhC\a7=WDO`um>Dm2Ju2=1W4h3<!knpd*/E*XJ>3+Aqbe!sOVTo;6+p,hn7K;g%U@,&_?>V2a07T5G)/,S8nfq2HsO#4#C7ad'3\QmFgPtcF@fJ*-Q)WIZH0HZDP#Sa5`pgJKH2[f)k$GO]Wu'Sg54>Eh+*HFkfd;=DeMa;CN1>bQTAUqZsA7[+>i(sDo`:n:oKpu1Beh`*.cf*h8HnV3Ot>5kie@>8$:n+U4:>:>V`.Wp8f2c(X2)1a=C??bgX.%N2q\E*$f+&r%h:ubWRX.g:*<::QWNWhWZ"qZ%+)L`,M`HoCm@XJ91.,6dO/,%J.u$jAs%B\7ShidHX6,c1";KU2fc2Ntn=Bj]p@,IV8<UHVW>l6/2Y1a7',4p;eT`m$YKom'MtC%nc?t_gpr?ceY\2Ynjh@V0n;upk;YY/q=:)fPEmM1:6u$la$)!e[aZ:md#3)bkLT]Xp`B<YWMLlPOPB<PSAXF%WPR=Ml'V`6CGj3ItR:0.l+(RDYWYjl0]E?FjoMuiF&=2#K`3d1%?RBmMe9!"kZ)LPK-FcX>]UD]BXk\/OT09#QOi''')).decode()) ``` ]
[Question] [ Your challenge is simple: GIven an integer **N**, ouput every list of positive integers that sums to **N**. For example, if the input was 5, you should output ``` [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] ``` These lists do not have to be output in any particular order, nor do the numbers inside each list. For example, this would also be an acceptable output for '5': ``` [1, 1, 1, 2] [5] [3, 1, 1] [2, 1, 2] [4, 1] [1, 1, 1, 1, 1] [2, 3] ``` You can safely assume that the input will be a positive integer, and you can take this number in any reasonable format. **You may NOT use any builtin functions that do this.** If your program either fails or takes too long for large **N** this is OK, but you must at the very least produce the correct output for the first 15. Standard loopholes apply, and the shortest answer in bytes wins! # Test IO ``` 1: [[1]] 2: [[1, 1], [2]] 3: [[1, 1, 1], [1, 2], [3]] 4: [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]] 5: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 4], [2, 3], [5]] 7: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 3], [1, 1, 1, 2, 2], [1, 1, 1, 4], [1, 1, 2, 3], [1, 1, 5], [1, 2, 2, 2], [1, 2, 4], [1, 3, 3], [1, 6], [2, 2, 3], [2, 5], [3, 4], [7]] 10: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 1, 1, 5], [1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 2, 4], [1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 6], [1, 1, 1, 2, 2, 3], [1, 1, 1, 2, 5], [1, 1, 1, 3, 4], [1, 1, 1, 7], [1, 1, 2, 2, 2, 2], [1, 1, 2, 2, 4], [1, 1, 2, 3, 3], [1, 1, 2, 6], [1, 1, 3, 5], [1, 1, 4, 4], [1, 1, 8], [1, 2, 2, 2, 3], [1, 2, 2, 5], [1, 2, 3, 4], [1, 2, 7], [1, 3, 3, 3], [1, 3, 6], [1, 4, 5], [1, 9], [2, 2, 2, 2, 2], [2, 2, 2, 4], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5], [2, 4, 4], [2, 8], [3, 3, 4], [3, 7], [4, 6], [5, 5], [10]] ``` Super large test case: 15 should output this ``` [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5], [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4], [1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 6], [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3], [1, 1, 1, 1, 1, 1, 1, 1, 2, 5], [1, 1, 1, 1, 1, 1, 1, 1, 3, 4], [1, 1, 1, 1, 1, 1, 1, 1, 7], [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 2, 2, 4], [1, 1, 1, 1, 1, 1, 1, 2, 3, 3], [1, 1, 1, 1, 1, 1, 1, 2, 6], [1, 1, 1, 1, 1, 1, 1, 3, 5], [1, 1, 1, 1, 1, 1, 1, 4, 4], [1, 1, 1, 1, 1, 1, 1, 8], [1, 1, 1, 1, 1, 1, 2, 2, 2, 3], [1, 1, 1, 1, 1, 1, 2, 2, 5], [1, 1, 1, 1, 1, 1, 2, 3, 4], [1, 1, 1, 1, 1, 1, 2, 7], [1, 1, 1, 1, 1, 1, 3, 3, 3], [1, 1, 1, 1, 1, 1, 3, 6], [1, 1, 1, 1, 1, 1, 4, 5], [1, 1, 1, 1, 1, 1, 9], [1, 1, 1, 1, 1, 2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 2, 2, 2, 4], [1, 1, 1, 1, 1, 2, 2, 3, 3], [1, 1, 1, 1, 1, 2, 2, 6], [1, 1, 1, 1, 1, 2, 3, 5], [1, 1, 1, 1, 1, 2, 4, 4], [1, 1, 1, 1, 1, 2, 8], [1, 1, 1, 1, 1, 3, 3, 4], [1, 1, 1, 1, 1, 3, 7], [1, 1, 1, 1, 1, 4, 6], [1, 1, 1, 1, 1, 5, 5], [1, 1, 1, 1, 1, 10], [1, 1, 1, 1, 2, 2, 2, 2, 3], [1, 1, 1, 1, 2, 2, 2, 5], [1, 1, 1, 1, 2, 2, 3, 4], [1, 1, 1, 1, 2, 2, 7], [1, 1, 1, 1, 2, 3, 3, 3], [1, 1, 1, 1, 2, 3, 6], [1, 1, 1, 1, 2, 4, 5], [1, 1, 1, 1, 2, 9], [1, 1, 1, 1, 3, 3, 5], [1, 1, 1, 1, 3, 4, 4], [1, 1, 1, 1, 3, 8], [1, 1, 1, 1, 4, 7], [1, 1, 1, 1, 5, 6], [1, 1, 1, 1, 11], [1, 1, 1, 2, 2, 2, 2, 2, 2], [1, 1, 1, 2, 2, 2, 2, 4], [1, 1, 1, 2, 2, 2, 3, 3], [1, 1, 1, 2, 2, 2, 6], [1, 1, 1, 2, 2, 3, 5], [1, 1, 1, 2, 2, 4, 4], [1, 1, 1, 2, 2, 8], [1, 1, 1, 2, 3, 3, 4], [1, 1, 1, 2, 3, 7], [1, 1, 1, 2, 4, 6], [1, 1, 1, 2, 5, 5], [1, 1, 1, 2, 10], [1, 1, 1, 3, 3, 3, 3], [1, 1, 1, 3, 3, 6], [1, 1, 1, 3, 4, 5], [1, 1, 1, 3, 9], [1, 1, 1, 4, 4, 4], [1, 1, 1, 4, 8], [1, 1, 1, 5, 7], [1, 1, 1, 6, 6], [1, 1, 1, 12], [1, 1, 2, 2, 2, 2, 2, 3], [1, 1, 2, 2, 2, 2, 5], [1, 1, 2, 2, 2, 3, 4], [1, 1, 2, 2, 2, 7], [1, 1, 2, 2, 3, 3, 3], [1, 1, 2, 2, 3, 6], [1, 1, 2, 2, 4, 5], [1, 1, 2, 2, 9], [1, 1, 2, 3, 3, 5], [1, 1, 2, 3, 4, 4], [1, 1, 2, 3, 8], [1, 1, 2, 4, 7], [1, 1, 2, 5, 6], [1, 1, 2, 11], [1, 1, 3, 3, 3, 4], [1, 1, 3, 3, 7], [1, 1, 3, 4, 6], [1, 1, 3, 5, 5], [1, 1, 3, 10], [1, 1, 4, 4, 5], [1, 1, 4, 9], [1, 1, 5, 8], [1, 1, 6, 7], [1, 1, 13], [1, 2, 2, 2, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 4], [1, 2, 2, 2, 2, 3, 3], [1, 2, 2, 2, 2, 6], [1, 2, 2, 2, 3, 5], [1, 2, 2, 2, 4, 4], [1, 2, 2, 2, 8], [1, 2, 2, 3, 3, 4], [1, 2, 2, 3, 7], [1, 2, 2, 4, 6], [1, 2, 2, 5, 5], [1, 2, 2, 10], [1, 2, 3, 3, 3, 3], [1, 2, 3, 3, 6], [1, 2, 3, 4, 5], [1, 2, 3, 9], [1, 2, 4, 4, 4], [1, 2, 4, 8], [1, 2, 5, 7], [1, 2, 6, 6], [1, 2, 12], [1, 3, 3, 3, 5], [1, 3, 3, 4, 4], [1, 3, 3, 8], [1, 3, 4, 7], [1, 3, 5, 6], [1, 3, 11], [1, 4, 4, 6], [1, 4, 5, 5], [1, 4, 10], [1, 5, 9], [1, 6, 8], [1, 7, 7], [1, 14], [2, 2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 5], [2, 2, 2, 2, 3, 4], [2, 2, 2, 2, 7], [2, 2, 2, 3, 3, 3], [2, 2, 2, 3, 6], [2, 2, 2, 4, 5], [2, 2, 2, 9], [2, 2, 3, 3, 5], [2, 2, 3, 4, 4], [2, 2, 3, 8], [2, 2, 4, 7], [2, 2, 5, 6], [2, 2, 11], [2, 3, 3, 3, 4], [2, 3, 3, 7], [2, 3, 4, 6], [2, 3, 5, 5], [2, 3, 10], [2, 4, 4, 5], [2, 4, 9], [2, 5, 8], [2, 6, 7], [2, 13], [3, 3, 3, 3, 3], [3, 3, 3, 6], [3, 3, 4, 5], [3, 3, 9], [3, 4, 4, 4], [3, 4, 8], [3, 5, 7], [3, 6, 6], [3, 12], [4, 4, 7], [4, 5, 6], [4, 11], [5, 5, 5], [5, 10], [6, 9], [7, 8], [15]] ``` ### Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 84165; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 31716; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] ## Pyth, ~~10~~ 9 bytes ``` {SMlMM./U ``` Not too sure if this isn't cheating, but the rules only said one cannot use **integer** partition (it's not stated clearly in the question itself, but a comment by OP in the question says integer partition). I'm using ~~string~~ **list** partition, which makes slices of the list that concatenate up to the "mother" list. I believe I have to thank @Maltysen for the idea of using lists rather than strings. n=15 takes less than one second on my machine. In dataflow pseudocode: ``` input // initial data U range // makes a list of length equal to input ./ partition // partitions string lMM length // length of each substring in each way to partition SM sort // sort each way to partition { deduplicate // removes all duplicate after sorting print // implicit, output final result ``` [Try it online here.](http://pyth.herokuapp.com/?code=%7BSMlMM.%2FU&input=4&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A7%0A10%0A15&debug=0) [Answer] # Pyth, 18 bytes ``` L?b{SM+R-bsdsyMb]Y ``` [Try it online!](http://pyth.herokuapp.com/?code=L%3Fb%7BSM%2BR-bsdsyMb%5DYy&input=15&debug=0) (The `y` at the end is used to call the function) This is fairly quick. This uses recursion. If the input is `b`, my method will generate the partitions from `0` to `b-1`, and then generate the correct partitions from each. For example, when `b=4`: * `b=0` gives `[[]]` * `b=1` gives `[[1]]` * `b=2` gives `[[2], [1, 1]]` * `b=3` gives `[[3], [1, 2], [1, 1, 1]]` Then, to each partition in `b=0`, append `4` (to make the sum 4); to each partition in `b=1`, append `3` (to make the sum `4`); etc. This is mainly how it works. ``` L?b{SM+R-bsdsyMb]Y L define a function called "y" which takes an argument: "b" ?b test for truthiness of b (in this case, test if b>0). {SM+R-bsdsyMb if truthy: yMb call this function from 0 to b-1. s unpack each list of partitions, generating only partitions. +R to each partition (d), append: - the difference of b b (the argument) and sd the sum of d (the partition). SM sort each partition. { remove duplicates. ]Y if falsey: Y yield []. ] yield [[]]. ``` [Answer] # Haskell, 53 bytes ``` p=[[]]:[map(1:)q++[a+1:b|a:b<-q,all(a<)b]|q<-p] (p!!) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` :"0Gq:@XNG3$Yc!dS!Xu ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiIwR3E6QFhORzMkWWMhZFMhWHU&input=NQ) For input `15` it takes about 2 seconds in the online compiler. ### Explanation This works by generating partition *points* and then converting to partition *lengths*. What I mean by this is the following. Given input *N* = 5, a possible partition is [2 2 1]. This is represented by partition points [0 2 4 5], such that *consecutive differences* (or lengths) of the partition points give the resulting partition of the input number. All arrays of partition points start with 0 and end with *N*. The number *k* of intermediate points varies from 0 to *N*-1. For *N* and *k* given, the intermediate points can be generated as a combination of the numbers [1, 2, ..., *N*-1] taken *k* at a time. Several arrays of partition points may give rise to the same result in a different order. For example, partition points [0 1 3 5] would give the partition lengths [1 2 2], i.e. the same as the previous [2 2 1] only in a different order. This has to be taken into account by *sorting* each array of partition lengths and *removing duplicates*. ``` : % Implicitly input N. Push [1 2 ... N]. These are the possible values of k, % except with N instead of 0 " % For each 0 % Push 0 Gq: % Push [1 ... N-1]. These the possible intermediate points @XN % Push k and produce the combinations. Each k produces a 2D array with % each combination on a row. The value k=N produces an empty array G % Push N 3$Yc % Prepend a column of zeros and append a column of N to the array !d % Transpose. Consecutive differences of each column S! % Sort each column. Transpose Xu % Keep only unique rows % Implicitly end for and display all arrays in the stack ``` [Answer] # J, ~~49~~ ~~42~~ ~~36~~ ~~35~~ 32 bytes ``` a:1&([:~.@,(,;}./:~@,(+{.))&>)~] ``` It's tacit now! Builds the integer partition of *n* by constructing the integer partitions from 1 to *n*. Computes the result for *n* = 15 in a millisecond. Starting with the initial integer partition `[[1]]` which corresponds to *n* = 1, construct the next integer partition by joining the results from two operations: appending a 1 to each partition; incrementing the smallest value by 1 in each partition. Of course, duplicate partitions will be removed. To get the integer partition *n* = 2 and onwards, ``` Partition for n = 1 [[1]] Partition for n = 2 [[1, 1]] join [[2]] = [[1, 1], [2]] Partition for n = 3 [[1, 2], [1, 1, 1]] join [[3], [1, 2]] = [[3], [1, 2], [1, 1, 1]] ... and so on ``` ## Usage ``` f =: a:1&([:~.@,(,;}./:~@,(+{.))&>)~] f 1 ┌─┐ │1│ └─┘ f 2 ┌───┬─┐ │1 1│2│ └───┴─┘ f 3 ┌─────┬───┬─┐ │1 1 1│1 2│3│ └─────┴───┴─┘ f 5 ┌─────────┬───────┬─────┬───┬─────┬───┬─┐ │1 1 1 1 1│1 1 1 2│1 2 2│2 3│1 1 3│1 4│5│ └─────────┴───────┴─────┴───┴─────┴───┴─┘ # f 15 176 ``` ## Explanation Since J does not support ragged arrays, each partition has to be boxed so they they won't be zero padded when appended to other partitions. ``` a:1&([:~.@,(,;}./:~@,(+{.))&>)~] Input: n a: The empty box ] Get the input n 1&( )~ Repeat n times with an initial array of one empty box ( )&> Operate on each partition ( ) Hook a partition {. Get its head (the smallest value) 1 + Add 1 to it 1 }. Drop the first value in each partition , Join the previous two results /:~@ Sort it 1 , Prepend a 1 to the initial partition ; Box the last two results and join them [: , Flatten the pairs of boxes ~.@ Remove duplicates and return Return the final result where each box is a partition of n ``` [Answer] ## Python, 65 bytes **Python 3** ``` def f(n,i=1,l=[]):n or print(l);i>n or[f(n-i,i,[i]+l),f(n,i+1,l)] ``` This function accumulates a partition and prints the outputs, branching on choices. It decides how many 1's to put in the partition, how many 2's, and so on. For each value `i`, it either * Adds a part of size `i`, and decreases `n` to `n-i`, or * Moves on to `i+1` If `i>n`, then no more parts can be made, so it stops. If `n` falls to `0`, the partition is successful and so is printed. **Python 2** ``` f=lambda n,i=1:n/i and[l+[i]for l in f(n-i,i)]+f(n,i+1)or[[]][n:] ``` A recursive method that outputs a list of partitions. As with the Python 3 code, it counts up the part size `i` and decides at each step whether to add another part of size `i` or stop. Both of these do `n=15` almost instantly. [Answer] ## Javascript, 194 bytes ``` p=n=>{var a=[];for(var i=1;i<=n-i;i+=1){for(v of p(n-i)){v.push(i);a.push(v.sort())}}a.push([n]);return a};n=5;s=p(n).map(v=>JSON.stringify(v));s=s.filter((v,i)=>s.indexOf(v)==i);console.log(s); ``` **Non-minified** Finding uniques by sorting and comparing to a string is quite a hack, but probably saves space. ``` p = n => { var a = []; for (var i = 1; i <= n-i; i++) { for (v of p(n-i)) { v.push(i); a.push(v.sort()); } } a.push([n]); return a; } n = 5; s = p(n).map(v => JSON.stringify(v)); s = s.filter((v,i) => s.indexOf(v) == i); console.log(s); ``` [Answer] ## Haskell, 44 bytes ``` 0%m=[[]] n%m=[j:r|j<-[m..n],r<-(n-j)%j] (%1) ``` The auxiliary function `n%m` gives the partitions of `n` into parts `≥m`, with the main function using `m=1`. It branches of each first entry `j` with `m≤j≤n`, recursing on the remaining partition of `n-j` into parts that are at least `j`. The base case `n==0` gives just the empty partition. [Answer] # Python 3.5, ~~82~~ 72 bytes ``` f=lambda n:{(*sorted([*p,i]),)for i in range(1,n)for p in f(n-i)}|{(n,)} ``` Returns a set of tuples. **n = 15** finishes instantly. Test it on [repl.it](https://repl.it/C7rf/3). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 33 bytes (Non-competing) ``` :1f:oad. :1eI,.##lI,.:{.>0}a+?,.= ``` This is non-competing because of a bug fix. This takes about 1 second for `15` on my machine. For `20` and greater this crashes with an `Out of global stack` exception. ### Explanation This uses no partitioning built-in of any kind, and instead uses the fact that `+` works both ways through constraints propagation. * Main predicate: ``` :1f Find the list of all valid outputs of predicate 1 :oa Sort each element of that list d. Output is that list of sorted lists minus all duplicates ``` * Predicate 1: ``` :1eI I is an integer between Input and 1 .##lI, Output is a list of length I .:{.>0}a Elements of Output are integers greater than 0 +?, The sum of the elements of Output is Input .= Assign values to the elements of Output ``` [Answer] # Pyth, 17 bytes ``` L|{SMs+LVrb0yMb]Y ``` Defines a function named `y`. [Try it online](https://pyth.herokuapp.com/?code=L%7C%7BSMs%2BLVrb0yMb%5DYy&input=5&test_suite_input=5). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` b1ŒṖḅ1Ṣ€Q ``` [Try it online!](http://jelly.tryitonline.net/#code=YjHFkuG5luG4hTHhuaLigqxR&input=&args=MTU) ### How it works ``` b1ŒṖḅ1Ṣ€Q Main link. Argument: n (integer) b1 Convert n to unary, i.e., a list A of n 1's. ŒṖ Generate all partitions of the list A. ḅ1 Convert each flat list from unary to integer. Ṣ€ Sort each resulting list. Q Unique; deduplicate the lists. ``` [Answer] ## J, 39 bytes ``` [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: ``` This is a monadic verb that takes an integer and returns an array of boxed arrays. [Try it here.](http://tryj.tk/) Usage: ``` p =: [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: p 3 +-----+---+-+ |1 1 1|2 1|3| +-----+---+-+ ``` On input 15, it runs for about a second on my machine. ## Explanation This challenge immediately looked like a job for Catalogue (`{`) and Cut (`;.`). The outline of the algorithm is: * Produce all 0-1 arrays of length `n`. * For each of them, cut a dummy length-`n` array along the 1s, and list the lengths of each part. * Sort the lengths, and remove duplicate arrays from the result. Apparently, Luis Mendo had the [same idea](https://codegolf.stackexchange.com/a/84169/32014) too. Explanation of code: ``` [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: Input is n. <: n-1 #~ copies of (<1 0) the boxed array [1 0]. 1 ; Prepend the boxed array [1]. {@ Catalog: produces all combinations of taking one item from each box, in a high-dimensional matrix. ,@ Flatten the matrix. This results in a list of all boxed 0-1 arrays of length n that begin with a 1. i. The array A =: 0, 1, ..., n-1. ( "1 0) For each of the boxed arrays B: ;.1~ cut A along the occurrences of 1s in B, # take the length of each part, \:~@ sort the lengths, <@ and put the result in a box. [:~. Remove duplicate boxes. ``` [Answer] # Mathematica, ~~62~~ 54 bytes ``` Inner[#2~Table~#&,FrobeniusSolve[r=Range@#,#],r,Join]& ``` The partitions of an integer *n* can be found by solving for *n*-tuples of non-negative integers (*c*1, *c*2, ..., *c**n*) such that *c*1 + 2 *c*2 + ... + *n* *c**n* = *n*. `FrobeniusSolve` is able to find all solutions to this equation which are used to create that many copies of their respective values in order to find all integer partitions of *n*. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ɾÞ×'∑?= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvsOew5cn4oiRPz0iLCIiLCI1Il0=) ``` ɾÞ×'∑?= ɾ # Get a list in the range [1, input] Þ× # Get all combinations (with replacement) of all lengths ' # Filter for: ∑?= # Sum equals the input ``` [Answer] ## JavaScript ~~(Firefox 30-57) 79~~ ES6, 65 bytes ``` f=(n,m=1,a=[])=>n?m>n?[]:[...f(n-m,m,[...a,m]),...f(n,m+1,a)]:[a] ``` Port of @xnor's Python solution. (If only I'd noticed that you could recurse over `m` as well as `n`...) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Å1.œO€{ê ``` Outputs as a list of lists, from `n` amount of 1s to `[n]`, where each inner list is sorted (I know the rules allow them to be unsorted, but it's necessary for the uniquify of lists). [Try it online](https://tio.run/##yy9OTMpM/f//cKuh3tHJ/o@a1lQfXvX/v6EpAA) or [verify the first 15 result](https://tio.run/##yy9OTMpM/W9o6qrkmVdQWmKloGTvp8Ol5F9aAuHp@P0/3Gqod3Sy/6OmNdWHV/3XObTN/j8A). If builtins were allowed, this would be **2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead (with the same exact results): `Åœ` - [Try it online](https://tio.run/##yy9OTMpM/f//cOvRyf//G5oCAA) or [verify the first 15 results](https://tio.run/##yy9OTMpM/W9o6qrkmVdQWmKloGTvp8Ol5F9aAuHp@P0/3Hp08n@dQ9vs/wMA). **Explanation:** ``` Å1 # Push a list with the (implicit) input amount of 1s .œ # Get all partitions of this list O # Sum each inner-most list €{ # Sort each inner list ê # Sorted uniquify the list of lists # (after which the result is output implicitly) ``` Minor note: `ê` (sorted uniquify) could also just be `Ù` (uniquify) for the same result, but with the added sort it's a lot faster in this case. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 44 bytes ``` (1!) _!0=[] a!n=anyOf[a ..n]#n a#n=a:a!(n-a) ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z/NVsNQUZMrXtHANjqWK1ExzzYxr9I/LTpRQU8vL1Y5jytRGShklaiokaebqPk/NzEzT8FWIU3B9D8A "Curry (PAKCS) – Try It Online") [Answer] ## [Scala](http://www.scala-lang.org/), 117 bytes Port of [@Dennis's Python answer](https://codegolf.stackexchange.com/a/84187/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##NYwxC8IwEEZ3f8WNOYqBDC6VCI4OnTqWIrG9QCRe0@YEQfztMQ5u33t8vDy56Mpyu9Mk0LnAQC8hnjOcU3pDmcmDV9xeWLDtSYae1qHCONpQvbUGq1XVKoNIMZMy8GQJERi1j046l1Swp3reB9SPSte2@S@dl01oRtSy1E7z6zAWgLQFlsjKK3NAPO4@5Qs) ``` def f(n:Int):Set[Seq[Int]]=if(n==1)Set(Seq(1))else(1 until n).flatMap(i=>f(n-i).map(_:+i).map(_.sorted)).toSet+Seq(n) ``` Ungolfed version. [Try it online!](https://tio.run/##TY6xCoMwEIZ3n@IfE6RChi4WCx0LdeooDqkmkJKewVyhID67VSvS4eDuvo@7Pzba62nqHk/TMErtCObDhtqISwgDEqA1FlZQjiuxzHE3XN1c5Goe6xoFhtkBnIUgFAWU3DZYVLGoQkm5rkYYH83OhcKb2HmQzKzXXOqAAQ7FeROwPMYBTmavlYV/Nh8IyNOFxq5n0@5k3Lox424OgRRrDNpSJL8KvSP2JKxQRylPyThNXw) ``` object Main extends App{ def f(n: Int): Set[List[Int]] = { if (n == 1) { Set(List(1)) } else { (1 until n).flatMap { i => f(n - i).map { p => (p :+ i).sorted } }.toSet + List(n) } } println(f(15)); } ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/106168/edit). Closed 7 years ago. [Improve this question](/posts/106168/edit) When you resize an image down to a very small size, it looks very blocky when you scale the pixels back up individually. [![original Starry Night](https://i.stack.imgur.com/l35KF.jpg)](https://i.stack.imgur.com/l35KF.jpg) [![scaled-down Starry Night](https://i.stack.imgur.com/aBVGE.jpg)](https://i.stack.imgur.com/aBVGE.jpg) In extreme cases, as above, you can no longer reconstruct the original image, as too much information has been lost. Your task is to build a program that will *imagine* what the original, unscaled image might have looked like in extreme cases such as this one, where the picture has been reduced to a simple palette. Your program will take an uncompressed bitmap image with three 8-bit RGB channels (with maximum dimensions 16 pixels on each side), and output a second image that produces the original image when scaled down using an average filter (equivalent to GIMP's "Linear" option). The output image should have the same aspect ratio as the original and have an exact multiple of pixels, to make average-filtering easier. It should also be at least 50 times the size of the original image on each dimension. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/96717/edit). Closed 7 years ago. [Improve this question](/posts/96717/edit) [This](https://codegolf.stackexchange.com/q/73230/56341) question wants you to golf batch programms. In Batch you can use ``` set x=averylongbatchcommand %x% arg1 ``` which expands to ``` set x=averylongbatchcommand averylongbatchcommand arg1 ``` Your task is it to expand these statements. As you can also use `set` for arithmetic purposes like this: ``` set x = 0 set /a x= %x%+1 ``` you should ignore the statements where the pattern with `set /a` is applied. There will never be something like ``` set s=SET %s% s=%s% a ``` where the variable is assigned using itself as command. But you have to handle things like ``` b: set a =echo %a% Hello World! set a=goto %a% b ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the answer with the fewest bytes wins. ## Testcases ``` set s=set %s% e=echo %e% I will have to use this exact thing very often because %e% it absolutely wouldn't be shorter if i just left out these set statements ``` Expands to: ``` set s=set set e=echo echo I will have to use this exact thing very often because echo it absolutely wouldn't be shorter if i just left out these set statements ``` --- ``` set s=set %s% i=0 set g=goto :a if %i%==15 ( %g% e echo %i% ) %s% /a i=%i%+1 %g% a :e %s% i=0 %g% a ``` Expands to: ``` set s=set set i=0 set g=goto :a if %i%==15( goto e echo %i% ) set /a i=%i%+1 goto a e: set i=0 goto a ``` --- ``` set s=set %s% s=%s% a= ``` Mustn't be supported. --- ``` set a=echo %a% Hi set a=type %a% log.txt ``` Expands to: ``` set a=echo echo Hi set a=type type log.txt ``` --- ``` set x = 0 set /a x= %x%+1 ``` Expands to: ``` set x = 0 set /a x= %x%+1 ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/68290/edit). Closed 8 years ago. [Improve this question](/posts/68290/edit) It's well known that corrupted JPEG files or NTSC/PAL streams will appear as distorted versions of the true images, or versions covered in random-looking blocks of pixels. --- Consider the below image (from [here](https://commons.wikimedia.org/wiki/File:Pontigny_Abbaye.jpg)): [![Pontigny Abbaye](https://i.stack.imgur.com/atGmw.jpg)](https://i.stack.imgur.com/atGmw.jpg) If we run it through [this filter](https://snorpey.github.io/jpg-glitch/) (with settings 44, 7, 21, 83, for anyone who wants to reproduce it), it ends up looking like this: [![Pontigny Abbaye glitched up](https://i.stack.imgur.com/G38uB.png)](https://i.stack.imgur.com/G38uB.png) Your task is to build a program that takes the pixels of a given image and mutilate it in some way to make it look like a computer processing error like above. Your program will take an uncompressed bitmap file (in the format of your choice) and return a "glitched" file of the same uncompressed format. Your program may not make any use of existing image processing libraries. (This is to make sure that the algorithm does not simply flip a few bytes in the file and let the image decompressor do the rest, like JPEG glitch programs usually do.) Your program must also visibly transform existing pixels, rather than simply overlaying noise on the picture. As this is a popularity contest, the program with the highest votes is the winner. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/66417/edit). Closed 8 years ago. [Improve this question](/posts/66417/edit) [Inspiration from Puzzling.SE.](https://puzzling.stackexchange.com/questions/23294/what-is-the-smallest-rectangle-containing-the-squares-of-1-through-100) Suppose we have an *m* × *n* grid such that each element is a base 10 digit. We can read the numbers from such a grid so that we fix a starting element, go to one of the eight nearest coordinates and maintain that direction for zero to five steps. This allows you to read a one to five digit number from a grid if you concatenate the digits. Your task is to write a program finding the smallest *m* × *n* grid from which the squares of the numbers 1 to 100 (inclusive) can be read. For example, if the grid is: ``` 00182 36495 ``` then the squares of `1`-`10` can be read from it, but, for example, `121` is missing. In this rectangle *m* × *n* = 2 × 5 = 10. The winner is the code which generates the smallest grid. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/55853/edit). Closed 8 years ago. [Improve this question](/posts/55853/edit) # The spoak laugh For those who don't know, in Brazil some people laugh on chats like this: aposkpaoskaposkaposkpaokspaoskpaoksa. So here is the challenge: To make a program that generate this laugh in a natural way. # How to produce this laugh programatticaly? When you laugh like this, you use one hand on the `(a, s)` part of the keyboard and the other on the `(k, o, p)` part, randomly hitting the keys on both parts, alterning keys and parts. I will put some laughs here for you to analise. * apsokaposkaposkaposkaposkaposkaposkaposkpaoskaposkpaoskaposkapsokaposkaposk * paoskpaoksaposkaposkaposkaposkaopskaopskaopskpaoskpaoksapokspaoskapsokapsok * aposkaposkpaoskpaoskaposkpaokspoakspaoksopaksopaskpaoskaopskpaoskapsokpasok * paoskpaoskaposkaposkapsokaposkaposkapsokaspokaspoksaposakposakaposkaspokaso * paoskpasokaspokapsokaspokaposkapsokaposkaspokaposkaspoksapaoskpasoksaopksao You have to study this pattern and produce it on your code. # What makes a valid spoak laugh? * In the spoak laugh, a letter ALMOST NEVER repeat twice in a row. So this is mandatory. * Spliting you string on the k, for example, in this javasript: `generated_string.split('k')` has to produce a list of various substring **ranging from 1 to 6 of length** (more on this later) and with **distance of same letter of minimum 3**. Example: `['spaos', 'asopa']`. In both cases the first letter repeats on the substring, but appears with distance of 3 from the repetition.. * There is no restriction to what character should be first or last in each laugh. # Order of the substrings: On a human written spoak laugh of 521 characters, this stats were observed: `Counter({'apos': 30, 'paos': 20, 'apso': 11, 'sapo': 9, 'paso': 6, 'saposa': 6, 'psao': 4, 'sapoa': 3, 'aspo': 2, 'sopsa': 2, 'saop': 1, 'spo': 1, 'opas': 1, 'p oas': 1, 'sapoas': 1, 'aops': 1, 'sa': 1, 'aspos': 1})` We noticed that: * the top 4 are apos = 30, paos = 20, apso = 11 and sapo = 9 * ...followed by paso and saposa both with 6 This means that when breaking the substrings the most occurrences are: **apos and paos** on 1st and 2nd, followed by **paso, sapo, apso and saposa** in any order, then any other combination, following the other rules. # Number of characters of each substring The substrings produced should respect this proportion on a 500 characters spoak laugh: * 1 char = at least 1% * 2 char = at least 1% * 3 char = at least 6% * 4 char = at least 70% * 5 char = at least 6% * 6 char = at least 1% # Validate you laugh on-line. * Enter <http://www.filipeteixeira.com.br/spoak_validator> to validate your generated laugh. * Submit 10 laughs of 500 length each, separated with a semicolon (;). * If you laughs are valid, post you code and the generated link here. # But is this the best way to produce a paoskpaoskaposkpasokaposk laugh? There would be other ways to produce it, but with rapid observation of pattern and statistics, we will stick to these heuristics. # Who wins? Shortest code wins. Have fun, paoskpaoskpoaskpaoskpsao :D ]
[Question] [ Enabling delayed expansion variables in Batch chews up a lot of bytes. The shortest I have managed to make it is: ``` @!! 2>nul||cmd/q/v/c%0&&exit/b ``` Saving 11 bytes over `@echo off&setLocal enableDelayedExpansion`. The method is explained here - [Tips for Golfing in Batch](https://codegolf.stackexchange.com/questions/20614/tips-for-golfing-in-batch/53601#answer-23709). Basically, it runs a command (`!!`) which fails initially (due to no delayed expansion) causing the script to be called again with delayed expansion variables enabled and echo turned off. The command (which is expanded now to 'nothing') then executes successfully, causing the rest of your script to be run. The initial instance of the script then exits. Can this be made any shorter / better? If so, how? One way which I have thought to make it smaller is piping the error output to a file with a one character name, instead of to null (`2>null` becomes `2>f`). However, you then run the risk of overwriting an existing file, as well as generating unwanted output in the form of a file containing the error: `'!!' is not recognized as an internal or external command, operable program or batch file.`. Which I suppose is fine if the challenge doesn't specify output requirements (in which case you can probably drop the redirect all together along with `@` and `/q`).. Suppressing no output you can save a further 9 bytes: `!!||cmd/v/c%0&&exit/b`. And in fact, you could drop the exit and just have the code run again without delayed expansion variables enabled (it won't run correctly the second time, but it will have already run). So if output doesn't matter, you could do something like the following: ``` !!||cmd/v/c%0 set a=test echo !a! ``` Which would output: ``` h:\>test.bat h:\>!! || cmd/v/ctest.bat '!!' is not recognized as an internal or external command, operable program or batch file. h:\>!! || cmd/v/ctest.bat h:\>set a=test h:\>echo !a! test h:\>set a=test h:\>echo !a! !a! ``` (Inspired by [Golfing with Python Import](https://codegolf.stackexchange.com/questions/54194/golfing-with-python-import)) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 8 years ago. [Improve this question](/posts/54085/edit) I found an old [post on Jon Skeet's blog](http://codeblog.jonskeet.uk/2014/01/14/a-tale-of-two-puzzles/) that pointed out a puzzle from a [tweet by Vladimir Reshetnikov](https://twitter.com/vreshetnikov/status/413379258283597824): > > C# quiz: write a valid C# program containing a sequence of three tokens `? null :` that remains valid after we remove the `null`. > > > *Note that the wording "three tokens" is important: `"? null :"` is a single string literal token, and comments are not tokens.* Neither the tweet replies nor the blog comments contain an answer (nor do later tweets or blog posts). I googled and couldn't find any other discussion of the problem aside from those two sources. I wasted over an hour trying different things to no avail, although I suspect it has something to do with Nullable types and case statements or maybe statement labels. This seems right up PCG's alley, so I'll award the check to the first submission that compiles in .Net 4.x (specify version) both with and without the `null` present. ]
[Question] [ # Most Recent Leaderboard @ 2014-08-02 12:00 ``` | Pos # | Author | Name | Language | Score | Win | Draw | Loss | Avg. Dec. Time | +-------+----------------------+-------------------------+------------+-------+-------+-------+-------+----------------+ | 1st | Emil | Pony | Python2 | 064 | 064 | 000 | 005 | 0026.87 ms | | 2nd | Roy van Rijn | Gazzr | Java | 062 | 062 | 001 | 006 | 0067.30 ms | | 2nd | Emil | Dienstag | Python2 | 062 | 062 | 001 | 006 | 0022.19 ms | | 4th | ovenror | TobiasFuenke | Python2 | 061 | 061 | 001 | 007 | 0026.89 ms | | 5th | PhiNotPi | BayesianBot | Perl | 060 | 060 | 000 | 009 | 0009.27 ms | | 6th | Claudiu | SuperMarkov | Python2 | 058 | 058 | 001 | 010 | 0026.77 ms | | 7th | histocrat | Alternator | Ruby | 057 | 057 | 001 | 011 | 0038.53 ms | | 8th | histocrat | LeonardShelby | Ruby | 053 | 053 | 000 | 016 | 0038.55 ms | | 9th | Stretch Maniac | SmarterBot | Java | 051 | 051 | 002 | 016 | 0070.02 ms | | 9th | Martin Büttner | Markov | Ruby | 051 | 051 | 003 | 015 | 0038.45 ms | | 11th | histocrat | BartBot | Ruby | 049 | 049 | 001 | 019 | 0038.54 ms | | 11th | kaine | ExcitingishBot | Java | 049 | 049 | 001 | 019 | 0065.87 ms | | 13th | Thaylon | UniformBot | Ruby | 047 | 047 | 001 | 021 | 0038.61 ms | | 14th | Carlos Martinez | EasyGame | Java | 046 | 046 | 002 | 021 | 0066.44 ms | | 15th | Stretch Maniac | SmartBot | Java | 045 | 045 | 001 | 023 | 0068.65 ms | | 16th | Docopoper | RoboticOboeBotOboeTuner | Python2 | 044 | 044 | 000 | 025 | 0156.55 ms | | 17th | Qwix | Analyst | Java | 043 | 043 | 001 | 025 | 0069.06 ms | | 18th | histocrat | Analogizer | Ruby | 042 | 042 | 000 | 027 | 0038.58 ms | | 18th | Thaylon | Naan | Ruby | 042 | 042 | 004 | 023 | 0038.48 ms | | 20th | Thaylon | NitPicker | Ruby | 041 | 041 | 000 | 028 | 0046.21 ms | | 20th | bitpwner | AlgorithmBot | Python2 | 041 | 041 | 001 | 027 | 0025.34 ms | | 22nd | histocrat | WereVulcan | Ruby | 040 | 040 | 003 | 026 | 0038.41 ms | | 22nd | Ourous | QQ | Cobra | 040 | 040 | 003 | 026 | 0089.33 ms | | 24th | Stranjyr | RelaxedBot | Python2 | 039 | 039 | 001 | 029 | 0025.40 ms | | 25th | JoshDM | SelfLoathingBot | Java | 038 | 038 | 001 | 030 | 0068.75 ms | | 25th | Ourous | Q | Cobra | 038 | 038 | 001 | 030 | 0094.04 ms | | 25th | Ourous | DejaQ | Cobra | 038 | 038 | 001 | 030 | 0078.31 ms | | 28th | Luis Mars | Botzinga | Java | 037 | 037 | 002 | 030 | 0066.36 ms | | 29th | kaine | BoringBot | Java | 035 | 035 | 000 | 034 | 0066.16 ms | | 29th | Docopoper | OboeBeater | Python2 | 035 | 035 | 002 | 032 | 0021.92 ms | | 29th | Thaylon | NaanViolence | Ruby | 035 | 035 | 003 | 031 | 0038.46 ms | | 32nd | Martin Büttner | SlowLizard | Ruby | 034 | 034 | 004 | 031 | 0038.32 ms | | 33rd | Kyle Kanos | ViolentBot | Python3 | 033 | 033 | 001 | 035 | 0032.42 ms | | 34th | HuddleWolf | HuddleWolfTheConqueror | .NET | 032 | 032 | 001 | 036 | 0029.86 ms | | 34th | Milo | DogeBotv2 | Java | 032 | 032 | 000 | 037 | 0066.74 ms | | 34th | Timmy | DynamicBot | Python3 | 032 | 032 | 001 | 036 | 0036.81 ms | | 34th | mccannf | YAARBot | JS | 032 | 032 | 002 | 035 | 0100.12 ms | | 38th | Stranjyr | ToddlerProof | Java | 031 | 031 | 010 | 028 | 0066.10 ms | | 38th | NonFunctional User2..| IHaveNoIdeaWhatImDoing | Lisp | 031 | 031 | 002 | 036 | 0036.26 ms | | 38th | john smith | RAMBOBot | PHP | 031 | 031 | 002 | 036 | 0014.53 ms | | 41st | EoinC | SimpleRandomBot | .NET | 030 | 030 | 005 | 034 | 0015.68 ms | | 41st | Martin Büttner | FairBot | Ruby | 030 | 030 | 006 | 033 | 0038.23 ms | | 41st | Docopoper | OboeOboeBeater | Python2 | 030 | 030 | 006 | 033 | 0021.93 ms | | 44th | undergroundmonorail | TheGamblersBrother | Python2 | 029 | 029 | 000 | 040 | 0025.55 ms | | 45th | DrJPepper | MonadBot | Haskel | 028 | 028 | 002 | 039 | 0008.23 ms | | 46th | Josef E. | OneBehind | Java | 027 | 027 | 007 | 035 | 0065.87 ms | | 47th | Ourous | GitGudBot | Cobra | 025 | 025 | 001 | 043 | 0053.35 ms | | 48th | ProgramFOX | Echo | .NET | 024 | 024 | 004 | 041 | 0014.81 ms | | 48th | JoshDM | SelfHatingBot | Java | 024 | 024 | 005 | 040 | 0068.88 ms | | 48th | Trimsty | Herpetologist | Python3 | 024 | 024 | 002 | 043 | 0036.93 ms | | 51st | Milo | DogeBot | Java | 022 | 022 | 001 | 046 | 0067.86 ms | | 51st | William Barbosa | StarWarsFan | Ruby | 022 | 022 | 002 | 045 | 0038.48 ms | | 51st | Martin Büttner | ConservativeBot | Ruby | 022 | 022 | 001 | 046 | 0038.25 ms | | 51st | killmous | MAWBRBot | Perl | 022 | 022 | 000 | 047 | 0016.30 ms | | 55th | Mikey Mouse | LizardsRule | .NET | 020 | 020 | 007 | 042 | 0015.10 ms | | 55th | ja72 | BlindForesight | .NET | 020 | 020 | 001 | 048 | 0024.05 ms | | 57th | robotik | Evolver | Lua | 019 | 019 | 001 | 049 | 0008.19 ms | | 58th | Kyle Kanos | LexicographicBot | Python3 | 018 | 018 | 003 | 048 | 0036.93 ms | | 58th | William Barbosa | BarneyStinson | Lua | 018 | 018 | 005 | 046 | 0005.11 ms | | 60th | Dr R Dizzle | BartSimpson | Ruby | 017 | 017 | 001 | 051 | 0038.22 ms | | 60th | jmite | IocainePowder | Ruby | 017 | 017 | 003 | 049 | 0038.50 ms | | 60th | ArcticanAudio | SpockOrRock | PHP | 017 | 017 | 001 | 051 | 0014.19 ms | | 60th | Dr R Dizzle | BetterLisaSimpson | Ruby | 017 | 017 | 000 | 052 | 0038.23 ms | | 64th | Dr R Dizzle | LisaSimpson | Ruby | 016 | 016 | 002 | 051 | 0038.29 ms | | 65th | Martin Büttner | Vulcan | Ruby | 015 | 015 | 001 | 053 | 0038.26 ms | | 65th | Dr R Dizzle | Khaleesi | Ruby | 015 | 015 | 005 | 049 | 0038.29 ms | | 67th | Dr R Dizzle | EdwardScissorHands | Ruby | 014 | 014 | 002 | 053 | 0038.21 ms | | 67th | undergroundmonorail | TheGambler | Python2 | 014 | 014 | 002 | 053 | 0025.47 ms | | 69th | cipher | LemmingBot | Python2 | 011 | 011 | 002 | 056 | 0025.29 ms | | 70th | Docopoper | ConcessionBot | Python2 | 007 | 007 | 000 | 062 | 0141.31 ms | +-------+----------------------+-------------------------+------------+-------+-------+-------+-------+----------------+ Total Players: 70 Total Matches Completed: 2415 Total Tourney Time: 06:00:51.6877573 ``` **Tourney Notes** * ***WOO HOO 70 BOTS*** * Emil is still KOTH with `Pony` and his new bot `Dienstag` takes 3rd place * Congrats to Roy for jumping into 2nd place with his `Gazzr` bot * William Barbosa wins the *Quick Draw* award for his bot `BarneyStinson` * And *Slow Poke* award goes to Docopoper for his bots `R.O.B.O.T` and `Concessionbot` who were both >140ms per hand * *Logs available @ <https://github.com/eoincampbell/big-bang-game/blob/master/tourneys/Tournament-2014-08-01-23-24-00.zip?raw=true>* **Excluded Bots** * BashRocksBot - still no joy with .net execing cygwin bash scripts * CounterPreferenceBot - awaiting bug fix * RandomlyWeighted - awaiting bug fix * CasinoShakespeare - excluded because it requires an active internet connection # Original Posted Question You've swung around to your friends house for the most epic showdown Battle ever of Rock, Paper, Scissors, Lizard, Spock. In true BigBang nerd-tastic style, none of the players are playing themselves but have created console bots to play on their behalf. You whip out your USB key and hand it over to the **Sheldor the Conqueror** for inclusion in the showdown. Penny swoons. Or perhaps Howard swoons. We don't judge here at Leonard's apartment. **Rules** Standard Rock, Paper, Scissors, Lizard, Spock rules apply. * Scissors cut Paper * Paper covers Rock * Rock crushes Lizard * Lizard poisons Spock * Spock smashes Scissors * Scissors decapitate Lizard * Lizard eats Paper * Paper disproves Spock * Spock vaporizes Rock * Rock crushes Scissors ![RPSLV Rules](https://i.stack.imgur.com/jILea.png) Each player's bot will play one *Match* against each other bot in the tournament. Each Match will consist of 100 iterations of an RPSLV game. After each match, the winner is the player who has won the most number of games/hands out of 100. If you win a match, you will be assigned 1 point in the league table. In the result of a draw-match, neither player will gain a point. **Bot Requirements** Your bot must be runnable from the command line. Sheldor's \*nix box has died, so we're running it off his windows 8 Gaming Laptop so make sure your provided solution can run on windows. Sheldor has graciously offered to install any required runtimes (within reason) to be able to run your solution. (.NET, Java, Php, Python, Ruby, Powershell ...) **Inputs** In the first game of each match no arguments are supplied to your bot. In each subsequent game of each match: - Arg1 will contain the history of your bots hands/decisions in this match. - Arg2 will contain the history of your opponents hands/decisions in this match. History will be represented by a sequence of single capital letters representing the possible hands you can play. ``` | R | Rock | | P | Paper | | S | Scissors | | L | Lizard | | V | Spock | ``` E.g. * Game 1: MyBot.exe * Game 2: MyBot.exe S V * Game 3: MyBot.exe SS VL * Game 4: MyBot.exe SSR VLS **Output** Your bot must write a single character response representing his "hand" for each game. The result should be written to STDOUT and the bot should then exit. Valid single capital letters are below. ``` | R | Rock | | P | Paper | | S | Scissors | | L | Lizard | | V | Spock | ``` In the case where your bot does not return a valid hand (i.e. 1 of the above 5 single capital letters, then you automatically forfeit that hand and the match continues. In the case where both bots do not return a valid hand, then the game is considered a draw and the match continues. **Match Format** Each submitted bot will play one match against each other bot in the tournament. Each match will last exactly 100 games. Matches will be played anonymously, you will not have an advanced knowledge of the specific bot you are playing against, however you may use any and all information you can garner from his decision making during the history of the current match to alter your strategy against your opponent. You may also track history of your previous games to build up patterns/heuristics etc... (See rules below) During a single game, the orchestration engine will run your bot and your opponents bot 100 milliseconds apart and then compare the results in order to avoid any PRNG collisions in the same language/runtime. (this actually happened me during testing). **Judging & Constraints** Dr. Sheldon Cooper in the guise of Sheldor the Conqueror has kindly offered to oversee the running of the tournament. Sheldor the Conqueror is a fair and just overseer (mostly). All decisions by Sheldor are final. Gaming will be conducted in a fair and proper manner: * Your bot script/program will be stored in the orchestration engine under a subfolder `Players\[YourBotName]\` * You may use the subfolder `Players\[YourBotName]\data` to log any data or game history from the current tournament as it proceeds. Data directories will be purged at the start of each tournament run. * You may not access the Player directory of another player in the tournament * Your bot cannot have specific code which targets another specific bots behavior * Each player may submit more than one bot to play so long as they do not interact or assist one another. **Edit - Additional Constraints** * Regarding forfeits, they won't be supported. Your bot must play one of the 5 valid hands. I'll test each bot outside of the tournament with some random data to make sure that they behave. Any bots that throw errors (i.e. forfeits errors) will be excluded from the tourney til they're bug fixed. * Bots may be derivative so long as they are succinctly different in their behaviour. Bots (including in other languages) that perform exactly the same behaviour as an existing bot will be disqualified * There are already spam bots for the following so please don't resubmit * + Rock - BartSimpson * + Paper - LisaSimpson * + Scissor - EdwardScissorhands * + Spock - Vulcan * + Lizard - Khaleesi * + Pseudo Random - SimpleRandomBot & FairBot * + Psuedo Random RPS - ConservativeBot * + Psuedo Random LV - Barney Stinson * Bots may not call out to 3rd party services or web resources (or anything else which significantly slows down the speed/decision making time of the matches). `CasinoShakespeare` is the only exception as that bot was submitted prior to this constraint being added. Sheldor will update this question as often as he can with Tournament results, as more bots are submitted. **Orchestration / Control Program** The orchestration program, along with source code for each bot is available on github. <https://github.com/eoincampbell/big-bang-game> **Submission Details** Your submission should include * Your Bot's name * Your Code * A command to + execute your bot from the shell e.g. + ruby myBot.rb + python3 myBot.py + OR + first compile your both and then execute it. e.g. + csc.exe MyBot.cs + MyBot.exe **Sample Submission** ``` BotName: SimpleRandomBot Compile: "C:\Program Files (x86)\MSBuild\12.0\Bin\csc.exe" SimpleRandomBot.cs Run: SimpleRandomBot [Arg1] [Arg2] ``` Code: ``` using System; public class SimpleRandomBot { public static void Main(string[] args) { var s = new[] { "R", "P", "S", "L", "V" }; if (args.Length == 0) { Console.WriteLine("V"); //always start with spock return; } char[] myPreviousPlays = args[0].ToCharArray(); char[] oppPreviousPlays = args[1].ToCharArray(); Random r = new Random(); int next = r.Next(0, 5); Console.WriteLine(s[next]); } } ``` **Clarification** Any questions, ask in the comments below. [Answer] # Pony (Python 2) This is based on a rock-paper-scissors bot I wrote some time ago for a programming challenge at the end of a [Udacity online class](https://www.udacity.com/course/cs212). I changed it to include Spock and lizard and made some improvements. The program has 11 different simple strategies, each with 5 variants. It chooses from among these based on how well they would have performed over the last rounds. I removed a fallback strategy that just played random against stronger opponents. I guess it's more fun like this. ``` import sys # just play Spock for the first two rounds if len(sys.argv)<2 or len(sys.argv[1])<2: print 'V'; sys.exit() # initialize and translate moves to numbers for better handling: my_moves, opp_moves = sys.argv[1], sys.argv[2] moves = ('R', 'P', 'S', 'V', 'L') history = zip([moves.index(i) for i in my_moves], [moves.index(i) for i in opp_moves]) # predict possible next moves based on history def prediction(hist): N = len(hist) # find longest match of the preceding moves in the earlier history cand_m = cand_o = cand_b = range(N-1) for l in xrange(1,min(N, 20)): ref = hist[N-l] cand_m = ([c for c in cand_m if c>=l and hist[c-l+1][0]==ref[0]] or cand_m[-1:]) cand_o = ([c for c in cand_o if c>=l and hist[c-l+1][1]==ref[1]] or cand_o[-1:]) cand_b = ([c for c in cand_b if c>=l and hist[c-l+1]==ref] or cand_b[-1:]) # analyze which moves were used how often freq_m, freq_o = [0]*5, [0]*5 for m in hist: freq_m[m[0]] += 1 freq_o[m[1]] += 1 # return predictions return ([hist[-i][p] for i in 1,2 for p in 0,1]+ # repeat last moves [hist[cand_m[-1]+1][0], # history matching of my own moves hist[cand_o[-1]+1][1], # history matching of opponent's moves hist[cand_b[-1]+1][0], # history matching of both hist[cand_b[-1]+1][1], freq_m.index(max(freq_m)), # my most frequent move freq_o.index(max(freq_o)), # opponent's most frequent move 0]) # good old rock (and friends) # what would have been predicted in the last rounds? pred_hist = [prediction(history[:i]) for i in xrange(2,len(history)+1)] # how would the different predictions have scored? n_pred = len(pred_hist[0]) scores = [[0]*5 for i in xrange(n_pred)] for pred, real in zip(pred_hist[:-1], history[2:]): for i in xrange(n_pred): scores[i][(real[1]-pred[i]+1)%5] += 1 scores[i][(real[1]-pred[i]+3)%5] += 1 scores[i][(real[1]-pred[i]+2)%5] -= 1 scores[i][(real[1]-pred[i]+4)%5] -= 1 # return best counter move best_scores = [list(max(enumerate(s), key=lambda x: x[1])) for s in scores] best_scores[-1][1] *= 1.001 # bias towards the simplest strategy if best_scores[-1][1]<0.4*len(history): best_scores[-1][1] *= 1.4 strat, (shift, score) = max(enumerate(best_scores), key=lambda x: x[1][1]) print moves[(pred_hist[-1][strat]+shift)%5] ``` Run as: ``` python Pony.py ``` *Edit*: I made a small change by putting in a bias towards the simplest strategy (i.e. always play the same move) in unsure cases. This helps a bit to not try to find overly complicated patterns where there are none, e.g. in bots like ConservativeBot. *Note*: I tried to explain the basic history matching strategy that this bot uses in the post for my other bot [Dienstag](https://codegolf.stackexchange.com/a/35509/29703). [Answer] ## ConservativeBot, Ruby New things are bad things. ``` puts ['R','P','S'].sample ``` Run like ``` ruby conservative.rb ``` [Answer] ## Markov, Ruby Looks at the opponent's last two moves and determines the possible (and most likely) follow ups. If the combination hasn't been picked before, he just uses all of the opponent's moves (so far) instead. Then he collects all the possible responses for these and picks a random one. ``` responses = { 'R' => ['P', 'V'], 'P' => ['S', 'L'], 'S' => ['R', 'V'], 'L' => ['S', 'R'], 'V' => ['P', 'L'] } if ARGV.length == 0 || (history = ARGV[1]).length < 3 choices = ['R','P','S','L','V'] else markov = Hash.new [] history.chars.each_cons(3) { |chars| markov[chars[0..1].join] += [chars[2]] } choices = [] likely_moves = markov.key?(history[-2,2]) ? markov[history[-2,2]] : history.chars likely_moves.each { |move| choices += responses[move] } end puts choices.sample ``` Run like ``` markov.rb ``` [Answer] ## Star Wars Fan - Ruby Screw you, Spock ``` puts ['R','P','L','S'].sample ``` Run it like: ``` ruby starwarsfan.rb ``` [Answer] ## Barney Stinson - Lua I only have one rule: New is always better. Screw old Jo Ken Po or whatever you call it. ``` math.randomseed(os.time()) print(math.random() > 0.5 and "V" or "L") ``` Run it like: ``` lua legenwaitforitdary.lua ``` [Answer] ## IocainePowder, Ruby ![enter image description here](https://i.stack.imgur.com/k4WXZ.jpg) Based off (shamelessly stolen from) the RPS strategy [here](http://dan.egnor.name/iocaine.html). The bot looks chooses a guess identical to the Markov bot, but then assumes the opponent has guessed what it's going to choose, and chooses a move to beat that one accordingly. Note that I've just adapted the basic idea of the linked strategy, not followed it in detail. ``` responses = { 'R' => ['P', 'V'], 'P' => ['S', 'L'], 'S' => ['R', 'V'], 'L' => ['S', 'R'], 'V' => ['P', 'L'] } if ARGV.length == 0 || (history = ARGV[1]).length < 3 choices = ['R','P','S','L','V'] else markov = Hash.new [] history.chars.each_cons(3) { |chars| markov[chars[0..1].join] += [chars[2]] } choices = [] likely_moves = markov.key?(history[-2,2]) ? markov[history[-2,2]] : history.chars likely_moves.each { |move| choices += responses[move] } end myChoice = choices.sample theirChoice = responses[myChoice].sample actualChoice = responses[theirChoice].sample puts actualChoice ``` Run like ``` iocaine.rb ``` [Answer] # Boring Bot (Java) He assumes everyone always plays the same thing and plans accordingly. He usually picks rocks in a ties though ’cause so does everyone else right? ``` public class BoringBot { public static void main(String[] args) { int Rock=0; int Paper=0; int Scissors=0; int Lizard=0; int Spock=0; if (args.length == 0) { System.out.print("P"); return; } char[] oppPreviousPlays = args[1].toCharArray(); for (int j=0; j<oppPreviousPlays.length; j++) { switch(oppPreviousPlays[j]){ case 'R': Rock++; break; case 'P': Paper++; break; case 'S': Scissors++; break; case 'L': Lizard++; break; case 'V': Spock++; } } int Best = Math.max(Math.max(Lizard+Scissors-Spock-Paper, Rock+Spock-Lizard-Scissors), Math.max(Math.max(Paper+Lizard-Spock-Rock, Paper+Spock-Rock-Scissors), Rock+Scissors-Paper-Lizard)); if (Best== Lizard+Scissors-Spock-Paper){ System.out.print("R"); return; } else if (Best== Rock+Spock-Lizard-Scissors){ System.out.print("P"); return; } else if (Best== Paper+Lizard-Spock-Rock){ System.out.print("S"); return; } else if(Best== Paper+Spock-Rock-Scissors){ System.out.print("L"); return; } else { System.out.print("V"); return; } } } ``` [Answer] ## HuddleWolfTheConqueror - C# HuddleWolf is back and better than ever. He will beat Sheldor the Conqueror at his own silly game. HuddleWolf is smart enough to identify and counter spammerbots. For more intelligent opponents, HuddleWolf uses his knowledge of basic 5th grade statistics and utilizes a weighted dice roll based on the opposition's history of plays. ``` using System; using System.Collections.Generic; using System.Linq; public class HuddleWolfTheConqueror { public static readonly char[] s = new[] { 'R', 'P', 'S', 'L', 'V' }; public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine(pickRandom()); return; } char[] myPlays = args[0].ToCharArray(); char[] oppPlays = args[1].ToCharArray(); char tryPredict = canPredictCounter(oppPlays); if (tryPredict != '^') { Console.WriteLine(tryPredict); } else { Console.WriteLine(pickRandom()); } return; } public static char canPredictCounter(char[] history) { // don't predict if insufficient data if (history.Length < 5) { return '^'; } // calculate probability of win for each choice Dictionary<char, double> dic = getBestProabability(history); // get item with highest probability of win List<char> maxVals = new List<char>(); char maxVal = '^'; double mostFreq = 0; foreach (var kvp in dic) { if (kvp.Value > mostFreq) { mostFreq = kvp.Value; } } foreach (var kvp in dic) { if (kvp.Value == mostFreq) { maxVals.Add(kvp.Key); } } // return error if (maxVals.Count == 0) { return maxVal; } // if distribution is not uniform, play best play if (maxVals.Count <= 3) { Random r = new Random(Environment.TickCount); return maxVals[r.Next(0, maxVals.Count)]; } // if probability is close to uniform, use weighted dice roll if (maxVals.Count == 4) { return weightedRandom(dic); } // if probability is uniform, use random dice roll if (maxVals.Count >= 5) { return pickRandom(); } // return error return '^'; } public static Dictionary<char, double> getBestProabability(char[] history) { Dictionary<char, double> dic = new Dictionary<char, double>(); foreach (char c in s) { dic.Add(c, 0); } foreach (char c in history) { if (dic.ContainsKey(c)) { switch(c) { case 'R' : dic['P'] += (1.0/(double)history.Length); dic['V'] += (1.0/(double)history.Length); break; case 'P' : dic['S'] += (1.0/(double)history.Length); dic['L'] += (1.0/(double)history.Length); break; case 'S' : dic['V'] += (1.0/(double)history.Length); dic['R'] += (1.0/(double)history.Length); break; case 'L' : dic['R'] += (1.0/(double)history.Length); dic['S'] += (1.0/(double)history.Length); break; case 'V' : dic['L'] += (1.0/(double)history.Length); dic['P'] += (1.0/(double)history.Length); break; default : break; } } } return dic; } public static char weightedRandom(Dictionary<char, double> dic) { Random r = new Random(Environment.TickCount); int next = r.Next(0, 100); int curVal = 0; foreach (var kvp in dic) { curVal += (int)(kvp.Value*100); if (curVal > next) { return kvp.Key; } } return '^'; } public static char pickRandom() { Random r = new Random(Environment.TickCount); int next = r.Next(0, 5); return s[next]; } } ``` [Answer] # ToddlerProof This fairly stupid bot assumes it is playing a toddler who will "chase" its moves, always trying to beat whatever was last thrown. If the bot is beaten several times in a row, it jumps to a new point in the pattern. It is based on my strategy for always beating my *much* younger brother. :) **EDIT::** Changed the length of a loss streak required to jump into random throws. Also fixed a major bug with the random jump. Save as `ToddlerProof.java`, compile, then run with `java ToddlerProof [me] [them]` ``` import java.util.HashMap; public class ToddlerProof { char[] moves = new char[]{'R', 'P', 'S', 'L', 'V'}; public static void main(String[] args) { if(args.length<1) //first Round { System.out.print('V');//Spock is best return; } else { String them = args[1]; String me = args[0]; int streak = 0; HashMap<Character, Character> nextMove = new HashMap<Character, Character>(); //Next move beats things that beat my last move nextMove.put('L', 'V'); nextMove.put('V', 'S'); nextMove.put('S', 'P'); nextMove.put('P', 'R'); nextMove.put('R', 'L'); //Check if last round was a tie or the opponent beat me int lastResult = winner(me.charAt(me.length()-1), them.charAt(them.length()-1)); if(lastResult == 0) { //tie, so they will chase my last throw System.out.print(nextMove.get(me.charAt(me.length()-1))); return; } else if(lastResult == 1) { //I won, so they will chase my last throw System.out.print(nextMove.get(me.charAt(me.length()-1))); return; } else{ //I lost //find streak for(int i = 0; i<me.length(); i++) { int a = winner(me.charAt(i), them.charAt(i)); if(a >= 0) streak = 0; else streak++; } //check lossStreak //If the streak is 2, then a rotation will make it even. //if it is >2, something bad has happened and I need to adjust. if(streak>2) { //if they are on to me, do something random-ish int r = (((them.length()+me.length()-1)*13)/7)%4; System.out.print(move[r]); return; } //otherwise, go on with the plan System.out.print(nextMove.get(me.charAt(me.length()-1))); return; } } } public static int winner(char me, char them) { //check for tie if(me == them) return 0; //check if they won if(me=='V' && (them == 'L' || them == 'P')) return -1; if(me=='S' && (them == 'V' || them == 'R')) return -1; if(me=='P' && (them == 'S' || them == 'L')) return -1; if(me=='R' && (them == 'P' || them == 'V')) return -1; if(me=='L' && (them == 'R' || them == 'S')) return -1; //otherwise, I won return 1; } } ``` [Answer] ## Bart Simpson "Good old rock! Nothing beats rock!" ``` puts 'R' ``` Run as ``` ruby DoTheBartman.rb ``` --- ## Lisa Simpson "Poor, predictable Bart. Always chooses rock." ``` puts 'P' ``` Run as ``` ruby LisaSimpson.rb ``` --- ## Better Lisa Simpson I felt bad about making Lisa quite so stupid, so I allowed her to randomly choose between either of the hands that will beat rock. Still stupid, but she is a Simpson after all. Maybe a crayon got stuck in her brain? ``` puts ['P','V'].sample ``` Run as ``` ruby BetterLisaSimpson.rb ``` [Answer] # Echo Written in C#. Compile with `csc Echo.cs`. Run like `Echo.exe ARG1 ARG2`. The first run, Echo takes a random option. Every run after the first, Echo simply repeats the opponent's latest action. ``` using System; namespace Echo { class Program { static void Main(string[] args) { if (args.Length == 0) { Random r = new Random(); string[] options = new string[] { "R", "P", "S", "L", "V" }; Console.WriteLine(options[r.Next(0, options.Length)]); } else if (args.Length == 2) { string opponentHistory = args[1]; Console.WriteLine(opponentHistory[opponentHistory.Length - 1]); } } } } ``` [Answer] ## Vulcan, Ruby My fingers are glued together. ``` puts 'V' ``` Run like ``` ruby vulcan.rb ``` (I think this is the only in-character strategy for your background setting.) [Answer] Tyrannosaurus, Godzilla, Barney... Lizards Rule. Occasionally they get in trouble and need to call Spock or throw Rocks ``` using System; public class LizardsRule { public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("L"); return; } char[] oppPreviousPlays = args[1].ToCharArray(); var oppLen = oppPreviousPlays.Length; if (oppPreviousPlays.Length > 2 && oppPreviousPlays[oppLen - 1] == 'R' && oppPreviousPlays[oppLen - 2] == 'R' && oppPreviousPlays[oppLen - 3] == 'R') { //It's an avalance, someone call Spock Console.WriteLine("V"); return; } if (oppPreviousPlays.Length > 2 && oppPreviousPlays[oppLen - 1] == 'S' && oppPreviousPlays[oppLen - 2] == 'S' && oppPreviousPlays[oppLen - 3] == 'S') { //Scissors, Drop your tail and pick up a rock Console.WriteLine("R"); return; } //Unleash the Fury Godzilla Console.WriteLine("L"); } } ``` [Answer] # BayesianBot, Perl (now v2!) Above everything else, this is a unique program. In it, you shall see the brilliant fusion of statistics and horrible programming form. Also, this bot probably breaks many rules of Bayesian statistics, but the name sounds cooler. The core essence of this bot is its creation of 250 different predictive models. Each model takes the form of *"Given that I played rock last turn and my opponent played scissors two turns ago, this is the probability distribution for my opponent's next move."* Each probability distribution takes the form of a multi-dimensional Dirichlet distribution. Each turn, the predictions of all applicable models (typically 10) are multiplied together to form an overall prediction, which is then used to determine which moves have the highest expected payoff. Edit 1: In this version, I changed the prior distribution and made the bot more randomized when it is losing. There are a few things which may be subject to improvement, such as the number of models (250 is only a 3 digit number), the choice of prior distribution (currently Dir(3,3,3,3,3)), and the method of fusing predictions. Also, I never bothered to normalize any of the probability distributions, which is okay for now because I'm multiplying them. I don't have super high expectations, but I hope this bot will be able to do well. ``` my ($phist, $ohist) = @ARGV; my %text2num = ('R',0,'V',1,'P',2,'L',3,'S',4); #the RVPLS ordering is superior my @num2text = ('R','V','P','L','S'); @phist = map($text2num{$_},split(//,$phist)); @ohist = map($text2num{$_},split(//,$ohist)); $lowerlimit = 0; for($lowerlimit..~~@phist-3){$curloc=$_; $result = $ohist[$curloc+2]; @moveset = ($ohist[$curloc],$ohist[$curloc+1],$phist[$curloc],$phist[$curloc+1]); for(0..3){$a=$_; for(0..$a){$b=$_; $predict[$a][$b][$moveset[$a]][$moveset[$b]][$result]++; } } } @recentmoves = ($ohist[-2],$ohist[-1],$phist[-2],$phist[-1]); @curpred = (1,1,1,1,1); for(0..3){$a=$_; for(0..$a){$b=$_; for(0..4){$move=$_; $curpred[$move] *= $predict[$a][$b][$recentmoves[$a]][$recentmoves[$b]][$move]/3+1; } } } @bestmove = (0,0,0,0,0); for(0..4){ $bestmove[$_] = $curpred[$_]/2+$curpred[$_-1]+$curpred[$_-2]; } $max = 0; for(0..4){ if($bestmove[$_]>$max){ $max = $bestmove[$_]; } } @options=(); $offset=0; if(($ohist[-1] - $phist[-1])%5 < 2 && ($ohist[-2] - $phist[-2])%5 < 2 && ($ohist[-3] - $phist[-3])%5 < 2){ #frequentist alert! $offset=int(rand(3)); } for(0..4){ if($bestmove[$_] == $max){ push(@options,$num2text[($_+$offset)%5]); } } $outputb = $options[int(rand(~~@options))]; print "$outputb"; ``` I've been running this program like so: ``` perl BayesianBot.plx ``` [Answer] ## DynamicBot Dynamic bot is almost always changing. It really hates repeating itself ``` import sys, random choices = ['L','V','S','P','R'] * 20 if len(sys.argv) > 1: my_history = sys.argv[1] [choices.remove(my_history[-1]) for i in range(15)] print(choices[random.randrange(len(choices))]) ``` Language: Python 3.4.1 Command: `python dynamicbot.py <history>` or `python3 dynamicbot.py <history>` depending on your system [Answer] # SmartBot - Java My first ever entry for anything on this site! Though not a very creative name... SmartBot finds sequences of moves where the opponent and/or itself's moves are similar to the moves last made and plans accordingly. `name = SmartBot` I think to run it, correct me if I am wrong. `java -jar SmartBot.jar` ``` import java.util.ArrayList; public class SmartBot { public static void main(String[] args) { if(args.length ==0){ System.out.print("L"); return; } if(args[0].length()<3){ String[] randLetter = new String[]{"R","P","S","L","V"}; System.out.print(randLetter[(int) Math.floor(Math.random()*5)]); return; } String myHistory = args[0]; String otherHistory = args[1]; double rScore,pScore,sScore,lScore,vScore;//score - highest = highest probability of next opponent move rScore = pScore = sScore = lScore = vScore = 0; lScore = .001; ArrayList<ArrayList<Integer>> moveHits = new ArrayList<ArrayList<Integer>>(); for(int g = 0;g<2;g++){ for(int i=1;i<(myHistory.length() / 2) + 1;i++){ if(g==0){ moveHits.add(findAll(myHistory.substring(myHistory.length() - i),myHistory)); } else{ moveHits.add(findAll(otherHistory.substring(otherHistory.length() - i),otherHistory)); } } for(int i = 0; i < moveHits.size();i++){ int matchingMoves = i+1; ArrayList<Integer> moveIndexes = moveHits.get(i); for(Integer index:moveIndexes){ if(index+matchingMoves +1<= otherHistory.length()){ char nextMove = otherHistory.charAt(index + matchingMoves-1); if(nextMove=='R'){rScore = rScore + matchingMoves;} if(nextMove=='P'){pScore = pScore + matchingMoves;} if(nextMove=='S'){sScore = sScore + matchingMoves;} if(nextMove=='L'){lScore = lScore + matchingMoves;} if(nextMove=='V'){vScore = vScore + matchingMoves;} } } } } if(rScore >= pScore && rScore >= sScore && rScore >= lScore && rScore >= vScore){ System.out.print("V"); return; } if(pScore >= rScore && pScore >= sScore && pScore >= lScore && pScore >= vScore){ System.out.print("L"); return; } if(sScore >= pScore && sScore >= rScore && sScore >= lScore && sScore >= vScore){ System.out.print("R"); return; } if(vScore >= pScore && vScore >= sScore && vScore >= lScore && vScore >= rScore){ System.out.print("L"); return; } if(lScore >= pScore && lScore >= sScore && lScore >= rScore && lScore >= vScore){ System.out.print("S"); } return; } public static ArrayList<Integer> findAll(String substring,String realString){ ArrayList<Integer> ocurrences = new ArrayList<Integer>(); Integer index = realString.indexOf(substring); if(index==-1){return ocurrences;} ocurrences.add(index+1); while(index!=-1){ index = realString.indexOf(substring,index + 1); if(index!=-1){ ocurrences.add(index+1); } } return ocurrences; } } ``` It assigns a score for each possible next move by the number of times similar patterns have happened. It slightly favors lizard. [Answer] # SpockOrRock - PHP ![SpockOrRock](https://i.stack.imgur.com/IxPbu.jpg) When played in the real world, most people instinctively pick scissors. This bot picks either Spock or Rock to beat the average player. It's not bothered about previous rounds. run with `php spockorrock.php` ``` <?php //Pick either Spock or Rock if (rand(0,1) == 0) echo("R\n"); else echo("V\n"); ?> ``` [Answer] ## SlowLizard, Ruby After starting with Lizard, it always picks a random move which beats the opponent's previous move. ``` responses = { 'R' => ['P', 'V'], 'P' => ['S', 'L'], 'S' => ['R', 'V'], 'L' => ['S', 'R'], 'V' => ['P', 'L'] } if ARGV.length == 0 puts 'L' else puts responses[ARGV[1][-1]].sample end ``` Run like ``` ruby slowlizard.rb ``` [Answer] # LexicographicBot This bot likes to order his letters, so he will choose a response that is 1 higher than his opponent gave in the previous round--unless the opponent chose Vulcan, then he randomly picks a response. ``` import sys import random choices = ["L", "P", "R", "S", "V"] total = len(sys.argv) if total==1: print("L") sys.exit() opponent = sys.argv[2] opponent_last = opponent[-1] if opponent_last == choices[-1]: print(random.choice(choices)) else: next = choices.index(opponent_last)+1 print(choices[next]) ``` This expects the opponent hand to be dealt second: ``` me v python LexicographicBot.py SR RV ^ opponent ``` [Answer] # Werevulcan - Ruby Run as `ruby werevulcan.rb` ``` @rules = { 'L' => %w[V P], 'P' => %w[V R], 'R' => %w[L S], 'S' => %w[P L], 'V' => %w[R S] } @moves = @rules.keys def defeats?(move1, move2) @rules[move1].include?(move2) end def score(move1, move2) if move1 == move2 0 elsif defeats?(move1, move2) 1 else -1 end end def move player, opponent = ARGV # For the first 30 rounds, pick a random move that isn't Spock if player.to_s.size < 30 %w[L P R S].sample elsif opponent.chars.to_a.uniq.size < 5 exploit(opponent) else # Pick a random move that's biased toward Spock and against lizards %w[L P P R R S S V V V].sample end end def exploit(opponent) @moves.shuffle.max_by{ |m| opponent.chars.map{|o| score(m,o) }.reduce(:+) } end puts move ``` The werevulcan looks normal by day, but when the moon rises, its ears grow pointy, and its moves grow more logical. [Answer] # Analogizer - Ruby Run with `ruby analogizer.rb`. I've made a logic fix to the code, but no idea why there were errors with this. ``` @rules = { 'L' => %w[V P], 'P' => %w[V R], 'R' => %w[L S], 'S' => %w[P L], 'V' => %w[R S] } @moves = @rules.keys def defeats?(move1, move2) @rules[move1].include?(move2) end def score(move1, move2) if move1 == move2 0 elsif defeats?(move1, move2) 1 else -1 end end def move player, opponent = ARGV case player.to_s.size # Throw six lizards in the beginning to confuse opponent when 0..5 'L' when 6 'V' when 7 'S' when 8 'P' when 9 'R' else analyze_history(player.chars.to_a, opponent.chars.to_a) end end def analyze_history(player, opponent) my_last_move = player.last predicted_moves = Hash.new {0} opponent_reactions = player.zip(opponent.drop(1)) # Check whether opponent tended to make a move that would've beaten, lost, or tied my last move opponent_reactions.each do |my_move, reaction| score = score(reaction, my_move) analogous_moves = @moves.select { |move| score == score(move, my_last_move) } analogous_moves.each { |move| predicted_moves[move] += 1 } end # Assume if an opponent has never made a certain move, it never will @moves.each { |m| predicted_moves[m] = 0 unless opponent.include?(m) } # Pick the move with the best score against opponent's possible moves, weighted by their likelihood, picking randomly for ties @moves.shuffle.max_by{ |m| predicted_moves.map { |predicted, freq| score(m, predicted) * freq }.reduce(0,:+) } end puts move ``` Assumes the opposing bot is always reacting to my previous move, and either picking something that would beat it, something that would lose to it, or the same move, possibly from a restricted set of possible moves. It then picks the best move given that assumption. Except that the first ten moves are hardcoded: first I pretend I only know lizard, then I assume my opponent always throws something to beat the last thing I threw until I have enough data for proper analysis. [Answer] # Java - SelfLoathingBot ``` BotName: SelfLoathingBot Compile: Save as 'SelfLoathingBot.java'; compile. Run: java SelfLoathingBot [me] [them] ``` Bot starts randomly, then ~33% to go random, or ~33% to play a winning tactic against either of the immediately prior plays, with 50% choice of winning tactic. ``` import java.util.Random; public class SelfLoathingBot { static final Random RANDOM = new Random(); private static char randomPlay() { switch (RANDOM.nextInt(5)) { case 0 : return 'R'; case 1 : return 'P'; case 2 : return 'S'; case 3 : return 'L'; default : return 'V'; } } private static char antiPlay(String priorPlayString) { char[] priorPlays = priorPlayString.toCharArray(); int choice = RANDOM.nextInt(2); switch (priorPlays[priorPlays.length - 1]) { case 'R' : return choice == 0 ? 'P' : 'V'; case 'P' : return choice == 0 ? 'S' : 'L'; case 'S' : return choice == 0 ? 'V' : 'R'; case 'L' : return choice == 0 ? 'R' : 'S'; default : return choice == 0 ? 'L' : 'P'; // V } } public static void main(String[] args) { int choice = args.length == 0 ? 0 : RANDOM.nextInt(3); char play; switch (choice) { case 1 : // 33.3% chance Play myself play = antiPlay(args[0]); break; case 2 : // 33.3% chance Play opponent just in case opponent is screwy like that play = antiPlay(args[1]); break; default : // 33.3% chance 100% Random play = randomPlay(); } System.out.print(play); return; } } ``` [Answer] # The Analyst The analyst analyzes some stuff and does some things to try to beat you. compile with `javac Analyst.java` and run as `java Analyst` ``` import java.util.Random; public class Analyst{ public static void main(String[] args){ char action = 'S'; try{ char[] enemyMoves = null, myMoves = null; //first move is random if(args.length == 0){ System.out.print(randomMove()); System.exit(0); //moves 2-3 will beat their last move }else if(args[0].length() < 8){ System.out.print(counterFor(args[1].charAt(args[1].length()-1))); System.exit(0); //following moves will execute some analyzation stuff }else{ //get previous moves myMoves = args[0].toCharArray(); enemyMoves = args[1].toCharArray(); } //test if they're trying to beat our last move if(beats(enemyMoves[enemyMoves.length-1], myMoves[myMoves.length-2])){ action = counterFor(counterFor(myMoves[myMoves.length-1])); } //test if they're copying our last move else if(enemyMoves[enemyMoves.length-1] == myMoves[myMoves.length-2]){ action = counterFor(myMoves[myMoves.length-1]); } //else beat whatever they've done the most of else{ action = counterFor(countMost(enemyMoves)); } //if they've beaten us for the first 40 moves, do the opposite of what ive been doing if(theyreSmarter(myMoves, enemyMoves)){ action = counterFor(action); } //if you break my program do something random }catch (Exception e){ action = randomMove(); } System.out.print(action); } private static char randomMove(){ Random rand = new Random(System.currentTimeMillis()); int randomMove = rand.nextInt(5); switch (randomMove){ case 0: return 'R'; case 1: return 'P'; case 2: return 'S'; case 3: return 'L'; default: return 'V'; } } private static char counterFor(char move){ Random rand = new Random(System.currentTimeMillis()); int moveSet = rand.nextInt(2); if(moveSet == 0){ switch (move){ case 'R': return 'P'; case 'P': return 'S'; case 'S': return 'R'; case 'L': return 'R'; default: return 'P'; } }else{ switch (move){ case 'R': return 'V'; case 'P': return 'L'; case 'S': return 'V'; case 'L': return 'S'; default: return 'L'; } } } private static boolean beats(char move1, char move2){ if(move1 == 'R'){ if((move2 == 'S') || (move2 == 'L')){ return true; }else{ return false; } }else if(move1 == 'P'){ if((move2 == 'R') || (move2 == 'V')){ return true; }else{ return false; } }else if(move1 == 'S'){ if((move2 == 'L') || (move2 == 'P')){ return true; }else{ return false; } }else if(move1 == 'L'){ if((move2 == 'P') || (move2 == 'V')){ return true; }else{ return false; } }else{ if((move2 == 'R') || (move2 == 'S')){ return true; }else{ return false; } } } private static char countMost(char[] moves){ int[] enemyMoveList = {0,0,0,0,0}; for(int i=0; i<moves.length; i++){ if(moves[i] == 'R'){ enemyMoveList[0]++; }else if(moves[i] == 'P'){ enemyMoveList[1]++; }else if(moves[i] == 'S'){ enemyMoveList[2]++; }else if(moves[i] == 'L'){ enemyMoveList[3]++; }else if(moves[i] == 'V'){ enemyMoveList[4]++; } } int max = 0, maxIndex = 0; for(int i=0; i<5; i++){ if(enemyMoveList[i] > max){ max = enemyMoveList[i]; maxIndex = i; } } switch (maxIndex){ case 0: return 'R'; case 1: return 'P'; case 2: return 'S'; case 3: return 'L'; default: return 'V'; } } private static boolean theyreSmarter(char[] myMoves, char[] enemyMoves){ int loseCounter = 0; if(enemyMoves.length >= 40){ for(int i=0; i<40; i++){ if(beats(enemyMoves[i],myMoves[i])){ loseCounter++; } } }else{ return false; } if(loseCounter > 20){ return true; }else{ return false; } } } ``` [Answer] # The Gambler - Python 2 ``` import sys import random MODE = 1 moves = 'RSLPV' def element_sums(a, b): return [a[i] + b[i] for i in xrange(len(a))] def move_scores(p): def calc(to_beat): return ['LDW'.find('DLLWW'[moves.find(m)-moves.find(to_beat)]) for m in moves] return dict(zip(moves, element_sums(calc(p[0]), calc(p[1])))) def move_chooser(my_history, opponent_history): predict = sorted(moves, key=opponent_history.count, reverse=MODE)[-2:] scores = move_scores(predict) return max(scores, key=lambda k:scores[k]) if __name__ == '__main__': if len(sys.argv) == 3: print move_chooser(*sys.argv[1:]) elif len(sys.argv) == 1: print random.choice(moves) ``` Contrary to the name, the only time randomness is used in this program is on the first round, when there's no information. Instead, it's named for the gambler's fallacy, the belief that if a random event has happened less often in the past, it's more likely to happen in the future. For example, if you flip a fair coin 20 times, and the first 15 are heads, the gambler's fallacy states that the odds of the remaining flips being tails are increased. Of course, this is untrue; regardless of the previous flips, a fair coin's odds of coming up tails is always 50%. This program analyzes the opponent's history, finds the 2 moves that it has used the least so far, and assumes that the opponent's move this time will be one of those two. Assigning 2 to a win, 1 to a draw and 0 to a loss, it finds the move with the maximum score against these two predicted moves and throws that. # The Gambler's Brother - Python 2 ``` import sys import random MODE = 0 moves = 'RSLPV' def element_sums(a, b): return [a[i] + b[i] for i in xrange(len(a))] def move_scores(p): def calc(to_beat): return ['LDW'.find('DLLWW'[moves.find(m)-moves.find(to_beat)]) for m in moves] return dict(zip(moves, element_sums(calc(p[0]), calc(p[1])))) def move_chooser(my_history, opponent_history): predict = sorted(moves, key=opponent_history.count, reverse=MODE)[-2:] scores = move_scores(predict) return max(scores, key=lambda k:scores[k]) if __name__ == '__main__': if len(sys.argv) == 3: print move_chooser(*sys.argv[1:]) elif len(sys.argv) == 1: print random.choice(moves) ``` By switching the `MODE` variable to 0, this program will operate based on a related fallacy, also sometimes referred to as the gambler's fallacy. It states that if a random event has been happened more often in the past, it's more likely to happen in the future. For example, if you flip a coin 20 times and the first 15 are heads, this fallacy states that the remaining flips are more likely to be heads, since there's currently a streak. In mode 0, this program operates the same way, except that it assumes the opponent will throw one of the two moves it's thrown most often so far. So yes, these two programs are only one character apart. :) [Answer] # Dienstag (Python 2) My first entry [Pony](https://codegolf.stackexchange.com/a/35181/29703) seems to fare quite well with all its second guessing (tripple guessing, ...) and meta reasoning. But is that even necessary? So, here is Dienstag, Pony's little friend, with only one of the 55 strategies: Predict the opponent's next move and beat it. On the long run Dienstag wins or ties with every Bot in the top ten of the current leaderboard. Except for Pony that is. ``` import sys if len(sys.argv)<2 or len(sys.argv[1])<2: print 'L'; sys.exit() hist = [map('RPSVL'.index, p) for p in zip(sys.argv[1], sys.argv[2])] N = len(hist) cand = range(N-1) for l in xrange(1,N): cand = ([c for c in cand if c>=l and hist[c-l+1]==hist[-l]] or cand[-1:]) print 'RPSVL'[(hist[cand[-1]+1][1]+(1,3)[N%2==0])%5] ``` Run as: ``` python Dienstag.py ``` I admit that the code is a bit obfuscated. Should anyone care to know more about it, I might add explanations. *Edit:* Here is a short example walkthrough to explain the idea: * The program gets the history of it's own and the opponent's moves: `sys.arg[1] = 'LLVLLVL', sys.arg[2] = 'RPSPSSP'` * The history is combined into a list of pairs and the moves are translated to numbers (R=0, ...): `hist = [[4, 0], [4, 1], [3, 2], [4, 1], [4, 2], [3, 2], [4, 1]]` * The number of rounds played so far is determined: `N = 7` * The basic idea now is to look for the longest unbroken chain of exactly the last moves in the earlier history. The program keeps track of where such a chain ends in the list `cand` (for 'candidates'). In the beginning, without checking, every position in the history except for the last one is considered: `cand = [0, 1, 2, 3, 4, 5]` * Now the length of possible chains is increased step by step. For chain length `l = 1` it looks for previous occurrences of the last move pair `[4, 1]`. This can be found at history position `1` and `3`. Only these are kept in the `cand` list: `cand = [1, 3]` * Next, for `l = 2` it checks which of the possible candidates was preceded by the second to last move pair `[3, 2]`. This is only the case for position `3`: `cand = [3]` * For `l = 3` and more there are no previous chains of that length and `cand` would be empty. In this case the last element of `cand` is kept: `cand = [3]` * The bot now assumes that history will repeat. The last time the cain `[3, 2], [4, 1]` occurred, it was followed by `[4, 2]`. So, the opponent played `2` (scissors) which can be beaten by `(2+1)%5 = 3` (Spock) or `(2+3)%5 = 0` (rock). The bot answers, with the first or second alternative depending on whether `N` is odd or even just to introduce some variance. * Here move `3` is chosen which is then translated back: `print 'V'` *Note:* Dienstag has time complexity O(*N*2) for returning the next move after *N* rounds. Pony has time complexity O(*N*3). So in this aspect they are probably much worse then most other entries. [Answer] ## Bash Rocks Is cygwin too much to ask as a runtime? bashrocks.sh: ``` #!/bin/bash HAND=(R P S L V) RAND=`od -A n -t d -N 1 /dev/urandom | xargs` echo ${HAND[ $RAND % 5 ]} ``` and run it like so: ``` sh bashrocks.sh ``` [Answer] # Algorithm An algorithm for the sake of having one. Cuz' it always feels safer doing something, the more complicated the better. Haven't done some serious Math yet, so this algorithm may not be that effective. ``` import random, sys if __name__ == '__main__': # Graph in adjacency matrix here graph = {"S":"PL", "P":"VR", "R":"LS", "L":"VP", "V":"SR"} try: myHistory = sys.argv[1] opHistory = sys.argv[2] choices = "" # Insert some graph stuff here. Newer versions may include advanced Math. for v in graph: if opHistory[-1] == v: for u in graph: if u in graph[v]: choices += graph[u] print random.choice(choices + opHistory[-1]) except: print random.choice("RPSLV") ``` Python 2 program: `python algorithm.py` [Answer] ## FairBot, Ruby Let's start simple. ``` puts ['R','P','S','L','V'].sample ``` Run like ``` ruby fairbot.rb ``` [Answer] # ViolentBot This bot choices the most violent option based on the opponents previous choice: ``` import sys choice_dict = {"L" : "S", "P" : "S", "R" : "V", "S" : "V", "V" : "L"} total = len(sys.argv) if total==1: print("L") sys.exit() opponent = sys.argv[2] opponent_last = opponent[-1] print(choice_dict[opponent_last]) ``` Run as ``` python ViolentBot.py (me) (opp) ``` [Answer] # Nitpicker (Ruby) ``` BotName: Nitpicker Run: ruby nitpicker.rb [Mine] [Theirs] ``` Code Update: Now counts more stuff. Code ``` scores = [ 0 ] * 9 @moves = { "R" => 0, "P" => 1, "S" => 2, "L" => 3, "V" => 4 } @responses = [ "R", "P", "S", "L", "V" ] @counters = { "R" => [ "P", "V" ], "P" => [ "S", "L" ], "S" => [ "V", "R" ], "L" => [ "R", "S" ], "V" => [ "P", "L" ] } def try( theirs, mine ) return @counters[theirs].include? mine end def counter( move ) return @counters[move][rand(2)] end def follower( move ) return @responses[(@moves[move]+1)%5] end def echo( move ) return move end if ARGV[1] != nil for i in 2 .. ARGV[1].length - 1 points = i > ARGV[1].length - 10 ? 10 - ( ARGV[1].length - i ) : 1 if try( ARGV[1].split("")[i], counter( ARGV[0].split("")[i-1] )) scores[0] += points end if try( ARGV[1].split("")[i], follower( ARGV[0].split("")[i-1] )) scores[1] += points end if try( ARGV[1].split("")[i], echo( ARGV[0].split("")[i-1] )) scores[2] += points end if try( ARGV[1].split("")[i], counter( ARGV[1].split("")[i-1] )) scores[3] += points end if try( ARGV[1].split("")[i], follower( ARGV[1].split("")[i-1] )) scores[4] += points end if try( ARGV[1].split("")[i], echo( ARGV[1].split("")[i-1] )) scores[5] += points end if try( ARGV[1].split("")[i], counter( ARGV[1].split("")[i-2] )) scores[6] += points end if try( ARGV[1].split("")[i], follower( ARGV[1].split("")[i-2] )) scores[7] += points end if try( ARGV[1].split("")[i], echo( ARGV[1].split("")[i-2] )) scores[8] += points end end end bestId = -1; bestScore = 0; for j in 0 .. scores.length - 1 if scores[j] > bestScore bestScore = scores[j] bestId = j end end if bestId == 0 puts counter( ARGV[0].split("")[-1] ) elsif bestId == 1 puts follower( ARGV[0].split("")[-1] ) elsif bestId == 2 puts echo( ARGV[0].split("")[-1] ) elsif bestId == 3 puts counter( ARGV[1].split("")[-1] ) elsif bestId == 4 puts follower( ARGV[1].split("")[-1] ) elsif bestId == 5 puts echo( ARGV[1].split("")[-1] ) elsif bestId == 6 puts counter( ARGV[1].split("")[-2] ) elsif bestId == 7 puts follower( ARGV[1].split("")[-2] ) elsif bestId == 8 puts echo( ARGV[1].split("")[-2] ) else puts @responses[rand(5)] end ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/45281/edit). Closed 9 years ago. [Improve this question](/posts/45281/edit) Your task is to implement an [Enigma](http://en.wikipedia.org/wiki/Enigma_machine) encryption machine. Your program will accept the machine initialization information followed by a string of text to be encrypted. Initialization vector will be 1. Rotors used (Left to right). Will be three characters. Rotors 1-5 are valid. 2. Initial rotor settings (A-Z) Left to right. 3. Ring Setting, Left to Right. 4. Number of plugs (0-13) 5. N pairs for the plugboard. After the initialization vector, encrypt all text until a newline (0xA) character is encountered. Any text not in the A-Z range (including lower case for simplicity) should be output as is. You can compare output against [this simulator.](http://startpad.googlecode.com/hg/labs/js/enigma/enigma-sim.html) The initialization vecotr for the default state is `123MCKAAA0` If you click 'set from passkey' and enter 'codegolf', your equivalent initialization vector is `245FZPPAM10FTJQAOHGMYCKWRIXVPES` With this setting, `baaaaaaaaaaa...` should translate to `OXVXI NSRPS RGUXY XZVGB QUNJH TWTVD JNPSI TBWKJ XCVNR IUUVK LJWXV OMCGL VQOKD TVJVW HCFZF DBDQS FYECN SDTPC GESYN OWGNZ WWSYQ WJJBT GVMQM GUUVC XZNCV EPGLM MCNHY KLRJC LISZZ PTYIZ GIEUP OPZUI DPZZZ ULXFZ ONGRI WETGU CICMT KKQBW ZJMNL BZSLJ TLMGR RMZDZ BCNGM RYRGJ MKXRF JKQGG PYZFD UUZRE EIKPD OFUPE XODND DFXKY OHXHX ODWDC SXFPV`. This should fully test a double stepping scenario. You may assume the Initialization vector will be valid. Rotors will be in required range, no letter will be used in multiple plugs, etc. Only Reflector B will be used. All needed info (rotor wirings etc...) must be included in your program, not fetched from an outside source. Most details you need are on [wikipedia.](http://en.wikipedia.org/wiki/Enigma_rotor_details) Shortest code wins. ]
[Question] [ At the end of your interview, the Evil Interviewer tells you, "We make all of our applicants take a short coding test, to see if they really know what they are talking about. Don't worry; it's easy. And if you create a working program, I'll offer you the job immediately." He gestures for you to sit down at a nearby computer. "All you have to do is create a working Hello World program. But"--and he grins broadly--"there's a catch. Unfortunately the only compiler we have on this machine has a small bug. It randomly deletes one character from the source code file before compiling. Ok, see you in five minutes!" And he walks out of the room, whistling happily. Can you guarantee that you will get the job? ## The Task Write a program that will print `Hello, world!` to standard output even after a single character is removed from any position in the file. Or come as close to this as possible. ## The Rules **No Extraneous Output** - `Hello, world!` must be the only substantive thing printed to standard output. It is ok to include other characters if they are naturally produced by your language of choice--such as a trailing newline or even something like `[1] "Hello, world!"` (for example if you were using R), but *it must print the exact same thing every time.* It cannot print `Hello, world!Hello, world!` or `Hello world!" && x==1` some of the time, for example. Warnings, however, are allowed. **Testing** In order to test determine your score, you have to test each possible permutation of the program: test it with each character removed, and see if it produces the correct output. I have included a simple Perl program for this purpose below, which should work for many languages. If it doesn't work for you, please create a test program and include it in your answer. **Scoring** Your score is *the number of times your program fails*. In other words, the number of individual positions in your file where deleting a character prevents your program from working. Lowest score wins. In the event of a tie, the shortest code wins. **Trivial Solutions** such as `"Hello, world!"` in several languages (score of 15) are acceptable, but they aren't going to win. Happy programming, and may you get the job. But if you fail, you probably didn't want to work for that evil boss anyway. *Perl test script:* ``` use warnings; use strict; my $program = 'test.pl'; my $temp_file = 'corrupt.pl'; my $command = "perl -X $temp_file"; #Disabled warnings for cleaner output. my $expected_result = "Hello, world!"; open my $in,'<',$program or die $!; local $/; #Undef the line separator my $code = <$in>; #Read the entire file in. my $fails = 0; for my $omit_pos (0..length($code)-1) { my $corrupt = $code; $corrupt =~ s/^.{$omit_pos}\K.//s; #Delete a single character open my $out,'>',$temp_file or die $!; print {$out} $corrupt; #Write the corrupt program to a file close $out; my $result = `$command`; #Execute system command. if ($result ne $expected_result) { $fails++; print "Failure $fails:\nResult: ($result)\n$corrupt"; } } print "\n$fails failed out of " . length $code; ``` [Answer] ## Befunge, Score 0, 96 bytes I think I cracked it - no single character deletion will change the output. Deleting any character from line 1 changes nothing - it still goes down at the same place. Lines 2 and 3 are redundant. Normally line 2 is executed, but if you delete a character from it, the `<` is missed, and line 3 takes charge. Deleting newlines doesn't break it either (it did break my previous version). No test program, sorry. **EDIT**: simplified a lot. ``` vv @,,,,,,,,,,,,,"Hello, world!"<< @,,,,,,,,,,,,,"Hello, world!"<< ``` A short explanation of the flow: 1. Befunge starts executing from top-left, moving right. Spaces do nothing. 2. `v` turns the execution flow downward, so it goes down one line. 3. `<` turns the execution flow left, so it reads line 2 in reversed order. 4. `"Hello, world!"` pushes the string to the stack. It's pushed in reversed order, because we're executing right to left. 5. `,` pops a character and prints it. The last character pushed is printed first, which reverses the string once more. 6. `@` terminates the program. [Answer] # HQ9+ This will never fail to produce the intended result when a character is deleted so gets a score of zero. ``` HH ``` When do I start? [Answer] # Perl, Score 0 *(147 characters)* Here is my solution, which I managed to get from 4 down to 0: ``` eval +qq(;\$_="Hello, world!";;*a=print()if length==13or!m/./#)|| +eval +qq(;\$_="Hello, world!";;print()if*a!~/1/||!m/./#)##)|| print"Hello, world!" ``` It must appear all on one line to work; line breaks are for "readability" only. It benefits from Perl's pathologically permissive syntax. Some highlights: * Barewords that are not recognized are treated as strings. So when `eval` becomes `evl`, that is not an error if a string is permissible at that point. * Unary `+` operator, which does nothing other than disambiguate syntax in certain situations. This is useful with the above, because `function +argument` (where + is unary) becomes `string + argument` (addition) when a function name is mangled and becomes a string. * Many ways to declare strings: a double quoted string `qq( )` can become a single-quoted string `q()`; a string delimited by parentheses `qq(; ... )` can become a string delimited by a semicolon `qq; ... ;`. `#` inside strings can eliminate balancing issues by converting things to comments. The length of this can probably be reduced somewhat, though I doubt ugoren's solution can be beaten. [Answer] ## [Befunge-98](https://github.com/catseye/FBBI), score 0, 45 bytes ``` 20020xx""!!ddllrrooww ,,oolllleeHH""cckk,,@@ ``` [Try it online!](https://tio.run/nexus/befunge-98#@29kYGBkUFGhpKSomJKSk1NUlJ9fXq6goKOTn58DBKmpHh5KSsnJ2dk6Og4O//8DAA "Befunge-98 – TIO Nexus") Although an optimal solution has already been found (and there's no tie breaker), I thought I'd show that this can be simplified considerably with Befunge 98. ### Explanation The `20020xx` reliably sets the delta (the steps of the instruction pointer between ticks) to `(2,0)` so that starting at the first `x`, only every other command is executed. See [this answer](https://codegolf.stackexchange.com/a/103101/8478) for a detailed explanation of why this works. Afterwards, the code is merely: ``` "!dlrow ,olleH"ck,@ ``` We first push all the relevant character codes onto the stack with `"!dlrow ,olleH"`. Then `ck,` means print the top of the stack (`,`), 13 (`c` plus 1) times (`k`). `@` terminates the program. [Answer] ## J, 7 points Selecting every letter with odd position: ``` _2{.\'HHeellllo,, wwoorrlldd!!' Hello, world! ``` [Answer] # Unary, score 0, 74817134662624094502265949627214372599829 bytes The code is not included due to post length limitations, but it consists of 74817134662624094502265949627214372599829 zeros. If any of these zeros is removed, the resulting brainfuck program is [KSab's hello world program](https://codegolf.stackexchange.com/questions/55422/hello-world/163590#163590). Sadly, I didn't get the job because my machine had only 500 GB of hard disk space. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 0X1, score 0, 38 bytes *Works in both 011 (real projective plane) and 001 (Klein bottle)* ``` // @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19fn8tBSTElpyi/XEEnPycn1UPJBlPk////uo7/DQwMAQ "Klein – Try It Online") This reflects the ip over the top of the program. The geometry causes the ip to reenter the program on the opposite end of the program. This makes it a lot shorter than the traditional method which requires a full length line to reach the right side of the program. # 000, score 0, 38 bytes ``` <<@"!dlrow ,olleH"/ <@"!dlrow ,olleH"/ ``` [Try it online!](https://tio.run/##y85Jzcz7/9/GxkFJMSWnKL9cQSc/JyfVQ0mfC1Po////uo7/DQwMAA "Klein – Try It Online") # 1X1 or 20X, score 0, 39 bytes *Works in 101, 111, 200, and 201* ``` .. @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19Pj4vLQUkxJacov1xBJz8nJ9VDyQZT5P///7qO/w0NDAE "Klein – Try It Online") Due to the longstanding bug that spaces are trimmed off the front of Klein programs two `.`s are needed to make this work. If it were not for this bug the 37 byte program: ``` @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` world work in all of these geometries. The idea here is that we choose a geometry that naturally reaches the location we want and clear its way. Particularly we want geometries that connect the east edge to either the north or south edges with the proper twisting so that the ip leaving the east edge enters on the right side of the program. There are 4 of these. # 0X0, score 0, 40 bytes *Works in both 000 (torus) and 010 (Klein bottle)* ``` ||@"!dlrow ,olleH"./ ..@"!dlrow ,olleH"/ ``` [Try it online!](https://tio.run/##y85Jzcz7/7@mxkFJMSWnKL9cQSc/JyfVQ0lPn0tPD11Q/////7qO/w0MDQA "Klein – Try It Online") # 1X1, 20X, 210, or 101, score 0, 43 bytes *Works in 101, 111, 200, 201, 210, and 101* ``` .. @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19Pj4tLQcFBSTElpyi/XEEnPycn1UPJBpvY////dR3/GxoYAgA "Klein – Try It Online") A modified version of the above where we move the `@`s out of the path so that 210 and 101 work. Once again `..` is required due to a bug and could be removed for a 2 byte save if the bug were fixed. # XXX, score 0, 54 bytes *Works in every geometry* ``` . \\ @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19PARXExHA5KCmm5BTllyvo5OfkpHoo2WCK/P//X9fxv4GBIQA "Klein – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), score = ~~6~~ 4, ~~454~~ 426 bytes ``` xec=eec=exc=exe=exeexec=rint=pint=prnt=prit=prin=ppprint=hhh=hh=hhh=fr=""""pp(fr[1::2]) rrr________:__"ii______p____;nn____p______ptt__(________p(( __________(ff__________rfrr________[__r[[______1____[11____:______1::__:________:22 __________:66__________-2::________4__]22______]____)]]____)______ ))"""##""" xec=eec=exc=exe=exec pp=print fr=fr=fr=""""HHeelllloo,, wwoorrlldd!!"""##""" exec(hhh[1::2++2++2++2++2++2++2++00]) ``` [Try it online!](https://tio.run/##bVLNbtswDL7rKRj3EAl2gdgretCga5EH2M0wDNeWYwGaJDBK02LYs2f6yexiKyFSJEVS5Ce5D79Y8@022kkK3O/3t3c5Chn5PbKMLKMPlfHCJYFJqCSMcM6ls2VZRFqLmFEUgZyjM7Y1503HABH7O/G@L5TKuoviuzGrHjbv@57@DXaUQr8SnefNwHmr2QazbbNeJ0dd3@9KLs5XPShN86kmf37ejMeGr2FPfd81Tda7KFiXt@wCxsKQDw9BkC9QG4lzCSFPAh55RVSORyl1IGurCuB6tRZR62na7dZqJKbTgGQCryz/X4dDx27huULAY92RcdBaTiDgZdBnSSY5w5tENfdnjzSwMifGCQQ6afs6aMgJyTOczxI9GOu/8OZcEAKKY@jaVnC1qKddkYLWa3/gRRIy2ovxwTqQ2SIoUAZwMCdJtTQ0/jB2b@KfdqPL40c@S5TmjxktV12ZFFXWvKvgV5EgLfg632@25d27/jRHeBDp/FY6ZVNVQS7abcmp@1LUhOSYwlx@vkqEeVAaRFHlAHb7Aw "Python 3 – Try It Online") The undeletable char are parenthesis for the exec function and the brackets. ## How it works: * `hhh=hh=hhh=fr=...` initialize the main code and stor it in `hhh` * `xec=...=ppprint=...` initialize all possibe deletion of `exec` and `print` to avoid a future `NameError` * `xec=eec=exc=exe=exec` ensure that `exec` (with possible deletions) is well defined * `fr=fr=fr=""""HHeelllloo,, wwoorrlldd!!"""##"""` store in `fr` the string `Hello, world!` but doubled to keep the information even with a deletion * the last slice can be equal to either `[1::14]`, `[::14]`, `[1:14]` or `[1::12]`. Both of them slice the main code to have respectively `print(fr[1:26:2])`, `"r";pp(fr[1::2])` , `pp(fr[1::2])` or `p :pp( fr[1:: 6-4])` Thanks to @Jo King♦ for pointing me my errors, helping me to solve them and helped me to golf the result [Answer] # 8086 machine code (MS-DOS .COM), 71 bytes, score = 0 Slight variation on [previous](https://codegolf.stackexchange.com/a/191375/75886) [answers](https://codegolf.stackexchange.com/a/196299/75886) on the same theme. In binary form: ``` 00000000 : EB 28 28 E8 00 00 5A 83 C2 09 B4 09 CD 21 C3 48 : .((...Z......!.H 00000010 : 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 24 90 90 90 : ello, World!$... 00000020 : 90 90 90 90 90 90 90 90 90 90 EB D7 D7 E8 00 00 : ................ 00000030 : 5A 83 C2 09 B4 09 CD 21 C3 48 65 6C 6C 6F 2C 20 : Z......!.Hello, 00000040 : 57 6F 72 6C 64 21 24 : World!$ ``` In readable form (NASM syntax): ``` cpu 8086 org 0x100 %macro CODEPART 0 call near .nextline .nextline: pop dx add dx, 0x09 mov ah, 0x09 int 0x21 ret .msg db "Hello, World!$" %endmacro jump1: jmp jump2 db 0x28 part1: CODEPART filler: times 13 db 0x90 jump2: jmp part1 db 0xd7 part2: CODEPART ``` # Rundown The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a short jump, and so is only two bytes long, where the second byte is the displacement (i.e. distance to jump, with sign determining direction). We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen. The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive one byte off the mark. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden. For both jumps, we duplicate the displacement byte, making each jump part 3 bytes long. This ensures that irradiation in one of the two last bytes will still make the jump valid. Irradiation in the first byte will stop the jump from happening at all, since the last two bytes will form a completely different instruction. Take the first jump: ``` EB 28 28 jmp +0x28 / db 0x28 ``` If either of the `0x28` bytes are removed, it will still jump to the same place. If the `0xEB` byte is removed, we will instead end up with ``` 28 28 sub [bx + si], ch ``` which is a benign instruction on MS-DOS (other flavours might disagree), and then we fall through to code 1, which must be clean, since the damage was in jump 1. If the jump is taken, we land at the second jump: ``` EB D7 D7 jmp -0x29 / db 0xd7 ``` If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The duplicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. If we either land one byte off (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the two remaining bytes will also here be benign: ``` D7 D7 xlatb / xlatb ``` Whichever the case, if we end up executing those two instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe. ## Testing The following program takes the COM filename as an argument, and creates all variants of it, along with a file called `tester.bat`. When run in DOS, this BAT file will run each of the created binaries, redirecting the outputs into one text file per program. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fin, *fout, *fbat; int fsize; char *data; if (!(fin = fopen(argv[1], "rb"))) { fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]); exit(1); } if (!(fbat = fopen("tester.bat", "w"))) { fprintf(stderr, "Could not create BAT test file.\n"); exit(2); } fseek(fin, 0L, SEEK_END); fsize = ftell(fin); fseek(fin, 0L, SEEK_SET); if (!(data = malloc(fsize))) { fprintf(stderr, "Could not allocate memory.\n"); exit(3); } fread(data, 1, fsize, fin); fprintf(fbat, "@echo off\n"); for (int i = 0; i < fsize; i++) { char fname[512]; sprintf(fname, "%02d.com", i); fprintf(fbat, "%s > %02d.txt\n", fname, i); fout = fopen(fname, "wb"); fwrite(data, 1, i, fout); fwrite(data + i + 1, 1, fsize - i - 1, fout); fclose(fout); } free(data); fclose(fin); fclose(fbat); } ``` DOSBox, where I tested this, does not have the `fc` command, so another BAT file was created to run under Windows. It compares each text file with the first one to make sure they are all identical: ``` @echo off for %%x in (*.txt) do ( fc %%x 00.txt > nul if ERRORLEVEL 1 echo Failed: %%x ) ``` Ocular inspection of one of the text files is still needed. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), Score 0, 122 bytes ``` >>>>>>>>>>>>>%%/>>>>>>>>>>/ \\ >>>>>>>>>>>>>//>>>>>>>>>>>\\ // /@+-( "vUvdlrow ,olleH"?<< /// /@+-("vUvdlrow ,olleH"? <<< ``` [Try it online!](https://tio.run/##y8kvLvn/3w4ZqKrqIzj6XDExXCjS@kiydkBJfX0ufQdtXQ0FBaWy0LKUnKL8cgWd/JycVA8lexsboDRUHlNWwcbG5v///7qOAA "Lost – Try It Online") It never stops amazing me that [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") are possible in Lost. If you haven't seen Lost before it is a 2-D programming language in which instead of starting execution at a fixed location it chooses a random location and direction and starts there. This makes writing any lost program a bit of a radiation hardening challenge normally, since a program must work from every start location. But now we layer on [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") too and every program must work from every start location. With 122 bytes, four directions and a 28 by 6 bounding box, this means there are approximately 80,000 different programs that must be work. This program is built with a mix of standard lost methods and standard radiation hardening methods. To start here is the normal Hello World for lost: ``` v<<<<<<<<<<>>>>>>>>>>> >%?"Hello, worldvU"-+@ ``` It is comprised of a "collector" which gathers all the stray instruction pointers and points them to the beginning of the actual program. ``` v<<<<<<<<<<>>>>>>>>>>> > v ``` A more detailed explanation of how this program works can be found [here](https://codegolf.stackexchange.com/a/137699/56656). Now we want to modify this program to use the duplicate alignment method of radiation hardening. This method works by having two copies of the desired code and entering them from the end of the line. ``` >>>>>>>>>vv program < program < ``` This way when on of the programs is edited it becomes misaligned and the other one is executed ``` >>>>>>>>>vv progam < program < ``` To do this with our lost program is pretty simple: ``` >>>>>>>>>>>>>>>>>>>>>\\ @+-"Uvdlrow ,olleH"?%< @+-"Uvdlrow ,olleH"?%< ``` However there are some problems with this. The alignment of the `"`s is an issue because it causes infinite loops (in the example above there are basically two strings `">"` lain out vertically, so if you start on the quotes going in the right direction you just push the `>` character endlessly). So you need to make sure the quotes don't line up even when a character has been deleted. ``` >>>>>>>>>>>>>>>>>>>>>>>\\ @+- "Uvdlrow ,olleH"?%< @+-"Uvdlrow ,olleH"?% < ``` Also since `v` is needed to escape the inside of the string it's deletion is potentially a problem. So we need a backup. ``` >>>>>>>>>>>>>>>>>>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?%< @+-("vUvdlrow ,olleH"?% < ``` Now while alignment prevents most pointers from entering the wrong program, if we delete a non-critical character from a program, e.g. ``` >>>>>>>>>>>>>>>>>>>>>>>>>\\ @+-( "vUvdlrow ,olle"?%< @+-("vUvdlrow ,olleH"?% < ``` Then if execution starts on the `%` it doesn't need to care about the alignment at all and it will just execute the bad program. So we need to move `%` *before* the alignment ``` >>>>>>>>>>>>>>>>>>>>>>%%\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` Now another line of collector is needed to fill the gap we made by adding non-redirecting characters to our collector (`%`s). ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` *(Some small changes are glossed over here mainly just edge casey nonsense)* Now we have to worry about what happens when a newline is deleted. This would normally be ok because the alignment doubling strategy works for these, however for us it opens the door to a lot of potential infinite loops for example in the program: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\@+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` we now have a bunch of columns with no redirecting characters on them, so pointers starting there can just loop up or down endlessly. The trick we use here is to add (nearly) blank lines so that deleting a newline doesn't smash two big lines together. ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` So if we delete a newline: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` Nothing fundamentally changed about our program. However these lines can't be completely blank as it leaves the door open for infinite loops. In fact they need to have at least two (because one could be deleted) redirecting characters. ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< // @+-("vUvdlrow ,olleH"? < ``` Now if we delete the last newline our quotes align again: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< //@+-("vUvdlrow ,olleH"? < ``` Which is no good so we use *3* characters on the 3rd filler line: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< /// @+-("vUvdlrow ,olleH"? < ``` From here we arrive at the final program with just some minor fiddling. Iteratively fixing and finding mistakes. I've covered everything I think is interesting, but if you are interested in exactly why this or that just leave a commend and I will add it to the explanation. [Answer] # Befunge-93, Score 0 (63 bytes) I know this isn't a code-golf challenge, but I thought it would be interesting to see if the existing Befunge-93 solution could be improved upon in terms of size. I had originally developed this technique for use in the similar [Error 404](/q/103097/62101) challenge, but the need for a wrapping payload in that case made the 3 line solution more optimal. This isn't quite as good as Martin's Befunge-98 answer, but it's still a fairly significant reduction on the winning Befunge-93 solution. ``` <>> "!dlrow ,olleH">:#,_@ vv ^^@_,#!>#:<"Hello, world!"<<># ``` [Try it online!](http://befunge.tryitonline.net/#code=PD4-ICAiIWRscm93ICxvbGxlSCI-OiMsX0AgIHZ2CiAgXl5AXywjIT4jOjwiSGVsbG8sIHdvcmxkISI8PD4j&input=) **Explanation** There are two versions of the payload. For an unaltered program, the first `<` causes the program to execute right to left, wrapping around to the end of the line, until it reaches a `v` directing it down to the second line, and a `<` directing it left into the left-to-right version of the payload. An error on the second line causes the final `<` to be shifted left and replaced with a `>` directing the flow right instead. The `#` (bridge) command has nothing to jump over, so the code just continues until it wraps around and reaches a `^` at the start of the line, directing it up to the first line, and then a `>` directing it right into the right-to-left payload. Most errors on the first line just cause the final `v` commands to shift across by one, but that doesn't alter the main flow of the code. Deleting the first `<` is slightly different, though - in that case the execution path just flows directly into the left-to-right payload on the first line. The other special case is the removal of the line break. When the code wraps around to the end of the line, in this case it's now the end of the what used to be the second line. When it encounters the `#` command from the right, this jumps over the `>` and thus continues directly into the right-to-left payload. In case there's any doubt, I've also tested with the perl script and it confirmed that "0 failed out of 63". [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), score 0, 38 bytes ``` <<H"Hello, world!"/ H"Hello, world!" < ``` The language is released after the challenge. [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), score 2, 242 bytes ``` !!!!!!!!!!!!!! ^!!!!!!!!!!!!!ddddddddddddddllllllllllllllrrrrrrrrrrrrrrooooooooooooooWWWWWWWWWWWWWW ,,,,,,,,,,,,,,oooooooooooooolllllllllllllllllllllllllllleeeeeeeeeeeeeeHHHHHHHHHHHHHH(((@%%%%%%%%%%%%%%))üü&& ^dlroW ,olleH((@) ``` [Try it online!](https://tio.run/##fcyxDcAgEAPAVZ4iCBSGoMwGdEQI6F6AmI@OwT60bnKdJds1tzJySjx5iChAEWIBDCboIAACDuCOf1TwAGOMv4C1e@2ltVLvTbHw7IHc@a@n663IBw "!@#$%^&*()_+ – Try It Online") Well, I give up. I'm on a mobile phone, so I cannot put the null character there. If someone would be so kind to replace the !!\_+ in the TIO link, I would appreciate it. The two weaknesses are the `^` between the exclamation marks. This is not particularly clever, and most of the characters are just padding. Contains two Unicode characters; the challenge specifications said remove one character, not one byte. The HW is repeated 14 times to be immune to `%` removal or removal in the HW string. !@#$%^&\*()\_+ allow unmatched `(` but not unmatched `)` when parsing, so the left parenthesis is repeated one more time than the right parenthesis. What if the `@` was removed? We can know from the stack size if 13 characters went missing, so we use stack indexing to exit by error if the stack size is too short. Each character is doubled to make sure the test is performed. If the test passed, it means the `@` is the removed character, and none of the characters after the test was removed, so you can put a normal Hello, World program there. I made this one bored afternoon at school with a pencil, but I did not have time to debug and post this until now. Bugs might still be present. [Answer] # [><>](https://esolangs.org/wiki/Fish), score 0, 40 bytes ``` ||o<"Hello, world!"\ |o<"Hello, world!"\ ``` [Try it online!](https://tio.run/##S8sszvj/v6Ym30bJIzUnJ19HoTy/KCdFUSmGC4vY//8A "><> – Try It Online") This is a port of [my klein 000 answer](https://codegolf.stackexchange.com/a/215215/56656). It's a little more costly to output in ><>, but overall this is nicely competitive. This halts by triggering an error, as suggested by JoKing. For my original version that exits properly: # [><>](https://esolangs.org/wiki/Fish), score 0, 54 bytes ``` ||>!;!?o!l<"Hello, world!"\ |>!;!?o!l<"Hello, world!"\ ``` [Try it online!](https://tio.run/##S8sszvj/v6bGTtFa0T5fMcdGySM1JydfR6E8vygnRVEphgu31P//AA "><> – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes, score 0 ``` kH0kH ∴¡¡ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiOSggICAgICAgICAgICAgICAgICAgIyBsb29wIDkgdGltZVxuV18gICAgICAgICAgICAgICAgICAgIyBjbGVhciBzdGFja1xuYGNoYXIgJSByZW1vdmVkOmBuJSwgIyBwcmludChcImNoYXIgJXMgcmVtb3ZlZDpcIiVuKVxuYCIsImtIMGtIIOKItMKhwqEiLCJg4bii4bmqICAgICAgICAgICAjIHJlbW92ZSBsZWFkaW5nIGFuZCB0cmFpbGluZyBuZXdsaW5lXG5u4oC54ouOICAgICAgICAgICAjIHJlbW92ZSB0aGUgbnRoIGNoYXJcbmBjb2RlOiBg4oK0OiwgICAjIHByaW50KFwiY29kZTogXCIgKyBjb2RlKVxuYG91dHB1dDogYOKCtMSWLCAjIHByaW50KFwib3V0cHV0OiBcIiArIGV2YWwoY29kZSkpXG7CpCwgICAgICAgICAgICAjIHByaW50KCkiLCIiXQ==) ## Explanation : ``` # unaltered kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] kH # push 'Hello, World!' => [ Hello, World! , 0 , Hello, World! ] ∴ # max(a,b) => [ Hello, World! , Hello, World! ] ¡¡ # sentence case (twice) => [ Hello, World! , Hello, world! ] # implicit output # 1st char missing H # convert to hex => [ 0 ] 0 # Push 0 => [ 0 , 0 ] kH # push 'Hello, World!' => [ 0 , 0 , Hello, World! ] ∴¡¡ # max and sentence case => [ 0 , Hello, world! ] # 2nd char missing k0 # do nothing => [ ] kH # push 'Hello, World!' => [ Hello, World! ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 3nd char missing kH # push 'Hello, World!' => [ Hello, World! ] kH # push 'Hello, World!' => [ Hello, World! , Hello, World! ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 4th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] H # convert to hex => [ Hello, World! , 0 ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 5th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] k # do nothing => [ Hello, World! , 0 ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 6th same as unaltered # 7th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] kH # push 'Hello, World!' => [ Hello, World! , 0 , Hello, World! ] ¡¡ # sentence case (twice) => [ Hello, World! , 0 , Hello, world! ] # 8th or 9th char missing same as unaltered but sentence case only once ``` Fun fact, the char `0` can be replaced by any of `$123456789₀₄₆₇₈Ȯ` (and maybe some more) and the program is still a solution [Answer] # MSDOS .COM, 51 bytes ``` 00000000: eb18 18e8 0e00 4865 6c6c 6f2c 2057 6f72 ......Hello, Wor 00000010: 6c64 2124 b409 5acd 21c3 ebe7 e7b4 09ba ld!$..Z.!....... 00000020: 2401 cd21 c348 656c 6c6f 2c20 576f 726c $..!.Hello, Worl 00000030: 6421 24 d!$ org 100h jmp .L2 ; SBB [BX+SI],BL if 1B removed db .L2-$ .L0:call .L1 db "Hello, World!$" .L1:mov ah, 9 pop dx int 0x21 ret db 0x11A-$ dup ? ; Actually none .L2:jmp .L0 ; OUT E7, AX if 1B removed db .L0-$ mov ah, 9 mov dx, .L3-1 ; If it goes this way int 0x21 ; then 1 byte missing ret .L3:db "Hello, World!$" ``` gastropner suggests me do this Collection of all programs with at most 1 byte removed in base64, confirmed ``` /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4NX/AgVdACCLvBunjDQGwDuQeO2LBXimvB64zX4rztWL/i5Av150lJoeOSHW05X92oDP65IyBlb67MdiB3tAoqaEfRm3gzRuAXuwZhHgJsxZs0QpbeW6y0O+IUD3a6M3dV4n+YbVbdSu8MWbR9qg76ck36pl5sy9kzvUv9hcAczs00fsjGJS10OdrU6sDxTIOpMk13Z+WxChUK04r19vxvShWbKDb2pZawGxFVJ2Sks0JvZNOJExJQx8l0fa6sSqQtOJR4oWVmOf/lePTc/ZDE3pz2nVPYgxQeLN31fGGeoso1JwWvr3sDyL6v49m2ZR9y0fVwc/nactXKMTJLzKmxSuwq6azF2f6ddf+0OL5fgVgccV5M1P9lQ6WV+sp80RWo1ceO8OJWmvIGM3ZTcl7ZcYqWUxQyvqAp0aL9ZDvXJhnybKXDSKOhzjtLcKM/07aCsVmBe5hZwllSnjiAOwKeH/8KyP/Uxfwl0xO5zyWshxWa0Znji7HAQH9ais1UHVHAP9P9EQF+g0rU5WehexGtrRg74lGF9/hUSepXTZZAZLpMURXJC9zlhkAj7xKsL3Lmm/yNZyETgDiZMB2kD/k3js5jDnmAZjU15KkYHpuNVsjsFcP6ERVipU4b3WRGCjsMgzbTcN1naVFUNOWXLGcvdY2Y5o2Wf2+TMTD275J51Db4aNUX8rIRd3NUwAAAAASNVP9/NyC/kAAaEEgKwDAKrxg/KxxGf7AgAAAAAEWVo= ``` [Answer] # [R](https://www.r-project.org/) [REPL](https://codegolf.meta.stackexchange.com/q/7842/95126)\*, ~~204~~ ~~137~~ ~~130~~ 99 bytes, score 0 \**(or any other R environment in which errors do not halt execution of subsequent commands: entering the program into the R interactive console works fine; alternatively (and as simulated in the TIO link) we can use the command-line option `-e 'options(error=function(){})'` (which would then define the language as "`R -e 'options(error=function(){})'`").* ``` a="Hello, world!"##" b="Hello, world!"##" T=cat(`if`(exists("a")&&(nchar(a)==13),a,b)); if(T)cat(a) ``` [Try it online!](https://tio.run/##bctBCsIwEEDRfU@hUygzkI24lNl7gB6g05hgIGRkElGQnj2le5f/wbeur5a0VAxmahzfxR@N9NuoC8M95Kzu9FHLjzOMIwzrP5zZS8MlxQXDN9VWEQRomrD4pxgKMV@u5MStRLchRZzpGIR63wE "R – Try It Online") **Explanation:** Lines 1 & 2: At least one of `a` or `b` should contain the text `"Hello, world!"` even if any character is deleted: * any deletion inside one quoted string shouldn't affect the other; * deletion of any of `a="` will simply error without assigning `a` (or the same for `b`); * deletion of the second `"` will assign ```"Hello, world!##"```` to that string without affecting the other; * deletion of any of `##"` has no effect; * deletion of the first newline will convert the following line into a comment and prevent assignment of `b`, without affecting `a`; * deletion of the second newline will convert the following line into a comment, without affecting either `a` or `b` (see line 3 below). Line 3: Aims to output one of `a` or `b` that exists and is the correct, 13-character `"Hello, world!"` string, or to error. If it succeeds without erroring, the variable `T` is re-assigned to `NULL` (instead of its default value of `TRUE`). * deletion of any of `T=`, `cat()`, ``if`(,,b)`, `exists("a")`, or `nchar(a)==` will error and fail to re-assign `T`. * deletion of any of `13` will select `b` instead of `a` to output; however, since this was the single deletion made, `b` is intact so this is Ok. * deletion of either `;` or the third newline has no effect; * if the entire line is commented-out (by deletion of the second newline), it will not re-assign `T`. Line 4: If `T` is not NULL, then either an error has occurred (so the deletion was on line 3), or the second newline was deleted (so line 3 was commented-out). In either case `a` should be the correct `"Hello, world!"` string, and nothing has yet been output, so we can safely output `a`. Any deletion to this line should cause an error so that it doesn't output anything to stdout. * deletion of any of `if(T)` will error; * if `T` is `NULL` (so no error has yet occurred, and line 3 ran Ok), `if(T)` will error and this line will not output anything. * if `T` is still `TRUE`, then the single deletion already happened on another line, so we shouldn't need to worry about further deletions on this line. ]
[Question] [ ## Introduction You are the computer science teacher in a large high school and have been tasked to create a system to generate the student timetables. You must, given a JSON dictionary of student names and the subjects they are taking, you must generate a timetable for each of the students. ## Specifications Each student takes seven subjects (English Literature, English Language and Maths are compulsory but don't count towards the seven subjects): ``` Subject name - Abbreviation Art - Ar Biology - Bi Business Studies - Bu Chemistry - Ch Computer Science - CS French - Fr Geography - Gg History - Hi IT - IT Mandarin - Cn Music - Mu PE - PE Physics - Ph Spanish - Sp Compulsory: English Language - La English Literature - Li Maths - Ma Other: Tutor - Tu Free - Ac ``` All abbreviations must be in the same case as above. Each day has ten periods of lessons. A lesson can either span a single period or a double period. There must be three lessons of each subject with each having one double lesson (double period length) and two single lessons. The only exception to this rule is English Language which only occurs once a week and is a double. There must be only one lesson of the same subject a day. A school day is Monday to Friday. Between periods 3 and 4 and between periods 5 and 6, there is a break. Lessons must not be placed over a break. From period six inclusive on a Wednesday to the end of the day, there are free periods. Period 1 on a Tuesday is Tutor period. Period 10 on a Friday is also Tutor. Period 10 on a Thursday is a free period. Lessons must not be split into multiple groups meaning that people studying the same subject must be together in those subjects. Students may have any number of frees. You must use the subject's abbbreviation in the timetable. ## Data input The JSON data must either be read from a local file or placed as a string variable in your code. The file will be a list of students with their names and a list of subjects. For example: ``` [ {"name":"Sarah","subjects":["physics","it","biology","history","art","business studies","french"]}, {"name":"Jim","subjects":["history","business studies","biology","computer science","geography","chemistry"]}, {"name":"Mary","subjects":["it","computer science","biology","physics","chemistry","art"]}, {"name":"Chris","subjects":["biology","chemistry","physics","french","computer science","geography"]} ] ``` Your program should then generate a timetable for each of the students, fitting all of the subjects in. If there are multiple solutions, choose the first. ***Note:*** The JSON file above has not been tested to see if it has a valid answer, it was just created to describe the formatting. ## Output The output must be a JSON file or CSV with the format detailed in your answer. You can either make a file for each of the students or have the timetables for all students in the same file. ## Winning The winning code is the shortest that successfully creates working timetables. [Answer] **NodeJS** **Edit** The algorthim is much faster now! There is definitely no solution for the given example! I tried some algorithms to generate a time table and I am pretty sure that your example has no solution. So I changed the example to students.json: ``` [ {"name":"Sarah","subjects":["physics","it","biology","history","art","business studies","french"]}, {"name":"Jim","subjects":["history","business studies","biology","computer science","geography","chemistry"]}, {"name":"Mary","subjects":["it","computer science","biology","physics","chemistry","art"]}, {"name":"Chris","subjects":["biology","chemistry","physics","french","computer science","geography"]} ] ``` (I only deleted the `pe`) which generates this timeTable.json ``` { "mon": [["Bi"],["Bi"],["Ar","Gg"],["La"],["La"],["Ch"],["Ch"],["CS"],["CS"],["Ph"]], "tue": [["Tu"],["Bi"],["Ar","Gg"],["Ma"],["Ma"],["Ch"],["CS"],["Ph"],["Ph"],["Bu"]], "wed": [["Bi"],["Ar","Gg"],["Ar","Gg"],["Li"],["Li"],["Fr"],["Fr"],["IT"],["IT"],["Hi"]], "thu": [["Li"],["Ma"],["Ch"],["CS"],["Bu"],["Ph"],["Fr"],["IT"],["Hi"],["Ac"]], "fri": [["Li"],["Ma"],["Fr"],["Bu"],["Bu"],["IT"],["Hi"],["Hi"],[],["Tu"]] } ``` And yes my programm is very long but I think code which is shortened afterwards makes it really hard to read and nowadays it isn't important to save bytes but time! If you have any suggestions or you found a bug => comment! You can start the file (timeTable.js) with `node timeTable.js students.js` ``` var fs = require('fs'); console.log('Timetable'); var json = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); var backTracks = 0; var lessons = ["art","biology","business studies","chemistry","computer science","french","geography","history","it","mandarin","music","pe","physics","spanish"]; var abbr = ["Ar","Bi","Bu","Ch","CS","Fr","Gg","Hi","IT","Cn","Mu","PE","Ph","Sp"]; var single = [2,2,2,2,2,2,2,2,2,2,2,2,2,2]; var double = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]; var days = ["mon","tue","wed","thu","fri"]; var nrOfStudents = json.length; var q = 0; // convert json into correct position for (var i = 0; i < json.length; i++) { var subjects = json[i].subjects; for (var s = 0; s < subjects.length; s++) { var pos = lessons.indexOf(subjects[s].toLowerCase()); if (pos >= 0) { subjects[s] = pos; } } } // Special lessons var timeTable = {"mon":[],"tue":[],"wed":[],"thu":[],"fri":[]}; timeTable.tue[0] = ["Tu"]; timeTable.fri[9] = ["Tu"]; timeTable.thu[9] = ["Ac"]; // one english double (Monday 4-5) timeTable.mon[3] = ["La"]; timeTable.mon[4] = ["La"]; // one double two single for math and literature (Tue 4-5,Wed 4-5,Thu 1,2,Fri 1,2) timeTable.tue[3] = ["Ma"]; timeTable.tue[4] = ["Ma"]; timeTable.wed[3] = ["Li"]; timeTable.wed[4] = ["Li"]; timeTable.thu[0] = ["Li"]; timeTable.thu[1] = ["Ma"]; timeTable.fri[0] = ["Li"]; timeTable.fri[1] = ["Ma"]; var timeTableBackup = {0:[],1:[],2:[],3:[],4:[]}; for (var i = 0; i < 5; i++) { var day = timeTable[days[i]]; for (var j = 0; j < 10; j++) { if (!(j in day) || !Array.isArray(day[j])) { day[j] = []; } } } // sort subjects var sortedSubs = []; // 14 subjects for (var i = 0; i < 14; i++) { sortedSubs[i] = {t:0,students:[],n:i}; } for (var i = 0; i < json.length; i++) { var subjects = json[i].subjects; var student = json[i].name; for (var s = 0; s < subjects.length; s++) { sortedSubs[subjects[s]].t ++; sortedSubs[subjects[s]].n = subjects[s]; sortedSubs[subjects[s]].students.push(student); } } console.log(sortedSubs); sortedSubs = sortByKey(sortedSubs,"t"); var k = sortedSubs.length-1; // remove all subs that weren't choosen by anyone while(sortedSubs[k].t == 0) { var sub = sortedSubs.pop(); single[sub.n] = 0; double[sub.n] = 0; k--; } var goBack = false; var start = false; var d = 0; while (d < 5) { // 10 lessons per day var l = 0; while(l < 10) { var day = timeTable[days[d]]; // if there is no subject if (day[l].length == 0) { var next = false; var s = start === false ? 0 : start; var firstChoice = false; while (!next && s < sortedSubs.length) { if (possibleToAdd(day,l,s)) { // different lessons on one day and possiblity to add lesson goBack = false; next = true; if (!firstChoice) firstChoice = s; // get the number of students that don't have this lesson var except = nrOfStudents - sortedSubs[s].t; if (except > 0) { // get the first lesson which none of the students have var breaked = false; var tempL; for (var ss = s+1; ss < sortedSubs.length; ss++) { if (sortedSubs[ss].t <= except && possibleToAdd(day,l,ss)) { var intersection = arrIntersect(sortedSubs[s].students,sortedSubs[ss].students); // no student has both classes if (intersection.length == 0) { if (!breaked) { // fill the current lesson (s) only once tempL = addLesson(day,l,s); } tempL = addLesson(day,l,ss); breaked = true; } } } if (breaked) { l = tempL; } else { // it wasn't possible to have two classes at this time next = false; var found = false; // maybe there are other lessons which can be added => found = true for (var z = s+1; z < sortedSubs.length; z++) { if (possibleToAdd(day,l,z)) { found = true; break; } } // otherwise fill this lesson with the first choice if (!found) { l = addLesson(day,l,firstChoice); } } } else { // everyone has this lesson :) // on day lesson no. l: subject no. s l = addLesson(day,l,s); } } else { if (start) goBack = true; } s++; } start = false; } // Friday last lesson if ((d == 4 && l == 9) || goBack) { // how many lessons are missing? var sum = double.reduce(function(pv, cv) { return pv + cv; }, 0)*2 + single.reduce(function(pv, cv) { return pv + cv; }, 0); if (sum > 0) { remove = removeLesson(d,l); if (remove) { backTracks++; if (backTracks % 50000 == 0) { console.log('backTracks: '+backTracks+'...'); } d = remove.back.day; l = remove.back.lesson; start = remove.start; } else { console.log('I could not find a solution for this problem :( '); console.log('backtracks: '+backTracks); process.exit(); l = 10; d = 5; } } else { l = 10; d = 5; } } else { l++; } } d++; } function removeLesson(d,l) { var day = timeTable[days[d]]; var back = true; // what is the latest subject var latestSub = sortedSubs[sortedSubs.length-1].n; // backtrack while(back) { // if there is no lesson before => back to the last lesson the day before if (l == -1) { if (d == 0) { return false; // not possible at all } d--; day = timeTable[days[d]]; l = day.length-1; } // if there is a non default lesson if (day[l].length > 0 && parseInt(day[l][0]) == day[l][0]) { // if the latestSub isn't part of this lesson we don't need to backtrack more if (day[l].indexOf(latestSub) < 0) { back = false; } var intersection = []; // if we are not in the first lesson => get double lessons if (l > 0) { intersection = arrIntersect(day[l],day[l-1]); } // if there are double lessons if (intersection.length > 0) { for (var i = 0; i < day[l].length; i++) { // check if current lesson is a double lesson if (intersection.indexOf(day[l][i]) >= 0) { double[day[l][i]]++; } else { single[day[l][i]]++; } } // remove all single lessons the lesson before for (var i = 0; i < day[l-1].length; i++) { if (intersection.indexOf(day[l-1][i]) < 0) { single[day[l-1][i]]++; } } day[l] = []; l--; } else { for (var i = 0; i < day[l].length; i++) { single[day[l][i]]++; } } // delete the day if the current lesson was the least possible solution if (back) { day[l] = []; } } else { l--; } } var start = false; // get start subject for this lesson d,l for (var s = 0; s < sortedSubs.length-1; s++) { if (day[l].indexOf(sortedSubs[s].n) >= 0) { start = ++s; day[l] = []; break; } } if (!start) { console.log('there is a bug'); process.exit(); } return {back:{day:d,lesson:l},start:start}; } function addLesson(day,l,s) { // is a double lesson possible? if (double[sortedSubs[s].n] > 0 && l != 2 && l != 4 && l+1 < 10 && (day[l+1].length == 0 || parseInt(day[l+1][0]) == day[l+1][0])) { double[sortedSubs[s].n]--; for (var i = l; i <= l+1; i++) { if (Array.isArray(day[i])) { day[i].push(sortedSubs[s].n); } else { day[i] = [sortedSubs[s].n]; } } l++; } else if (single[sortedSubs[s].n] > 0) { // put it into a single lesson single[sortedSubs[s].n]--; if (Array.isArray(day[l])) { day[l].push(sortedSubs[s].n); } else { day[l] = [sortedSubs[s].n]; } } else { console.log('ERROR'); process.exit(); } return l; } function possibleToAdd(day,l,s) { // it is not allowed to have the same lesson twice on a day var notSet = true; for (var i = 0; i < l; i++) { if (day[i].indexOf(sortedSubs[s].n) >= 0) { notSet = false; break; } } if (!notSet) return false; // no double lesson 3+4 and (starting with 1) if (double[sortedSubs[s].n] > 0 && l != 2 && l != 4 && l+1 < 10 && (day[l+1].length == 0 || parseInt(day[l+1][0]) == day[l+1][0])) { return true; } else if (single[sortedSubs[s].n] > 0) { return true; } else { return false; } } function arrIntersect(array1,array2) { return array1.filter(function(n) { return array2.indexOf(n) != -1 }); } function sortByKey(array, key) { return array.sort(function(a, b) { var x = a[key]; var y = b[key]; return ((x < y) ? 1 : -1); }); } // convert lesson numbers into abbr for (var d = 0; d < 5; d++) { var day = timeTable[days[d]]; // 10 lessons per day for (var l = 0; l < 10; l++) { for (var ll = 0; ll < day[l].length; ll++) { if (parseInt(day[l][ll]) == day[l][ll]) { day[l][ll] = abbr[day[l][ll]]; } } } } console.log(timeTable); console.log('Backtracks: '+backTracks); fs.writeFile("timeTable.json", JSON.stringify(timeTable), function(err) { if(err) { console.log(err); } else { console.log("The file was saved (timeTable.json)!"); } }); ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/32221/edit). Closed 7 years ago. [Improve this question](/posts/32221/edit) Represent poker cards as numbers from 0 to 51. 0 to 12 - all hearts from 2 to Ace, 13 to 25 all diamonds and so on. Your goal is to write a function for each [poker hand type](http://en.wikipedia.org/wiki/List_of_poker_hands) which generates a random 7-card hand (as in Texas Holdem on the river), in which the best 5-card combination is of the target type. The output is a sequence of 7 numbers. So, your function accepts a number from 0 to 8, where 0 is a High Card poker hand type and 8 is a Straight Flush, and returns a sequence of 7 numbers which represent the hand. Additional requirements: 1. The hand should be sampled uniformly from all the possible hands of the given type. For example, it's not ok to generate straight flushes which always end with Ace. 2. You can't use or generate any look up tables bigger then 1000 values. For example, it's not ok to generate all flushes and than select a random one from them. 3. Generating completely random sets of 7 cards and checking for the target type until it is found is not allowed. Basically your function should have defined upper time limit. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/26040/edit) As I'm sure many of you know, synonyms can range from very similar to not-so-similar-but-I-can-see-how-it's-similar. It's common for dictionaries to use "See also" to denote occurrences of words that have especially good synonyms. Thesauruses (Thesauri?), on the other hand, list every word that is remotely close in definition. It got me thinking: **Is it possible to construct one single "See also" loop that encompasses an entire dictionary?** Of course, you'd have to stretch definitions at some point. Switches between parts of speech would also have to happen if you intend to make your loop large. The only rules are that each must reference EXACTLY the word after it only with respect to spelling, and the final word must reference the first word. For example: * **Huge**: See also **Giant** * **Giant**: See also **Titan** * **Titan**: See also **Behemoth** * **Behemoth**: See also **Beast** * **Beast**: See also **Creature** * **Creature**: See also **Pig** * **Pig**: See also **Gorge** * **Gorge**: See also **Void** * **Void**: See also **Free** * **Free**: See also **Unrestricted** * **Unrestricted**: See also **Huge** That was just thrown together, but I think it gets the idea across. You can go for "words" that are really multiple words, so long as it is the type of thing you'd find in a dictionary. Some helpful resources (let me know of any others): * <http://thesaurus.com/> * <http://wordnetweb.princeton.edu/> * <http://icon.shef.ac.uk/Moby/> And that's it! As for going above and beyond, it would be cool to see some kind of visualisation of your loop, possibly making each part of speech a different color or something. Use your imagination! It will be interesting to see what kind of stuff you might come up with. **Winning criteria**: The program which produces a loop that contains the largest number of unique words will be deemed the winner. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/23369/edit). Closed 9 years ago. [Improve this question](/posts/23369/edit) Write an object-oriented program that, when ran, outputs one complete example from each reserved-word-vise unique signature combination available to that language. Reserved words for primitive types are excluded. Each example should start from a new line. This implies that for all signatures any changes in parameters, return types or in their counts do not contribute towards the goal. The resulting output for Java could be something like this: ``` private int a; protected int a; public int a; private static int a; protected static int a; public static int a; private static final int a; protected static final int a; ... private void a(){}; protected void a(){}; ... private abstract void a(); protected abstract void a(); ... ``` ]
[Question] [ This is a very stripped down version of [A BlackJack KOTH contest](https://codegolf.stackexchange.com/questions/2698/a-blackjack-koth-contest)... This is the goal: Upon the execution: There are two inputs, "H" to hit (have the code deal a card), "S" to stand (Stop getting cards, and let dealer try to win). Coding Rules: 1. There is no betting or splitting of hands, for simplicity of the challenge. 2. Suits are HDCS; standing for Hearts, Diamonds, Clubs and Spades respectively. 3. Trumps must be formatted as A23456789TJQK, where T is the 10; therefore TH is the 10 of Hearts, etc. 4. A is worth 1 or 11. Face cards are worth 10 points. A perfect game is 21 points. 5. If you go over 21 points, the output along with the cards must show "BUST". 6. If the dealer goes over 21 points and you're standing, output with cards must show "WIN" 7. If the dealer beats you even though you're standing, output with cards must show "LOSE" 8. If the dealer matches your score on standing, output with cards must show "PUSH" 9. Dealer must stand on 17 through to 21. 10. If you Stand, it calculates your score and displays it (see below), and then goes into dealer play mode. If the dealer stands or busts, it calculates its score and displays it. 11. Standard 52 cards in a deck, no duplicates can be generated. 12. Output must resemble the following: ``` H Your hand: 3H H Your hand: 3H 8S H Your hand: 3H 8S 9D S Standing... Your hand: 3H 8S 9D = 20 points My hand: 2C 5H 8H 9S = 24 points WIN ``` 13. Shortest code wins [Answer] ## [Golf-Basic 84](http://timtechsoftware.com/?page_id=1261 "Golf-Basic 84"), 852 characters (ALL rules observed) ``` :"YOUR HAND:"_Str1:-1_X:0_O:0_A:0_P:2_H:3_2l`Ii`I@I=2o`H#o`Sl`H:Str1+" "_Str1:round(rand*13,0)_R@R=0:Str1+"A"_Str1@R=1:Str1+"2"_Str1@R=2:Str1+"3"_Str1@R=3:Str1+"4"_Str1@R4:Str1+"5"_Str1@R=5:Str1+"6"_Str1@R=6:Str1+"7"_Str1@R=7:Str1+"8"_Str1@R=8:Str1+"9"_Str1@R=9:Str1+"10"_Str1@R=10:Str1+"J"_Str1@R=11:Str1+"Q"_Str1@R=12:Str1+"K"_Str1@R=1:A+10_A@R<9:P+R+1_P#P+10_P:round(rand*4,0)_R@R=0:Str1+"H"_Str1@R=1:Str1+"D"_Str1@R=2:Str1+"C"_Str1@R=3:Str1+"S"_Str1d`Str1@P>20:o`So`Il`St`STANDING... "+Str1+", POINTS:"d`P@P=21 or P+A=21:"WIN"_Str2@P>21:"BUST"_Str2:round(rand*8,0)_R:"MY HAND: "_Str3l`X:X+1_X:round(rand*8,0)@R=0:Str3+"9H"_Str3@R=1:Str3+"9D"_Str3@R=2:Str3+"9C"_Str3@R=3:Str3+"9S"_Str3@R4:Str3+"JH"_Str3@R=5:Str3+"QD"_Str3@R=6:Str3+"KC"_Str3@R=7:Str3+"KS"_Str3@R<4:O+9_O#:O+10_O@Xo`E#o`Xl'Et`Str3+"= POINTS:"d`O@P=O:"PUSH"_Str2@P<O:"LOSE"_Str2d`Str2 ``` Coded all by myself! **Explanation** * Initialize variables; put `0` in `P` and `"YOUR HAND:"` in `Str1` * Take input, either `H` or `S` (no quotes needed) * Based on input, goto `Lbl H` or `Lbl S` * If input is `H`, generate a random card, add a space, a number/letter, and a suit to `Str1` * Based on the card generated, add the value of the card to `P` and additionally add 1 to `A` (ace count) * Get more input * If input is `S`, calculate the points and the dealer's points * Put `WIN` or `BUST` in `Str2` depending on the points generated * Display the dealer's hand * Calculate your points and the dealer's points, conditionally put `LOSE` or `PUSH` in `Str2` * Display `WIN`, `PUSH`, `LOSE`, or `BUST` **Sample output** ``` ?H YOUR HAND: 9C ?H YOUR HAND: 9C 7S ?H YOUR HAND: 9C 7S 4S ?S STANDING... YOUR HAND: 3H 8S 9D, POINTS: 20 MY HAND: 9H KS = POINTS: 19 WIN ``` [Answer] ## Javascript 838 The very first version, not optimized ! All rules are not fully observed, :-o ``` !function(){var f=require("readline").createInterface(process.stdin,process.stdout),g=[],h=function(){for(var b;!b||-1<g.indexOf(b);)b="A23456789TJQK".charAt(13*Math.random()|0)+"HDCS".charAt(4*Math.random()|0);g.push(b);return b},k=function(b){var a=0,d=0;for(z=b.length;z--;){var c=b[z].charAt(0);/[TJQK]/.test(c)?a+=10:/[2-9]/.test(c)?a+=+c:"A"==c&&(d++,a++)}for(;d--;)21>=a+10&&(a+=10);return a};(function(){var b=[],a=[],d=0,c=0;f.prompt();f.on("line",function(e){e=e.charAt(0);"H"==e&&(b.push(h()), c=k(b),console.log("Your hand: "+b+" = "+c+" points"),21<c&&(console.log("LOSE"),process.exit(0)));if("S"==e){for(;17>(d=k(a));)a.push(h());console.log("My hand: "+a+" = "+d+" points");21<d||d<c?console.log("WIN"):d>c?console.log("LOSE"):console.log("DRAW");process.exit(0)}f.prompt()}).on("close",function(){process.exit(0)})})()}(); ``` Execute it with nodeJS ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 10 years ago. [Improve this question](/posts/12714/edit) [this](http://www.cise.ufl.edu/~manuel/obfuscate/westley.hint) code looks like a story but does nothing useful. My challenge for you guys is to write piece of code which sounds like another story but it must generate output - another story. So the point of challenge to make valid code which can be read like a logical story/poem/tale, also it must generate output - another story/poem/tale. It is not real code golf, so you can produce as much code as you need, also there is no need generate very long output with small piece of code, everything is about ingenuity. However there is only one limit in code, output needs to be longer then `Why did the chicken cross the road?` My own opinion is not objective so the winner will be the top answer by votes. Will not accept an answer until 1st of November. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/35727/edit). Closed 9 years ago. [Improve this question](/posts/35727/edit) Calculate the [Riemann zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function) to the maximum primitive precision in your language (for C-family, that would be `double` or `long double`, `var` in JS, etc.) No need for `BigDecimal` or the like unless you need it to use a `double`-equivalent precision. 1. Efficiency (be sane) doesn't matter. 2. If it's not in a common language, I can't test it, but I hope somebody does. 3. **No libraries or built-in math functions.** 4. Recursion is cool! See my JS entry for a sample program. [Answer] # JavaScript (Chrome): 78 ``` function zeta(r){for(var t=0,a=1,n=1;t!=a;a=t,t+=1/Math.pow(n++,r));return t} ``` ]
[Question] [ # Write some code... Write a program that takes **no input** and outputs an integer `n` which is a multiple of `3`. So `n=3k`, where `k` is a positive integer. **Double** the **last character** of your code. Your code should then output `k`. # Examples Here is my program `hui#2(21+4)//lm`, which outputs `81`. Because of that, `hui#2(21+4)//lmm` should output `27`. or If `p8$w2*8` outputs `9`, `p8$w2*88` should output `3`. # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins! [Answer] # Mathematica, 2 bytes ``` 4! ``` 4! returns 24 4!! returns 8 [Answer] ## Many languages, 4 bytes ``` 16-1 ``` Outputs 15. ``` 16-11 ``` Outputs 5. This is a CW answer [for many languages it works for](https://codegolf.meta.stackexchange.com/a/11218/20260). Edit to add to the list: * APL * bc * Dyvil * Haskell * I * J * Japt * Javascript REPL * Java REPL * Julia REPL * Mathematica * Python REPL * R REPL * Ruby REPL * Scala REPL * Swift REPL * TI-83/84 Basic [Answer] # [Lost](https://github.com/Wheatwizard/Lost), ~~52~~, 18 bytes ``` \(@>>> \>>%? \(13$ ``` [Try it online!](https://tio.run/##y8kvLvn/P0bDwc7OjivGzk7VnitGw9BY5f///7qBAA "Lost – Try It Online") ``` \(@>>> \>>%? \(13$$ ``` [Try it online!](https://tio.run/##y8kvLvn/P0bDwc7OjivGzk7VnitGw9BYReX///@6gQA "Lost – Try It Online") ## Explanation Lost is a language in which the start location and direction of the pointer are entirely random. Thus making a deterministic program can be tough. The code we want to execute is either `13$(@` or `13$$(@`. * `31` pushes 3 and 1 to the stack * `$` will swap them * `$` will swap them back if present * `(` will pop the top element * `@` will halt and output We want to insert the `$` at the end so we have to split this ``` \(@ v \31$ ``` The rest of this is a careful orchestration to make sure that every possible pointer executes this code and only this code. [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 19 bytes ``` a="3";aa="1";hint a ``` **Outputs:** [![](https://i.stack.imgur.com/7Rtfk.jpg)](https://i.stack.imgur.com/7Rtfk.jpg) ``` a="3";aa="1";hint aa ``` **Outputs:** [![](https://i.stack.imgur.com/PDpw5.jpg)](https://i.stack.imgur.com/PDpw5.jpg) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` 3ȷ ``` [Try it online!](https://tio.run/##y0rNyan8/9/4xPb//wE "Jelly – Try It Online") Outputs 3000. `3ȷ` is a numeric literal for 3000. `3ȷȷ` outputs 1000: `3ȷ` is 3000, which is thrown away and replaced by `ȷ`, 1000. This is the only two-byte solution, and it is optimal; I found it by trying every possible program. [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` 5¬ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/00Jr//wE "Actually – Try It Online") Repeating the last character: [`5¬¬`](https://tio.run/##S0wuKU3Myan8/9/00JpDa/7/BwA). Explanation: ``` 5¬ 5 push 5 ¬ subtract 2 ``` Adding another `¬` causes 2 to be subtracted from 3, yielding 1. [Answer] # [Python 2](https://docs.python.org/2/), 9 bytes ``` print 3&3 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwVjN@P9/AA "Python 2 – Try It Online") Prints 3. ``` print 3&33 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwVjN2Pj/fwA "Python 2 – Try It Online") Prints 1. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 2 bytes This prints `3` and `6ee` prints `1`. ``` 6e ``` **[Try it here!](http://pyke.catbus.co.uk/?code=6e&input=&warnings=0&hex=0)** ``` 6ee ``` **[Try it here!](http://pyke.catbus.co.uk/?code=6ee&input=&warnings=0&hex=0)** ``` 6 - Push 6. e - Floor halve. - Print Implicitly. ``` --- # How? Not much to explain. The whole point of this solution is that: ![](https://latex.codecogs.com/gif.latex?%5Cinline&space;%5Ctext%7Bfloor%7D(%5Cfrac%7B6%7D%7B2%7D)=3%5Ctext%7B,%7D "\text{floor}(\frac{6}{2})") ![](https://latex.codecogs.com/gif.latex?%5Cinline&space;%5Ctext%7Bfloor%7D(%5Cfrac%7B%5Ctext%7Bfloor%7D(%5Cfrac%7B6%7D%7B2%7D)%7D%7B2%7D)=1 "\text{floor}(\frac{\text{floor}(\frac{6}{2})}{2})=1") [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` 2_5+ ``` Outputs `27`. [Try it online!](https://tio.run/##S85KzP3/3yjeVPv/fwA "CJam – Try It Online") ``` 2_5++ ``` Outputs `9`. [Try it online!](https://tio.run/##S85KzP3/3yjeVFv7/38A) [Answer] ## Haskell, 8 bytes ``` gcd 3 21 ``` Outputs `3`, and `gcd 3 211` outputs `1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` 81½ ``` [Try it online!](https://tio.run/##y0rNyan8/9/C8NDe//8B "Jelly – Try It Online") Outputs 9. ``` 81½½ ``` [Try it online!](https://tio.run/##y0rNyan8/9/C8NDeQ3v//wcA "Jelly – Try It Online") Outputs 3. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` 3Xr ``` Outputs 3. [Try it online!](https://tio.run/##MzBNTDJM/f/fOKLo/38A) ``` 3Xrr ``` Outputs 1. [Try it online!](https://tio.run/##MzBNTDJM/f/fOKKo6P9/AA) [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 6 bytes Works by changing the path based on cubes with different edge sizes. None of that tricky math stuff. The starting numbers could be also 1 3 or 2 6 ``` 39O@W@ ``` Cubified ``` 3 9 O @ W @ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9/Y0t8h3OH/fwA "Cubix – Try It Online") Only executes `9O@` which is Push 9, Output as number, Halt. ``` 39O@W@ ``` Cubified ``` 3 9 O @ W @ @ . . . . . . . . . . . . . . . . . ``` This now executes `W3O@`, which is Left shift, Push 3, Output as number, Halt. [Try it online!](https://tio.run/##Sy5Nyqz4/9/Y0t8h3MHh/38A "Cubix – Try It Online") [Answer] # Mathematica, 13 bytes ``` PrimeOmega@27 ``` Not the shortest solution but y'know... [Answer] # Polyglot, [05AB1E](https://github.com/Adriandmen/05AB1E) / [2sable](https://github.com/Adriandmen/2sable), 3 bytes This one prints `9`. `81tt` prints `3`. ``` 81t ``` **[Try it online!](https://tio.run/##MzBNTDJM/f/fwrDk/38A "05AB1E – Try It Online")** **[Try it online!](https://tio.run/##MypOTMpJ/f/fwrDk/38A "2sable – Try It Online")** ``` 81tt ``` **[Try it online!](https://tio.run/##MzBNTDJM/f/fwrCk5P9/AA "05AB1E – Try It Online")** **[Try it online!](https://tio.run/##MypOTMpJ/f/fwrCk5P9/AA "2sable – Try It Online")** [Answer] # [Befunge-98](https://github.com/catseye/FBBI), 6 bytes ``` <q%5b' ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/36ZQ1TRJ/f9/AA "Befunge-98 (FBBI) – Try It Online") Outputs via exit code. Explanation: On program start the IP is immediately sent leftwards, so it wraps to the right end and executes commands from right to left. So, in this program, it encounters `'b5%`, which pushes 98, the value of the character `b`, and then computes the remainder of 98 when divided by 5, which is 3. Finally, with `q`, it quits with this exit code. With the last character doubled, it encounters `''b5%`, which pushes the value of the character `'` but then immediately pushes `b`, which is 11. It then computes the remainder of 11 when divided by 5, which is 1, and quits with this exit code. [Answer] # C, ~~60~~ 45 bytes *Thanks to @nwellnhof for saving 15 bytes!* ``` #define AA"5");} #define A"1"AA main(){puts(A ``` [Outputs 15](https://tio.run/##S9ZNT07@/185JTUtMy9VwdFRyVRJ07qWCy6gZKjk6MiVm5iZp6FZXVBaUqzh@P8/AA) ``` #define AA"5");} #define A"1"AA main(){puts(AA ``` [Outputs 5](https://tio.run/##S9ZNT07@/185JTUtMy9VwdFRyVRJ07qWCy6gZKjk6MiVm5iZp6FZXVBaUqzh6Pj/PwA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes This prints `9`. `x8 11` prints `3`. ``` x8 1 ``` **[Try it online!](https://tio.run/##K6gsyfj/v8JCwfD/fwA "Pyth – Try It Online")** ``` x8 11 ``` **[Try it online!](https://tio.run/##K6gsyfj/v8JCwdDw/38A "Pyth – Try It Online")** --- # How? ``` x8 1 - Full program. x - Bitwise XOR. 8 1 - Of 8 and 1. - Implicitly print. ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 5 bytes ``` [q/3g ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@PLtQ3Tv//HwA "Befunge-98 (PyFunge) – Try It Online") Outputs via exit code. ### Explanation First, the IP hits the "turn left" instruction (`[`) twice, which wraps it back around to the back of the code, going right. The "get" instruction (`g`) takes the first 2 values and pushes the ASCII value of the character at that x and y position. The first time it is executed, there are only zeros on the stack, meaning we get the value 91. If we don't double the `g`, we divide 91 by 3, with integer division, truncating it to 30, which is returned. If we do duplicate the `g`, it gets the ASCII value at (0, 91), which isn't anywhere near the code. Because the grid is initialized to be filled with spaces, this returns the value 32. if we integer divide by 3, we get 10, one third of 30. [Answer] # Python 2, 16 bytes ``` a=3;aa=1;print a ``` outputs 3 ``` a=3;aa=1;print aa ``` outputs 1 [Answer] # [V](https://github.com/DJMcMayhem/V), 5 bytes ``` é52ñ ``` [Try it online!](https://tio.run/##K/v///BKU6PDGyX@//@vWwYA "V – Try It Online") Outputs 3 ``` é52ñ ``` [Try it online!](https://tio.run/##K/v///BKU6PDGyUk/v//r1sGAA "V – Try It Online") Outputs 1 [Answer] # [Ly](https://github.com/LyricLy/Ly), 6 bytes ``` 3>1<<> ``` [Try it online!](https://tio.run/##y6n8/9/YztDGxu7/fwA "Ly – Try It Online") Outputs `3`. With the second character duplicated: ``` 3>1<<>> ``` [Try it online!](https://tio.run/##y6n8/9/YztDGxs7u/38A "Ly – Try It Online") Outputs `1`. [Answer] # [Recursiva](https://github.com/officialaimm/recursiva), 5 bytes ``` +16-1 ``` [Try it online!](https://tio.run/##K0pNLi0qzixL/P9f29BM1/D/fwA "Recursiva – Try It Online") * Ripped off from [Many languages solution](https://codegolf.stackexchange.com/a/140592/59523), only a byte more since Recursiva is prefix and `-` sign and subtract operator are the same. This is actually adding `16` and `-1`. # Other solution: # [Recursiva](https://github.com/officialaimm/recursiva), 10 bytes ``` Y_+B5A3IH1 ``` [Try it online!](https://tio.run/##K0pNLi0qzixL/P8/Ml7bydTR2NPD8P9/AA "Recursiva – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes This one outputs `3`. By doubling the last character, you get `1`. ``` HḞ 6Ç ``` **[Try it online!](https://tio.run/##y0rNyan8/9/j4Y55XGaH2///BwA "Jelly – Try It Online")** ``` HḞ 6ÇÇ ``` **[Try it online!](https://tio.run/##y0rNyan8/9/j4Y55XGaH2w@3//8PAA "Jelly – Try It Online")** [Answer] # [Japt](https://github.com/ETHproductions/japt/), 3 bytes Still on the hunt for a 2 byte solution. `#Q` is 81 and `¬` is square root, which gives `9`. Adding another `¬` at the end gives `3` ``` #Q¬ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=I1Gs&input=) ``` #Q¬¬ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=I1GsrA==&input=) [Answer] # [><>](https://esolangs.org/wiki/Fish), 6 bytes ``` ",n;c! ``` [Try it online!](https://tio.run/##S8sszvj/X0knzzpZ8f9/AA "><> – Try It Online") ``` ",n;c!! ``` [Try it online!](https://tio.run/##S8sszvj/X0knzzpZUfH/fwA "><> – Try It Online") ### Explanation ``` ",n;c! : Put each character onto the stack; [110, 59, 99, 33] ,n; : Divide the top two stack items, print as a number and end. 99/33 = 3 ``` --- ``` ",n;c!! : Put each chat onto the stack; [110, 59, 99, 33, 33] ,n; : Divide the top two stack items, print as a number and end. 99/33 = 3 ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 2 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` 9₃ ``` Returns 9/3 [Try it online!](https://tio.run/##K6gs@f/f8lFT8///AA) --- ``` 9₃₃ ``` Returns (9/3)/3 [Try it online!](https://tio.run/##K6gs@f/f8lFTMxD9/w8A) --- Alternatively, also 2 bytes: ``` 6₂ ``` This works due to Python 2's integer division [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` -16 1 ``` [Try it online!](https://tio.run/##K6gsyfj/X9fQTMHw/38A "Pyth – Try It Online") * Yet another rip from [many languages answer](https://codegolf.stackexchange.com/a/140592/59523) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes This one prints `15`. The other version prints `5`. ``` I⁻¹⁶¦¹ ``` **[Try it online!](https://tio.run/##ARsA5P9jaGFyY29hbP//77yp4oG7wrnigbbCpsK5//8 "Charcoal – Try It Online")** ``` I⁻¹⁶¦¹¹ ``` **[Try it online!](https://tio.run/##AR0A4v9jaGFyY29hbP//77yp4oG7wrnigbbCpsK5wrn//w "Charcoal – Try It Online")** [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` ηᚠ ``` Outputs 3. Doubled, outputs 1. [Try it online!](https://tio.run/##y0vNzP3//9z2h7MW/P8PAA "Neim – Try It Online") [Doubled](https://tio.run/##y0vNzP3//9z2h7MWANH//wA "Neim – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/22756/edit). Closed 6 years ago. [Improve this question](/posts/22756/edit) Write the shortest program you can that displays a red 3D cube. Rules: * The cube must be red, have 6 rendered sides, and be displayed in 3D. * Your program cannot load any textures. * More than 1 side must be visible. * The result does not need to be rotatable. [Answer] ## T-SQL, 168 chars (but no OpenGL) Decidedly *not* using OpenGL or Direct3D because there is absolutely no way to do that in SQL. I think I have a pretty nice little cube, anyway. ``` RAISERROR(' @@@ @@@@@@@@@ @@@@@@@@@@@@@@@ x@@@@@@@@@@@@&& xxx@@@@@@@@&&&& xxxxx@@@&&&&&&& xxxxxx&&&&&&&&& xxxxx&&&&&&& xxx&&&& x&& ',15,1) ``` Exploiting the fact that errors of high severity are raised in red: ![srs errr](https://i.stack.imgur.com/W6LQG.jpg) [Answer] ## Mathematica 25 ``` Graphics3D@{Red,Cuboid[]} ``` ![Mathematica graphics](https://i.stack.imgur.com/1BW39.png) Instructions for testing this answer without Mathematica installed: 1. Download <http://pastebin.com/3dnGNHCP> and save it as \*.CDF 2. Dowload the free CDF environment from Wolfram Research at <https://www.wolfram.com/cdf-player/> (not a small file) 3. The cube can be "dragged" to rotate it! [Answer] # TXT, 12 bytes This is a TXT file with ANSI escape codes and UTF-8 characters. I can show its contents as a C string: ``` "\033[31m\xe2\xac\xa2\033[m\n" ``` or as a hexdump: ``` 0000000: 1b5b 3331 6de2 aca2 1b5b 6d0a .[31m....[m. ``` This is the result when it is "executed" with `cat` on a terminal. You can see the small cube, solid red, with 3 visible faces and no texture loaded: ![cube.txt](https://i.stack.imgur.com/LPgLw.png) [Answer] May i be the first to... # Processing, ~~513~~ 110 ``` void setup(){size(640,360,P3D);}void draw(){fill(255,0,0);translate(width/2,height/2,0);rotateX(0.7);box(99);} ``` ![example](https://i.stack.imgur.com/Xd3On.png) [Answer] # [Sage](http://www.sagemath.org/), 17 *Note: after some research I realised that this does not use OpenGL.* ``` cube(color='red') ``` Output: ![enter image description here](https://i.stack.imgur.com/MbKQ6.png) I can finally beat Mathematica! It uses [Jmol](http://jmol.sourceforge.net/) (which comes with the Sage installation) to show the cube, which allows rotation by dragging. [Answer] # Processing, 68 Chars Ultra-golf version of @TheDoctor 's answer, using tips from @Ace, plus one of my own (rotation.) ``` void setup(){size(99,99,P3D);fill(#FF0000);translate(9,9,0);box(9);} ``` Produces a pathetically small cube of just 9 units per side (image at left.) Changing the `9`'s to `25`'s we get a larger cube (image at right.) By keeping the cube far from the centre of the window, we can see the bottom and right hand side without needing to rotate (if it was in the centre of the window, they would be hidden. ![enter image description here](https://i.stack.imgur.com/Cw6zD.png) [Answer] # Mathematica 9, 21 ``` Image3D@{{{{3,0,0}}}} ``` ![enter image description here](https://i.stack.imgur.com/UtqIS.png) --- # Mathematica 10, 17 ``` Image3D@{{{Red}}} ``` [Answer] # Windows Batch, 51 chars ``` @echo off color 0c echo _ echo /!_! echo |/_/ ``` I know this is cheating, but at least I get bronze (at the time this was posted). Partially inspired by Jonathan van Matre's answer. [Answer] # Postscript 920 Requires [mat.ps](http://web.archive.org/web/20160404161539/https://code.google.com/p/xpost/downloads/detail?name=mat.ps&can=2&q=). ``` /olddiv/div load def/div{dup 0 eq{pop pop 100000}{olddiv}ifelse}def(mat.ps)run/disp<</cam[0 0 10]/theta[0 0 0]/eye[0 0 20]/Rot 3 ident>>def/makerot{theta 0 get roty theta 1 get rotx matmul theta 2 get rotz matmul}def/proj{DICT begin cam{sub}vop Rot matmul 0 get aload pop eye aload pop 4 3 roll div exch neg 4 3 roll add 1 index mul 4 1 roll 3 1 roll sub mul exch end}dup 0 disp put def/v[[1 1 -1][-1 1 -1][-1 -1 -1][1 -1 -1][1 1 1][-1 1 1][-1 -1 1][1 -1 1]]def /fv[[0 1 2 3][0 4 5 1][1 5 6 2][2 6 7 3][3 7 4 0][4 7 6 5]]def/R 20 def/H -3 def/ang 0 def {300 700 translate 1 70 dup dup scale div setlinewidth disp begin/cam[ang sin R mul H ang cos R mul]def/theta[ang H R atan 0]def/Rot makerot def end fv{{v exch get proj}forall moveto lineto lineto lineto closepath 1 0 0 setrgbcolor fill}forall fv{{v exch get proj} forall moveto lineto lineto lineto closepath 0 setgray stroke}forall showpage/ang ang 3 add def}loop ``` Ungolfed and commented. ``` %! /olddiv/div load def /div{dup 0 eq{pop pop 100000}{olddiv}ifelse}def (mat.ps)run /disp << /cam [ 0 0 10 ] % Camera position /theta [ 0 0 0 ] % Rotation sequence /eye [ 0 0 20 ] % Eye relative to image surface /Rot 3 ident >> def /makerot { theta 0 get roty theta 1 get rotx matmul theta 2 get rotz matmul } def % Ax Ay Az /proj { DICT begin %3 array astore %dup == flush cam {sub}vop %Camera translation %pstack()= Rot matmul %Camera rotation 0 get aload pop % Dx Dy Dz eye aload pop % Dx Dy Dz Ex Ey Ez %pstack()= 4 3 roll div % Dx Dy Ex Ey Ez/Dz exch neg % Dx Dy Ex Ez/Dz -Ey 4 3 roll add % Dx Ex Ez/Dz Dy-Ey 1 index mul % Dx Ex Ez/Dz Ez(Dy-Ey)/Dz 4 1 roll 3 1 roll % Ez(Dy-Ey)/Dz Ez/Dz Dx Ex sub mul exch % Ez(Dx-Ex)/Dz Ez(Dy-Ey)/Dz %pstack ()= end } dup 0 disp put def /v [[ 1 1 -1 ] %cube vertices [ -1 1 -1 ] [ -1 -1 -1 ] [ 1 -1 -1 ] [ 1 1 1 ] [ -1 1 1 ] [ -1 -1 1 ] [ 1 -1 1 ]] def /fv [[ 0 1 2 3 ] %cube faces out of vertices [ 0 4 5 1 ] [ 1 5 6 2 ] [ 2 6 7 3 ] [ 3 7 4 0 ] [ 4 7 6 5 ] ] def /R 20 def /H -3 def /ang 0 def { 300 700 translate 1 70 dup dup scale div setlinewidth disp begin /cam [ ang sin R mul H ang cos R mul ] def /theta [ ang H R atan 0 ] def /Rot makerot def end fv { { v exch get proj } forall moveto lineto lineto lineto closepath 1 0 0 setrgbcolor fill } forall fv { { v exch get proj } forall moveto lineto lineto lineto closepath 0 setgray stroke } forall showpage /ang ang 3 add def } loop ``` [Answer] ## JAVASCRIPT - TQUERY (108 chars) ``` w=tQuery.createWorld().boilerplate().start();tQuery.createCube().addTo(w).setBasicMaterial().color(0xff0000) ``` ``` <script src="https://jeromeetienne.github.io/tquery/build/tquery-bundle.js"></script> ``` <http://jsfiddle.net/Gy4w7/335/> [Answer] ## RBX.Lua, 83 bytes ``` s=Instance.new("Part",workspace)s.BrickColor=BrickColor.new(21)s.Size=Vector3.new() ``` Result: [![Result](https://i.stack.imgur.com/JRgmB.png)](https://i.stack.imgur.com/JRgmB.png) Explanation: ``` s=Instance.new("Part",workspace) Instances a new Brick in the world. s.BrickColor=BrickColor.new(21) Makes it red. 21 is the color code for "Bright red". s.Size= We have to set the size, because a brick isn't cubic. Vector3.new() Initiates a [0, 0, 0] size. The brick rounds this up to the minimum size. ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/11215/edit). Closed 10 years ago. [Improve this question](/posts/11215/edit) **Task** Write a function to generate names of aliens and their worlds, so that the output is of the form: ``` Greetings Earthfolk, I am ____ of the planet _____. ``` **"Rules"** Best space-sounding-ness to code length wins. The more diversity the better. Dictionaries/look-up tables count towards code length. Random number generators definitely allowed, other libraries less so. Provide examples of the output. [Answer] ## APL (72) Not entirely serious, but I couldn't resist. The names are generated from a subset of the APL charset. The names are between 5 and 14 characters long. ``` {'Greetings Earthfolk, I am'⍺'of the planet'⍵}/{⎕AV[186+{?25}¨⍳4+?9]}¨⍬⍬ ``` Example output: ``` Greetings Earthfolk, I am ⌹⍒|⍟∩⊤∩⍉⊂⊥⌽ of the planet ∩⌹⍱⍎∪≢⊂∩ Greetings Earthfolk, I am ⍕≡|⍕⍋!⍟⌹ of the planet ⊂⊤⊤⌽⍟⊖⍱⊤⊤⍟⊥ Greetings Earthfolk, I am ≢⍉⊂⍫⊂ of the planet ⍋⌽!⍟⍉⊂∪≢ ``` [Answer] # Perl, 51 characters ``` print"Greetings Earthfolk, I am ~ of the planet ~." ``` The aliens communicate using a special space language that is not translatable in human text or speech. It is customary to use the character `~` to represent any word in the aliens' native tongue. Thus this answer is very space-sounding and also contains a great deal of diversity, which, unfortunately, is not able to be adequately represented using a standard character set. [Answer] ### GolfScript, 85 characters ``` 26,{97+}%{9,{;..,rand=}%@@}2*;;"Greetings Earthfolk, I am "\+" of the planet "+\+"."+ ``` [(online test version)](http://golfscript.apphb.com/?c=MjYsezk3K30lezksezsuLixyYW5kPX0lQEB9Mio7OyJHcmVldGluZ3MgRWFydGhmb2xrLCBJIGFtICJcKyIgb2YgdGhlIHBsYW5ldCAiK1wrIi4iKw%3D%3D) ``` Greetings Earthfolk, I am mfevurnoh of the planet pclqvbpcu. Greetings Earthfolk, I am niuzigmuu of the planet wdkosibdb. Greetings Earthfolk, I am tvihxsxhd of the planet depkxwcto. ``` Pclqvbpcuans and wdkosibdbeans apologise for having chosen such a difficult name for us to pronounce for their planet. Tvihxsxhd's first parent also apologises for the double "x" in tvihxsxhd's name. He said he would never expect their child to travel to Earth. longer version, but more pronounceable names: ### GolfScript, 105 characters ``` "aeiouy".26,{97+}%\-{5,{;..,rand=2$.,rand=}%@@}2*;;"Greetings Earthfolk, I am "\+" of the planet "+\+"."+ ``` [(online test version)](http://golfscript.apphb.com/?c=ImFlaW91eSIuMjYsezk3K30lXC17NSx7Oy4uLHJhbmQ9MiQuLHJhbmQ9fSVAQH0yKjs7IkdyZWV0aW5ncyBFYXJ0aGZvbGssIEkgYW0gIlwrIiBvZiB0aGUgcGxhbmV0ICIrXCsiLiIr) Sample output: ``` Greetings Earthfolk, I am nirexahuji of the planet hulabasesa. Greetings Earthfolk, I am xepozidylo of the planet wuxasidape. Greetings Earthfolk, I am jypakivixy of the planet lutegujyxo. ``` For those who are claiming that they wrote us a letter, not spoke to us (and thus capitalisation is important), this can be fixed in as few as six characters: ``` 26,{97+}%{9,{;..,rand=}%(32-\+@@}2*;;"Greetings Earthfolk, I am "\+" of the planet "+\+"."+ ``` [(test)](http://golfscript.apphb.com/?c=MjYsezk3K30lezksezsuLixyYW5kPX0lKDMyLVwrQEB9Mio7OyJHcmVldGluZ3MgRWFydGhmb2xrLCBJIGFtICJcKyIgb2YgdGhlIHBsYW5ldCAiK1wrIi4iKw%3D%3D) ``` "aeiouy".26,{97+}%\-{5,{;..,rand=2$.,rand=}%(32-\+@@}2*;;"Greetings Earthfolk, I am "\+" of the planet "+\+"."+ ``` [(test)](http://golfscript.apphb.com/?c=ImFlaW91eSIuMjYsezk3K30lXC17NSx7Oy4uLHJhbmQ9MiQuLHJhbmQ9fSUoMzItXCtAQH0yKjs7IkdyZWV0aW5ncyBFYXJ0aGZvbGssIEkgYW0gIlwrIiBvZiB0aGUgcGxhbmV0ICIrXCsiLiIr) [Answer] Javascript golfed ( 186 bytes ) ``` function f(){for(c=[],b=0;new Date%30+2>b;)c[++b]=String.fromCharCode(Math.random()*25|0+(b<2?65:97));return c.join('')}alert('Greetings Earthfolk, I am '+f()+' of the planet '+f()+'.') ``` Example Output: > > Greetings Earthfolk, I am Kugwegoysuseq of the planet Esagqwsakeges. > > Greetings Earthfolk, I am Ui of the planet Oq. > > Greetings Earthfolk, I am Qeuseoswwusk of the planet Gsyuemaeqqwa. > > Greetings Earthfolk, I am Usyssacemsiiokk of the planet Mgscemkaooaggku. > > Greetings Earthfolk, I am Egugskkgmk of the planet Ecakmkayys. > > > Keep in mind without the bulky text in the output, the function alone is 121 bytes. Also the names and the planet names are the same character len so I can save a few characters and use `new Date%30+2` however if this is an issue just run them a ~hundred ms apart. [Answer] # PHP - 283 with line breaks. Here's my code for alien sounding words. My goal was to make it sound like a legitimate language without difficult pronunciation. The apostrophe's suffix the preceding letter with the 'yeh' sound (e.g. GYEH, DYEH, FYEH, etc.). All vowels are of the long-vowel sound, with the exception of A and E, which are short. Granted, this sounds like a single language rather than many diverse languages, but I don't care. ``` <?$a=$z="";function w(){$k=array("B","D","F","G","J","K","L","M","N","P","T","V","W","Z");$v=array("A","E","O","U","'");return$k[rand(0,13)].$v[rand(0,4)];}for($i=0;$i<rand(3,8);$i++){$a.=w();}for($i=0;$i<rand(3,8);$i++){$z.=w();}echo"Greetings Earthfolk, I am $a of the planet $z."; ``` Here's the ungolfed version: ``` <?php $a=$z=""; function rk() { $k = array("B","D","F","G","J","K","L","M","N","P","T","V","W","Z"); return $k[rand(0,13)]; } function rv() { $v = array("A","E","O","U","'"); return $v[rand(0,4)]; } function rp() { return rk().rv(); } for ($i=0; $i < rand(3,8); $i++) { $a .= rp(); } for ($i=0; $i < rand(3,8); $i++) { $z .= rp(); } echo "Greetings Earthfolk, I am $a of the planet $z."; ?> ``` Sample outputs: * Greetings Earthfolk, I am **NEMEWEJU** of the planet **N'VUMELULOFU**. * Greetings Earthfolk, I am **FUM'FELE** of the planet **WUW'JEDUG'GELA**. * Greetings Earthfolk, I am **ZUDEWEGUPOGE** of the planet **LUNOT'ZEJALOTU**. * Greetings Earthfolk, I am **M'DOMAMO** of the planet **WUWAGUBU**. [Answer] Python Code : This code will generate random words of random length . ``` from random import *;t=range;l=map(chr,t(97,123));k=m="";r=randint for i in t(r(1,100)):k+=l[r(0,25)] for i in t(r(1,100)):m+=l[r(0,25)] print "Greetings Earthfolk, I am",k," of the planet",m ``` Sample output: ``` Greetings Earthfolk, I am ixpygrfoswpkby of the planet kanhkcg Greetings Earthfolk, I am ijojukgjfxcbdt of the planet zvllqgtqihkxy Greetings Earthfolk, I am svbwsgrwgedfshw of the planet inepzkdzerbkscy Greetings Earthfolk, I am srixnnlqendbnbcqbghpdfotvxhfjidpdypzhkoddtbfhbjneaagnxtfqlbikfmrfrjwkwjoordvmks of the planet qxyrvaxwnktqffbwcloeznkzuhkwzbwusksaychspjedtvrwxzjeoxtymrgfhqelqrwhquxrlvjbnbghiml ``` The last one is most "aliener" among the random outputs :D .. We can even shorten the code more by adding the restriction of having the length of the planet's and alien's name of same length ``` from random import *;t=range;l=map(chr,t(97,123));k=m="";r=randint for i in t(r(1,100)):k+=l[r(0,25)];m+=l[r(0,25)] print "Greetings Earthfolk, I am",k," of the planet",m ``` Sample outputs : ``` Greetings Earthfolk, I am grtmsmjxbcvfcqfrvnmxuburprkgofstzemaflrbwtxabpdmmkhohntmvgkwcntjhefvrbcuzbdkrrgbxgsbwkrevi of the planet mzuykipozdfhzalajaarqlrcoebmalrmfdvevieldqmuojwsfjbcfxdwwxakilcpwprdyedzplhxyafstcbpwdfzor Greetings Earthfolk, I am rltfsxhaiybpqthmkwprepkchbeprxnkiaoyaujwehgsbafxwikenohviyxnj of the planet qdgoyjqcwlopfgciethfqfaffhloqbmjkkonwutabozgbmzpyrsftiunucnse Greetings Earthfolk, I am ynyhetukywsfgllbzejrmqygbzerhbrnorflri of the planet qgihkeymaujjgltgzaeyfhnbqyzjtlpsnpnmbl ``` [Answer] # Lua, 211 ``` m,c=math.random,("").char print(((" "):rep(9):gsub(".",function()return c(("aeiouy"):byte(m(1,6)))end):gsub(".-",function()return c(m(97,122))end):gsub("^.......","Greetings Earthfolk, I am %1 of the planet "))) ``` > > Greetings Earthfolk, I am toqujor of the planet aeilywyvuief > > > Greetings Earthfolk, I am kyvirux of the planet ymofoyyxidyw > > > Greetings Earthfolk, I am hooikoe of the planet exucedimetez > > > Greetings Earthfolk, I am dytudiu of the planet ueitebeyoben > > > Greetings Earthfolk, I am denecub of the planet ufolyvooutab > > > ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 9 years ago. [Improve this question](/posts/31464/edit) The challenge: Write a function, that delivers following output: "1 2 3 4 5 4 3 2 1". Kids stuff? Of course. But here's the point: * You only can use: 1 for loop, 2 int variables. * You must not use: IF terms, another function, ... * Do not hardcode the output There are also some more restrictions to make this harder: * No functions like abs or sth. else are allowed! (Yep, it's possible) * No static output like echo "1 2 3 4 5 4 3 2 1" This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most votes wins! [Answer] ## Python One for loop, one int variable (`i`), no if, no other functions (unless you consider `print` or `+-*/` as functions, haha): ``` for i in range(9): print i+1 - 2*(i//5)*(i-4), ``` [Answer] # C No function, no hidden IF (abs, min, etc.) ``` #include <stdio.h> int main() { int sum=0; for (int i=3; i<12; i++) { sum += 1-2*(i/8); printf("%d\n", sum ); } } ``` Explanation : The 4th bit of i is the heart of the trick : it's 0 for [3,7] and 1 for [8,11]. i/8 gives the value of the bit (just like i>>3) for i in [3,11] it gives : 0, 0, 0, 0, 0, 1, 1, 1, 1 1-2\*(i/8) is simple math to obtain 1, 1, 1, 1, 1, -1, -1, -1, -1 += is used to sum the values [Answer] **Javascript, 32 characters** ``` +new Date(1970,0,2,11,17,34,321) ``` *edit:* **not timezone-dependant, 42 chars** ``` +new Date(Date.UTC(1970,0,2,10,17,34,321)) ``` [Answer] # Cobra ## Really, this is quite trivial. ``` class Program def main for i in 10, Console.write(5 - Math.abs(5 - i)) ``` Or ``` class Program def main v as int = 123454321 for i in v.toString, Console.write(i) ``` Or even simpler ``` class Program def main print 1, 2, 3, 4, 5, 4, 3, 2, 1 ``` ## But if you insist on following the question *exactly*: ``` class Program def main num as int = 123454321 for i in '[num]' Console.write(i) Console.write(' ') ``` This uses only one integer variable, only one loop, and the only function explicitly called is used for output. [Answer] ### Golfscript, 16 characters ``` 6,(;)1$-1%++' '* ``` I assume this is meant to be a code golf? No variables. All data (two arrays and a number) is on the stack. The only loops are implicit ones. Online demonstration: <http://golfscript.apphb.com/?c=NiwoOykxJC0xJSsrJyAnKg%3D%3D> [Answer] **C++: Works finely in VC 11.0** ``` #include <iostream> #include <cstring> #include <vector> #include <conio.h> #include <algorithm> using namespace std; bool called = false; int main(); int f() { called = true; typedef vector<int>::iterator _v_interate; int l; static bool d; vector<int> iVector; for(l = 1; (true); (!d) ? l++ : l--) { _v_interate i = find(iVector.begin(), iVector.end(), 4); _v_interate i2 = find(iVector.begin(), iVector.end(), 3); _v_interate i3 = find(iVector.begin(), iVector.end(), 2); _v_interate i4 = find(iVector.begin(), iVector.end(), 1); _v_interate i5 = find(iVector.begin(), iVector.end(), 5); d = (i != iVector.end()) && (i2 != iVector.end()) && (i3 != iVector.end()) && (i4 != iVector.end()) ? 1 : 0; iVector.push_back(l); cout << l << " "; (d && (l==1) ? main() : 0); } return 0; } int main() { !called ? f() : 0; _getch(); exit(0); // Removing the exit(0) causes an infinite loop; I don't know why. return 0; } ``` A simple solution: ``` #include <iostream> void main() { cout << "1 2 3 4 5 4 3 2 1"; } ``` [Answer] # Delphi XE3 I dont think this requires much explaining right? ``` function p:string; var i:integer; begin for I:=1 to 4 do Result:=Format('%s%d ',[Result,I]); Result:=Format('%s%d%s',[Result,5,ReverseString(Result)]); end; ``` In case it does. Function loops from 1 to 4, and keeps adding the number + [space]. Then it adds I again which became 5 which made it quit the loop and adds the reversed string as it is now. # Variation ``` function p:string; ``` const s='123454321' var i:integer; begin s:='123454321'; for I:=1to Length(s) do Result:=Format('%s %s',[Result,s[i]]); Exit(Trim(Result)); end; This might seem hardcoded but the constant doesnt have the spaces that are required. Although it might seem impossible but there is a solution that is even lamer than this. ``` function p:string; const s='123454321' begin result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9]]) {or} result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[4],s[3],s[2],s[1]]) {OR!} result:=Format('%d %d %d %d %d %d %d %d %d',[1,2,3,4,5,4,3,2,1]) end; ``` [Answer] # Perl ### Version 1: ``` for(1..9){ $x = ($_%18 - 5); print 5 - ($x, -$x)[$x < -$x] . " "; } ``` ### Version 2: ``` for(1..9){ $x = ($_%18 - 5); $x =~ s/-//; print 5 - $x . " "; } ``` For both versions: 1 For loop, and 2 variables, `$_` and `$x`, and I'm not using `if` or any other function. [Answer] Ruby - **47 chars** ``` (1..4).to_a.push((1..5).to_a.reverse).join ' ' ``` Edit - **33 chars** ``` [*(1..4),[*(1..5)].reverse]*' ' ``` [Answer] **Java** Used one loop and the loop variable. Added a constant for the upper bound. ``` public class Test { private static final int BOUND = 5; public static void main(String[] args) { for (int i = 1; i < BOUND * 2; i++) { System.out.print(i - (2 * ((i % BOUND) * (i / BOUND))) + " "); } } } ``` [Answer] # Brainfuck, 83 ``` +++++++[>+++++++>+++++++>+++++++>+++++++>+++++++<<<<<-]>.>+.>++.>+++.>++++.<.<.<.<. ``` Only 1 loop, no `if`s (if you don't count the loop as an `if`). No `int` variables. [Answer] # JavaScript ``` function f(){ for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) ) console.log(i); } ``` [Answer] # C Not sure if it follows exactly the rules but my answer is below ``` int main() { int x; for(x = 123454321; x > 10; x /= 10) { printf("%d ", x % 10); } printf("%d", x); return 0; } ``` [Run the code](https://ideone.com/lJuyk1) [Answer] Well, I guess the fastest and most naive solution (in Python) would be: ``` ' '.join (str(x) for x in range(1,6)) + ' ' + ' '.join (str(x) for x in range(4,0,-1)) ``` [Answer] # Javascript This might not be the best and fastest way to do it, but I like what I came up with. ``` z = ''; for (x = 1; x <= 5; x++) { // Don't need a loop, but hey, I like loops! z += x + ' '; // Creates "1 2 3 4 5 " } document.getElementById('result').innerHTML = z + z.split("").reverse().join("").substring(2, 10); // "1 2 3 4 5 " + " 4 3 2 1" ``` Result: ``` 1 2 3 4 5 4 3 2 1 ``` You can see it in action [Here](http://jsfiddle.net/ebWaL/4/)! [Answer] As 2.0 ``` var num:Int = 11111; alert(num*num); ``` [Answer] ## Java, 79 chars (standalone: 131 chars) ``` int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));} ``` Uses two `int`s, and no other variables. No if statements, just a for loop for evaluation. This will run on its own when put in the main(String[] args) method in a class, or in any other function. The full code, including class declaration and method, is 131 chars. ``` public class M{public static void main(String[]a){int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}}} ``` While I'm at it: ## PHP, 70 chars (standalone: 78 chars) ``` $b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");} ``` Uses same method as Java. Standalone script is 62 chars: ``` <?php $b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}?> ``` [Answer] **C** ``` #include <stdio.h> int main(void) { int i; for (i = 21911761; i > 0 && printf("%d", i&7); i = i>>3) i > 1 && printf(" "); return 0; } ``` [Answer] # Fortran 90: 60 ``` integer::j(9)=5;do i=1,4;j(i)=i;j(10-i)=i;enddo;print*,j;end ``` If you wanted it formatted slightly better, I can add a few characters to make the print statement `print'(9i2)',j`. Ungolfed & written properly, this is ``` program main implicit none integer :: i, j(9) j = 5 do i=1,4 j(i) = i j(10-i) = i enddo print *,j end program main ``` [Answer] # Powershell ``` ((1..9)|%{ $_ = ($_%18-5) 5 - @($_,-$_)[$_ -lt -$_] })-join ' ' ``` 1 variable, no `if`, no functions (unless you were to count `-join` which is just for displaying the data... **Explanation:** Loops from 1 to 9, then for each value calculates the reminder of the current value by 18, then subtracts 5 and assigns it to the currently used `$_` variable. After that it evaluates `$_ < -$_` (this is to handle negative values), and uses the result (`False`/`True`) to get the value from the array `@($_,-$_)`, therefore making sure we always get a positive number in this case, after that it subtracts this number to 5 and finally joins the results with space. [Answer] # Scala, 53 ``` (4 to 12).foldLeft(1)((a,b)=>{print(a);a+1-2*(b/8)}) ``` I stole the neat bit shifting idea from @cpri <http://scalafiddle.net/console/3b3fff6463464959dcd1b68d0320f781> ]
[Question] [ Consider this file path: ``` C:/Users/Martin/Desktop/BackupFiles/PC1/images/cars/new.png ``` Your goal is to write a program that will return the file path starting from the folder after the last folder that contains a number till the filename. So, for the above file path, the program should return `images/cars/new.png`. One or more of the folder names may also contain spaces: ``` C:/Users/User1/Documents/Books/eBooks/PM2.4/ref/Project Management.pdf ``` should return `ref/Project Management.pdf`. Also this filepath: ``` C:/Users/John/Videos/YouTube/3D/Animations/52.Tricky.Maneuvers/video234.png ``` should return `video234.png`. Your answer should work with the above given three examples and all other examples that match the criteria described here. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the lowest number of bytes yields victory. I am new to the site, so feel free to modify my post and/or add relevant tags. [Answer] # JavaScript (ES6), ~~29~~ 28 bytes *Saved 1 byte thanks to @tsh* ``` s=>s.replace(/.*\d.*?\//,'') ``` [Try it online!](https://tio.run/##fY4xb8IwEIX3/opuSVDxiUAXJFoBUYdKkTLQSpVYjHMJJsFn@exU/PrgqF3b5d4N7/v0LnKQrJy2fm6oxrHZjLx5YeHQ9lJhCmJ2rMXs9QjwlCTZqMgw9Sh6atMmTfZr@GB0DKV0XhsokDtPFnZSdcG@6R4Zqv0C9FW28VUyVg1@C2vaJMse/rJNdwEFqXBF4xl2RB0D/kRV5mIFDhuoHF1Q@cdSmqifqsLWzX/idzob@NQ1EsMXhUM4ISwL2Jo40OsIwXMuDk6r7iaiFcMwUcME5MvV7@zxDg "JavaScript (Node.js) – Try It Online") ### How? ``` /.*\d.*?\// \/\/\_/\/ | | | | match the longest possible string (greedy) ---+ | | | match a digit ----------------------------------+ | | match the shortest possible string (lazy) ---------+ | match a slash ---------------------------------------+ ``` [Answer] # [Gema](http://gema.sourceforge.net/), 8 bytes ``` *<D>*\/= ``` Sample run: ``` bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/Martin/Desktop/BackupFiles/PC1/images/cars/new.png' images/cars/new.png bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/User1/Documents/Books/eBooks/PM2.4/ref/Project Management.pdf' ref/Project Management.pdf bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/John/Videos/YouTube/3D/Animations/52.Tricky.Maneuvers/video234.png' video234.png ``` [Try it online!](https://tio.run/##S0/NTfz/X8vGxU4rRt/2/39nK/3Q4tSiYn3fxKKSzDx9l9Ti7JL8An2nxOTs0gK3zJzUYv0AZ0P9zNzEdCAzORGoNC@1XK8gLx0A "Gema – Try It Online") [Answer] # sed, 17 bytes ``` s:.*[0-9][^/]*/:: ``` [Try it online](https://tio.run/##PYyxCoMwGIT3PkVnwVwtXZpRpVvApZNYCPFXrJqE/JE@fqoUutx3w3fH1Oej3VJiKbL2kt@79oUug5QpVRJPpsBQOsTJoiaeo/MotZk3/5gWYjRVgWnV416N3lVLH@HtePpvjyxQO7OtZCOjdG5m0A@NuoobAg1ognuTiWel7X52qML3wxc). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '/©¡RćUηí®ýʒþd_}®«õš¤X« ``` [Try it online](https://tio.run/##AW0Akv9vc2FiaWX//ycvwqnCoVLEh1XOt8Otwq7DvcqSw75kX33CrsKrw7XFocKkWMKr//9DOi9Vc2Vycy9NYXJ0aW4vRGVza3RvcDMvQmFja3VwRmlsZXMvUEMwL2ltYWdlcy9jYXJzL25ldzEucG5n) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf3X9QysPLQw60h56bvvhtYfWHd57atLhfSnxtYfWHVp9eOvRhYeWRBxa/V/nv7OVfmhxalGxvm9iUUlmnr5LanF2SX6BvlNicnZpgVtmTmqxfoCzoX5mbmI6kJmcCFSal1quV5CXzgXXCyIN9V3yk0tzU/NKivWd8vOzi/VTIVSAr5GeiX5Rapp@QFF@VmpyiYJvYh7QMJBSvYKUNIQxXvkZefphmSmp@cX6kfmlIaVJqfrGLvqOeUDLSzLz84r1TY30Qooyk7Mr9YBmpJaWgXSVgTQYGZvAnJRoqJ@Iai6q14zR/GaA7jdDkEkA). 05AB1E has no regexes, so this is not the kind of challenge it will do very good, in comparison to non-verbose languages that have a strength in regexes like Retina or Pyth. Can probably still be golfed by at least a few bytes, though. **Explanation:** ``` '/ # Push a "/" © # Store it in the register (without popping) ¡ # Split the (implicit) input on slashes # i.e. "C:/Desktop3/Stuff/F0/images/new1.png" # → ["C:","Desktop3","Stuff","F0","images","new1.png"] R # Reverse this list # i.e. ["C:","Desktop3","Stuff","F0","images","new1.png"] # → ["new1.png","images","F0","Stuff","Desktop3","C:"] ć # Head extracted # i.e. ["new1.png","images","F0","Stuff","Desktop3","C:"] # → ["images","F0","Stuff","Desktop3","C:"] and "new1.png" U # Pop the extracted head, and store it in variable `X` η # Take the prefixes of the list # i.e. ["images","F0","Stuff","Desktop3","C:"] # → [["images"],["images","F0"],["images","F0","Stuff"],["images","F0","Stuff","Desktop3"],["images","F0","Stuff","Desktop3","C:"]] í # Reverse each inner list again # i.e. [["images"],["images","F0"],["images","F0","Stuff"],["images","F0","Stuff","Desktop3"],["images","F0","Stuff","Desktop3","C:"]] # → [["images"],["F0","images"],["Stuff","F0","images"],["Desktop3","Stuff","F0","images"],["C:","Desktop3","Stuff","F0","images"]] ®ý # And join them by slashes # i.e. [["images"],["F0","images"],["Stuff","F0","images"],["Desktop3","Stuff","F0","images"],["C:","Desktop3","Stuff","F0","images"]] # → ["images","F0/images","Stuff/F0/images","Desktop3/Stuff/F0/images","C:/Desktop3/Stuff/F0/images"] ʒ } # Now filter this list by: þ # Leave only the digits of this suffix # i.e. "images" → "" # i.e. "Stuff/F0/images" → 0 d # Check if its >= 0 # i.e. "" → 0 (falsey) # i.e. 0 → 1 (truthy) _ # Inverse the boolean (0→1; 1→0) ®« # Append a slash to each remaining suffix # i.e. ["images"] → ["images/"] õš # Prepend an empty string as list # (work-around when there are no valid suffices left) # i.e. [] → [""] # i.e. ["images/"] → ["","images/"] ¤ # Take the last suffix # i.e. ["","images/"] → "images/" X« # Append variable `X` (and implicitly output the result) # i.e. "images/" and "new1.png" → "images/new1.png" ``` [Answer] # [Powershell](https://docs.microsoft.com/en-us/powershell/scripting/powershell-scripting) 42 39 45 30 26 bytes Find the last decimal before a /, fetch all after the slash as the new path ``` ($args-split'.*\d.*?/')[1] ``` [Try it out!](https://tio.run/##K8gvTy0qzkjNyfn/X0MlsSi9WLe4ICezRF1PKyZFT8teX10z2jD2////6s5W@qHFQLX6XvkZefphmSmp@cX6kfmlIaVJqfrGLvqOeZm5iSWZ@XnF@qZGeiFFmcnZlXq@iXmppWUgXWUgDUbGJnoFeenqAA) - many bytes by tips from @mazzy - 1 byte by removing non-required regex escape - 4 bytes as the regex with -split didn't require a group - added greedy decimal search [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes ``` ->s{s=~/.*\d.*?\//;$'} ``` [Try it online!](https://tio.run/##ZY5BSwMxFITv/ooehIWCGbqtl0oV28WDsLCHWhDrIc2@rXFtEvKSShH96zFLT@JlZg4zH@Pj7pS6Rbq65S9e/ECMt60Y322Bm8viO7lR91Ks5nhi8oxa@qANKuI@WIelVH10D/qDGM1qAn2Q@xyVzFVDn8KZffF68Rcx6ASVVfFAJjCW1vYMOltTl2IGTx0ab99JhVEtTWYOVeHa7h/t0b4ZbHRLlvFs4zruCNMK9yZfCdoaxnUp1l6r/iQyiuJxWB2HQTmdnQ@m9As "Ruby – Try It Online") Same trick as Arnauld and everybody else after him. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 26 bytes ``` s->s.split(".*\\d.*?/")[1] ``` [Try it online!](https://tio.run/##bZBNSwMxEIbv/RXDQqFb1gz98FK1opYehEKhVRDtIe5ma7q7ScgklSL97TW7W3rRQzIZ8s7D8Oz4nl/tsuIkK6Otg13omXeyZLlXqZNasf5NJy05ESy4VPDTATD@s5QpkOMulL2WGVThr7dyVqrt@wa43VLcRAHmZ85t@5u0ZQo53J3oakqMTCldL2L9j4@M9e8xit8Hm9NNM3whOkGO4O7MBIieJvhCwhIuuHVS4UxQ4bTBR54W3sxlKQiXTwOUFd@GZ8pDVIlvZtQ2Sv5A6nuAM536SihH@Kh1QSjaslwM2RityHFp9U6kLphQgVpHmcnyf3jP@kvhq8yEJnzTfu0/BY5m@KDCOrUMwushW1uZFgcWYMLv66l9PTAcjZslG@ax1ZBre5bbiJi0OuKLjdWBnKiY9mGfkHJ5L@oGW1PoUldFSRNPIGfcmPLQq7s4bsnHTn2Op18 "Java (JDK 10) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 9 bytes ``` .*\d.*?/ ``` Regex is ported from [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/172191/52210), so make sure to upvote him! [Try it online.](https://tio.run/##XY8/iwIxEMV7P4W1RR7Z1cbmOF0shIUtVDi4JmZHL7eaWfJH8dPvJYge2swMzPzevOcoGKvkMIjJdysmHxgNw3KOrSfnUSuXtqjId4F7LJTuYr8yJ/JolhLmrI5p1CqdWrqK3h5HTzZXiYp1PJMNHgvmzoPurakLMYWjAxrHv6TDuFY2ieVT0beHf5k1/1jsTEvs8cVxE/eEssKnTc@DYesxK8TGGd3dRNKgeMnUJQNFOX219BqnfMtTvOeRD1pJqOzqDw) **Explanation:** ``` .*\d.*?/ # Main regex: .* # Zero or more characters (as much as possible) \d # Followed by a digit .*? # Followed by zero or more optional characters (as few as possible) / # Followed by a slash # Replace the match with: # Nothing (so basically remove that leading part) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”/ɓṣṖf€ØDTṀ‘ṫ@ṣj ``` A monadic Link accepting a list of characters which returns a list of characters. **[Try it online!](https://tio.run/##y0rNyan8//9Rw1z9k5Mf7lz8cOe0tEdNaw7PcAl5uLPhUcOMhztXOwDFs/7//@9spR9anFpUrO@bWFSSmafvklqcXZJfYKzvlJicXVrglpmTWqwf4Gykn5mbmA5kJicC1eallhvqFeSlAwA "Jelly – Try It Online")** ### How? ``` ”/ɓṣṖf€ØDTṀ‘ṫ@ṣj - Link: list of characters X ”/ - literal '/' character ɓ - start a new dyadic chain with swapped arguments - i.e. f(X,'/') ṣ - split (X) at ('/') Ṗ - pop (removes the rightmost) ØD - yield digit characters € - for each: (of the parts of X after the split & pop) f - filter keep (digit characters) T - truthy indices (1-indexed indices of parts containing any digit(s)) Ṁ - maximum (rightmost, zero if not found) ‘ - increment ṣ - split (X) at ('/') (...again) @ - with swapped arguments: ṫ - tail (the split X) from index (the incremented maximum...) j - join with ('/') ``` [Answer] # [Red](http://www.red-lang.org), 79 bytes ``` func[s][d: charset"0123456789"parse s[any[to d thru"/"]copy t to end(print t)]] ``` [Try it online!](https://tio.run/##VVDJTsMwEL33Kyyf4JIhacuSG23EASlShAoSinIw9qQxoWPLS1G@PjhwoZdZnuYtGodqfkHVdqu@nPtIsvVdq0omB@E8Bn6TF@vN9vbu/oHbBWG@FTS1wTDFwuAiB95JYycWWMKQ1JV1mtJy3XVzz/i@hFePzkMtXNAEFfoxGAs7Icdon/QXemj2OeiTOKZRJg8g/M4sHfnqP3@pOVRGxhNS8LAzZvSAf62pi2wDDntonPlEGVgtKAkup5lV/aXUsxkI3rRC4@HdxEP8QFhX8EgpRNCGPGyL7OC0HKcs6WA8L6zzQkjP@I02/wA "Red – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 74 bytes ``` r='';k=1 for c in input(): r+=c;k-=c.isdigit() if'/'==c:r*=k;k=1 print r ``` [Try it online!](https://tio.run/##TY5NT8MwDIbv@RVRL4UharUbl045sFUckCr1MJA4ltTtQlgc5WOwX1/ScQDJsi3rfR7ZXsKRTDVLGpALnmXZ7ESeb7Uo2UiOS65MKhvDzW3NuLsTcqvvhSyUH9Sk0pVxNeaQCyFrtxL6SlqnTOBuTjrG8BslX/yr9Zzta3jx6Dy0vQvKQINeB7Kw66WO9kl9ooduX4I69VNaZZ@iBr8Ka6aM/dFLL6EhGU9ogocdkfaAv6Nrq2IDDkfoHH2gDLztTdIt0cIO43/RMx0NvKoBycMbxUN8R1g38GjSA0GR8fBQFQenpL4UyYLxvFDnBajWm@tbPw "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 42 bytes ``` lambda n:re.sub(".*\d.*?/","",n) import re ``` [Try it online!](https://tio.run/##TY49a8MwFEV3/wqhyTZBj9jpEgilielQMHhIC4UssvycqI6fhD7S5te7dju0y7tvuOdw7T1cDBWTMh2yHeOcJ/3uNF3l2HaS0dah8LFNuchPncgfga84X1GW6NEaF5jDyTpNgfWpJhtDmmXJ4kjwCxVbpHk58cMWXj06D7V0QRNU6IdgLOylGqJ91lf00BzWoEd5nl8l5yrhp7B05skfvdw1VEbFESl42BszeMDfaOpCbMBhD40zH6gCqyXNuqUqbNf/F72YC8Gb7tB4eDfxGFuEsoInmgcEbcjDQyGOTqvhLmYLxttC3RagKDc/s74B "Python 2 – Try It Online") [Answer] ## Pyth, 14 bytes The same regex solution that everybody else is using: ``` :z"^.*\d.*?/"" : regex replace z in the input() string "^.*\d.*?/" the file path up until the last path with a number " with an empty string (Pyth terminates this string at end of program) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` a@`\d.*?/`$' ``` Takes input as a command-line argument. Verify all test cases: [Try it online!](https://tio.run/##VY5NawIxFEX3/opBCoVCc3HUjZu2OnRRGJiFLUgtmGaeNh3NC/mwiPS3pxnc1M27b3HP4Vpt0znJx826FXcP2Nzcpt@iLt4HxXAxw6sn51FLF7RBRb4LbDGXqov2We/Jo1mMoA9yl18lc9XQj7BmN/yP93eEilU8kAkec@bOgy7R1KWYwNEWjeNvUqGopcm@vipsu70yvfCXwZtuiT1WHJfxkzCu8GTyhKDZeExLsXRadSeRNRSPPXXsgXI8uQz7SOl@/wc "Pip – Try It Online") ### Explanation Does ***not*** use the same regex as everyone else! (Well, okay, it's pretty similar.) ``` a 1st command-line argument `\d.*?/` Regex matching a digit, as few characters as possible, and then a slash @ Find all matches $' Special variable: the portion of the string after the last match Autoprint ``` --- The shortest solutions using the standard regex were all 13 bytes: ``` aRM`.*\d.*?/` Remove a|>`.*\d.*?/` Left-strip aR`.*\d.*?/`x Replace with empty string ``` [Answer] ## Matlab, 68 bytes ``` function[r]=f(s),[~,b]=regexp(s,'/[^/;]+\d[^/;]+/');r=s(b+1:end);end ``` [Try it Online!](https://tio.run/##JY1BC4IwGEB/zjYUP9K6ODxEnYJuFoQZqPu0EW2yz0ld@usr6fLe6fFsNzUzhtB7003amsrVRc9JxNUnbuvC4YCvkVPMoLqBrKOr@huYkK4g3karHI0S8oegNI2852yXw4nQERzs3cBZK7QEF@tL3yJke9ga/WyWG8EmTUqnu8c7OTYG/bxU8xKk2ToZzcCEkOEL) [Answer] ## PHP 4 (42 chars) Given *$argv[1]*, it will [silence](https://www.php.net/manual/en/language.operators.errorcontrol.php) the [**end**](https://www.php.net/manual/en/function.end.php)'s “*Only variables should be [passed by reference](https://www.php.net/manual/en/language.references.pass.php)*” notice. ``` echo@end(preg_split(';\d.*?/;',$argv[1])); ``` [Answer] # C, ~~103~~ ~~100~~ 88 bytes ``` *a(b,l)char*b;{for(b+=l;!isdigit(*b);b--);for(;*b-47&&*b;b++);for(;*b-47;b--);return b;} ``` [Try online!](https://tio.run/##VY5NS8NAEIbP5lfEFkqSNhlaK4JRIUnxIBR6qILH3c0kXZPuhv2oSOlvj4mhWi8zwzPvPAwLS8baNiAendU@2xEV0PhYSOXR6WMdX3Od85IbL6B@TMPQj/tVHNBweTeZdFE6nV6yIaPQWCVcGp/acY4FF@gm7ii7h1eNSsOaKMMFrFBXRjaQElbZ5pnXqGGTzYHvSdmNjHRRgZ9RI8qRc/akF56@zmElmd2jMBpSKSsNOLTNehEtQWEBGyU/kBl3TUQn7qNRkxd/yuxC@SJ3At54jlLDu7RbSxFuVpCI7inDpdBwu4i2irPqK@p8aA/91aE/WNwsh1edMRestjm6D9ooLspo9@RC0M01igCcPeHC84/OVWON9oiXzIaVl/i@H//i9IzTfzg74@wHn9pv) -22 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) Note: the function may have undefined behavior if the string doesn't contain a number and a "/" character! ## Ungolfed version ``` *a(b,l)char*b; /* b:the string, l:the length of the string */ { for(b += l; !isdigit(*b); b--); /* start from the end of the string and decrement pointer until a number is found */ for(; *b-47 && *b; b++); /*increment pointer until '/' (ascii value 47) is found*/ for(; *b-47; b--); /* decrement pointer until '/' is found */ return b; } ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 13 bytes *12 bytes for code; +1 for -p switch* ``` s!.*\d.*?/!! ``` [Try it online!](https://tio.run/##VY5BawIxFITv/RXdq2AGV730UqqLB2FhD7Yg9JJmnxpX80JeYumfb8y2UOhl3hzmmzeewmWZs1Rq8t6ryTOqKuf1E16FgqDVIVqHhmSI7LHSZkh@Yy8k6NYz2Ks@Fmt0iTr6VN4dH/7YLZ8c3mxPLNhz2qUPwrzBiytUtOwEy1rtgjXDl2q1o3QbqdsI1PPF/65RZ2jYpCu5KFgxDwL6PV1bqwUCHdAFPpOJj6WuDBujyveHb/Y///LU3wE "Perl 5 – Try It Online") I solemnly swear I came up with my own solution before reading other answers. ]
[Question] [ Your program must accept as input six numbers, which describe a triangle - for example, the inputs 80, 23, 45, 1, 76, -2 describe a triangle with vertices (80, 23), (45, 1), and (76, -2). The input must be given as six plain real numbers or as a list of six real numbers, in the order given in the example. Your task is to figure out whether the triangle's vertices are given in clockwise order. Assume that the input vertices are not all in one line. In this case, the vertices are not in clockwise order because the second vertex is to the bottom-left of the first. This is code-golf, meaning the submission with the shortest number of bytes wins. Good luck! [Answer] # JavaScript (ES6), 38 bytes Returns a Boolean value (*true* for clockwise). ``` (a,b,c,d,e,f)=>a*d+b*e+c*f<b*c+a*f+d*e ``` [Try it online!](https://tio.run/##BcFLDsIwDAXAq3iZOK8VFPpZUO7iODYCVQ2iiOuHmZf85NDP8/3t9lqs@dqCIENRYPC43oVLymxJ2W@ZNQl7KmxN637UzfqtPoKH5QQaLqDrCDqD5gnUDTG2Pw "JavaScript (Node.js) – Try It Online") $$D=\begin{vmatrix} a&b&1\\ c&d&1\\ e&f&1 \end{vmatrix}=(ad-bc)-(af-be)+(cf-de)$$ $$D<0\iff ad+be+cf<bc+af+de$$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` s2;€1ÆḊṠ ``` [Try it online!](https://tio.run/##y0rNyan8/7/YyPpR0xrDw20Pd3Q93Lng////FgY6CkbGOgompjoKhjoK5mY6CrpGAA "Jelly – Try It Online") -2 bytes thanks to Bubbler by transposing the matrix from ngn's formula which saves bytes on padding with 1s, since determinant is invariant over transposition. Outputs `-1` for clockwise and `1` for counterclockwise. Stole ngn's formula [from chat](https://chat.stackexchange.com/transcript/message/58180608). ``` s2;€1ÆḊṠ Main Link; [x0, y0, x1, y1, x2, y2] s2 Slice into chunks of size 2; [[x0, y0], [x1, y1], [x2, y2]] ; Append... € to each chunk... 1 1; [[x0, y0, 1], [x1, y1, 1], [x2, y2, 1]] ÆḊ Determinant Ṡ Sign ``` [Answer] # [R](https://www.r-project.org/), ~~62~~ ~~44~~ 36 bytes *Edit: Realized that I'd ridiculously over-engineered my first version after looking at [Arnauld's answer](https://codegolf.stackexchange.com/a/226564/95126) which uses the same approach. Upvote that!* *Edit 2: And then I looked [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/226557/95126) (upvote that one, too!) realized that that strategy would be shorter anyway.* ``` function(p)det(rbind(matrix(p,2),1)) ``` [Try it online!](https://tio.run/##K/qfmFeSmZyTn5xdnlmcavs/rTQvuSQzP0@jQDMltUSjKCkzL0UjN7GkKLNCo0DHSFPHUFMTVY9GsoaFgY6CkbGOgompjoKhjoK5mY6CrpGmpoKyAopKLlz6IBqg@sH64Kr@AwA "R – Try It Online") Outputs a positive value for anticlockwise, and a negative value for clockwise. Add 2 bytes (`>0`) ([like this](https://tio.run/##K/qfmFeSmZyTn5xdnlmcavs/rTQvuSQzP0@jQDMltUSjKCkzL0UjN7GkKLNCo0DHSFPHUFPTzgBVl0ayhoWBjoKRsY6CiamOgqGOgrmZjoKukaamgrICikouXPogGqD6wfrgqv4DAA)) if you prefer to have a `TRUE`/`FALSE` output. [Answer] # [Factor](https://factorcode.org/) + `math.matrices.laplace`, 44 bytes ``` [ 2 group [ 1 suffix ] map determinant sgn ] ``` [Try it online!](https://tio.run/##JYw7DgIhFEV7V3E3IFH8RhdgbGyM1WQKgg8kMgw@INEY145Em1Pcm3OM0nnkejkfT4cdLI8lumCR6FEoaEq4EwfyGFS@/SAa2LVHeBW90oTIlPMrsgsZ@8kb2xnkAssV5tisMZX41A7y30bX1lSMcU/0rRdxpUw8uKCanWxAX7XyHqJ@AQ "Factor – Try It Online") Port of @hyper-neutrino's [Jelly answer](https://codegolf.stackexchange.com/a/226557/97916). [Answer] # [J](http://jsoftware.com/), 24 16 bytes ``` 0>1-/ .*@,.3 2$] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DewMdfUV9LQcdPSMFYxUYv9rcqUmZ@QrqLsl5hRXqkM4aQoWBgpGxgompgqGCuZmCvFGUEUhRaUlGeiqwAogamESYA6yrMJ/AA "J – Try It Online") -8 thanks to Bubbler for pointing out I could take a single determinant of a 3x3 to implement the shoelace formula Takes input as a single list. Looks like hyper-neutrino beat me to the idea, which is just to use the [shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula) and then check if the answer is negative. Since the shoelace formula expects the coordinates in counter-clockwise order, it will be negative only when they're in clockwise order. ## how Consider the input: ``` 80 23 45 1 76 _2 ``` * `3 2$]` Shape into matrix: ``` 80 23 45 1 76 _2 ``` * `1...,.` Zip with 1: ``` 1 80 23 1 45 1 1 76 _2 ``` * `-/ .*` Determinant: ``` 787 ``` * `0>` Is it negative? ``` 0 ``` [Answer] # MATLAB/Octave, 33 bytes ``` @(A)det([reshape(A,2,3);1,1,1])<0 ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQcNRMyW1RCO6KLU4I7EgVcNRx0jHWNPaUAcIYzVtDP4n5hVrRFsY6CgYGesomJjqKBjqKJib6SjoGsVq/gcA "Octave – Try It Online") Anonymous function. Takes as input list of points (so a vector in MATLAB's nomenclature). It reshapes it into 2x3 array, adds ones and calculates the determinant. The reshaped array with ones looks like so: $$ \begin{bmatrix} A(1) & A(3) & A(5) \\ A(2) & A(4) & A(6) \\ 1 & 1 & 1 \end{bmatrix}$$ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ≔⪪A²θ›⁰ΣEθקι⁰ΣE³×⊖맧θ⁺κ⊖λ¹ ``` [Try it online!](https://tio.run/##VY7LCsIwEEX3fkWWE5iC1id0VRCkC6FQd6WL0A4aTGObpOLfx9kE8cIwi3O43P6hXP9SJsbSe3230ExGB6jstASQKHK@WRar2mkb4OJIBXKwRtEsI1zVBDOKmx7JQxkqO9AHNIq1/PFt4mfqHY1kAw1gWEh@@lxUm8XDE8W/KlneyJQixrY98YCcm3d7RiiOBxRZ3nUxe5sv "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for clockwise, nothing if not. Explanation: ``` ≔⪪A²θ ``` Split the input into three pairs of coordinates. ``` ›⁰ΣEθקι⁰ΣE³×⊖맧θ⁺κ⊖λ¹ ``` Multiply each coordinate by each cyclically adjacent coordinate and its adjacency, i.e. $$ x\_0 (y\_{0+1} + 0y\_{0+0} - y\_{0-1}) + x\_1 (y\_{1+1} + 0y\_{1+0} - y\_{1-1}) + x\_2(y\_{2+1} + 0y\_{2+0} - y\_{2-1}) $$ and compare the sum to zero to see whether the vertices are clockwise. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` lambda a,b,c,d,e,f:a*d+b*e+c*f<b*c+a*f+d*e ``` [Try it online!](https://tio.run/##BcFJCoAwDAXQq2Sp6Re0jojexE06BAUnxI2nr@/d37tep006L2mXwwUhgYNHQISOwsE4jsazTo69EVYTOKb72c4302woQbYGNS2oAvUdqLB5nn4 "Python 2 – Try It Online") Port of Arnuald's JS answer. But unfortunately using dot product is longer, because `@` operator requires numpy. ]
[Question] [ Write a program that counts and prints the number of characters in it's own source code to standard output. The number must be generated from counting the characters. This Ruby solution would not be allowed: ``` puts 6 ``` because it is not calculated. Spaces, tabs, new lines, etc **should be counted**. The program must be smallest possible in any programming language. [Answer] # Bash, 10 Pretty boring, but: * Prints the code size in bytes, and nothing else. * Filename may contain spaces. Make sure that the file doesn't have a new line at the end! If it does, it will output `11`. ``` wc -c<"$0" ``` If the file doesn't have spaces in its name, you can get 8 characters: ``` wc -c<$0 ``` [Answer] # CJam / GolfScript - 11 CJam: ``` {`"_~"+,}_~ ``` GolfScript: ``` {`".~"+,}.~ ``` This actually generates its own source code (like a quine) and then calculates the string length. [Answer] # [PYG](https://gist.github.com/Synthetica9/9796173) (9, and actually calculated) Calculates the length of the source code (`Q`) with the builtin string length checker `len`, and prints (`P`) the result: ``` P(len(Q)) ``` [Answer] # Ruby, ~~30 22 20~~ 18 ``` p IO.read($0)=~/$/ ``` [Answer] # perl, 9 bytes No trailing newline. ``` print-s$0 ``` Running it looks like this: ``` $ echo -n 'print-s$0' >/tmp/foo.pl $ perl /tmp/foo.pl ; echo 9 ``` [Answer] # BASH (builtins only) - 18 ``` $ cat bash ; echo # no final newline in file a=`<$0` echo ${#a} $ ls -l bash -rwxr-xr-x 1 yeti yeti 18 18. Mai 07:11 bash $ ./bash 18 ``` [Answer] ## Fortran 78 ``` character*78::a;open(unit=9,file='c.f90');read(9,'(a78)')a;print*,len(a);end ``` File IO isn't the best in Fortran, so we have to waste space opening the file & then reading from it. Had I not specified the `a78` (78 characters), then it would stop at the comma next to `file` (silly [list-directed IO](http://www.adt.unipd.it/corsi/Bianco/www.pcc.qub.ac.uk/tec/courses/f90/stu-notes/F90_notesMIF_10.html)). [Answer] # HTML + Javascript (jQuery): 48 Save this script as `script.html` and open it with a browser. ``` <script>alert($('body').html().length)</script> ``` [Answer] # Python 31 Save the file as `'l'` ``` print len(file.read(file('l'))) ``` Outputs `34` [Answer] # Rebol, 40 ``` print length? read system/options/script ``` [Answer] # VIM - 43 Add this in your `.vimrc` file : ``` :echo strlen(join(readfile(".vimrc")),"\n") ``` But it will only work if you are in your home when executing vim. More generic solution `vim ~/.vimrc` (**46 chars**) : ``` :echo strlen(join(readfile(bufname("%")),"\n")) ``` [Answer] # PHP - 22 ``` <?=filesize(__FILE__); ``` [Answer] # Python 3, ~~28~~ 27 bytes I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the `.py` exension: ``` print(len(open("f.py").read())) ``` EDIT: The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out [Answer] ## JavaScript 78 ``` <script id="s"> function f(){document.write(document.getElementById("s").innerHTML.length);} </script> ``` [Answer] # J - 16 char J can `read($0)` itself too, you know! Not all that well, but... ``` echo#1!:1]1{ARGV ``` A more natural solution in the interpreter REPL, in which we do the normal quine thing and then take the length, costs **24 chars**: ``` #(,2#{:),~'#(,2#{:),~''' ``` `,~` appends the string to itself, `(,2#{:)` appends two copies of the trailing single quote, and `#` takes the length. [Answer] # [Extended BrainFuck](http://sylwester.no/ebf/): 12 ``` ,(>+<,)>55+. ``` Usage: ``` beef ebf.bf < cnt.ebf > cnt.bf beef cnt.bf < ent.ebf ``` Output: ``` C ``` Which is 12 in hex. If you add a linefeed in the file it will output a `D` for 13 so it's definitely counting the characters in the source. [Answer] **Hy** (38 characters): ``` (defmain [n] (print (.read (open n)))) ``` [Answer] # dc - 8 Not sure if this is allowed, but calculates the length of the macro(the part in the square brackets and adds 4(which is the length of the part outside the macro)). ``` [Z4+p]dx ``` [Answer] ## Lua: 42 ``` print(string.len(io.open('l',"r"):read())) ``` Pretty straight-forward, you must save the file as `l` and call it as `lua l`. [Answer] # K,13 ``` 1@$#,/0:.z.f; ``` / ``` $ q a.k -q 13 ``` [Answer] # Python 3: 33 or 37 ``` print(len(open(__file__).read())) print(len(open(__file__,'b').read())) ``` First if you only count the characters, second if you want to count the number of bytes. [Answer] ## JavaScript (Node.js) - 60 ``` console.log(require('fs').readFileSync(__filename).length); ``` [Answer] # Java, 157 characters Since nobody has done Java yet... ``` public class A{public static void main(String[]a) throws Exception{System.out.print(new java.util.Scanner(new java.io.File("A.java")).nextLine().length());}} ``` [Answer] ## PHP - 44 Save this as `c` ``` <?$f=fopen("c","r");echo strlen(fgets($f)); ``` [Answer] ## JavaScript **42 - ES5** ``` (function a(){alert((a+"()()").length)})() ``` **37 - ES6** ``` (a=x=>{alert((a+"(a=)()").length)})() ``` [Answer] # Javascript (pure - no HTML nor JQuery) 41 bytes ``` function f() {alert((f+"f()").length)}f() ``` [Answer] ## awk, 13 bytes ``` $0=length($0) ``` Write it to a program file `program.awk` and ``` $ awk -f program.awk program.awk 13 ``` [Answer] # RProgN, 3 bytes. ``` Q L ``` Simply, Q is the function that pushes the source code to the stack, and L is the function that gets the length of the string on top of the stack. The stack is then implicitly printed. [Try it online!](https://tio.run/nexus/rprogn#@x@o4PP/PwA "RProgN – TIO Nexus") [Answer] # [Dyalog APL](https://dyalog.com), 8 bytes The niladic function `f`: ``` ≢∊⎕NR'f' ``` Notice that this prints 10 because APL counts (and stores) the function header (name + newline). However, PPCG practice is not to count this header. The entire program can be displayed with ``` ↑⎕NR'f' ``` Giving: ``` f ≢∊⎕NR'f' ``` --- `⎕NR'f'` the **N**ested (i.e. a list of character lists) **R**epresentation of `f` `∊` **ϵ**nlist (flatten) `≢` tally ]
[Question] [ **This question already has answers here**: [Cartesian product of a list with itself n times](/questions/165664/cartesian-product-of-a-list-with-itself-n-times) (25 answers) Closed 5 years ago. Question: Print out all the coordinates of a NxN grid. Preferably in C, however other languages also accepted **Input**: N (integer) **Output**: for N=3, a 3x3 grid: ``` 0,0 1,0 2,0 0,1 1,1 2,1 0,2 1,2 2,2 ``` [Answer] # Japt, 3 bytes ``` o ï ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=byDv&input=MwotUQ==) ``` o :Range [0,input) ï :Cartesian product with itself ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ 51 bytes Saved 32 bytes and fixed output order thanks to Kevin Cruijssen. ``` i;f(n){for(i=0;i<n*n;)printf("%d,%d\n",i++%n,i/n);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jT7M6Lb9II9PWwDrTJk8rz1qzoCgzryRNQ0k1RUc1JSZPSSdTW1s1TydTP0/TuvZ/bmJmngZQj4YxiAcA "C (gcc) – Try It Online") I'm by no means a C programmer (or C golfer), but I thought I'd give it a try. Should the main be included in the byte count? [Answer] # [R](https://www.r-project.org/), ~~33~~ 25 bytes ``` which(diag(scan())|1,T)-1 ``` [Try it online!](https://tio.run/##K/r/vzwjMzlDIyUzMV2jODkxT0NTs8ZQJ0RT1/C/8X8A "R – Try It Online") Thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) for suggesting a 2-byte golf, which inspired me to look further :-) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~48~~ 42 bytes ``` param($n)0..--$n|%{$i=$_;0..$n|%{"$i,$_"}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVP00BPT1dXJa9GtVol01Yl3hrIB/OUVDJ1VOKVamv///9vDAA "PowerShell – Try It Online") Boring double-for loop. *Saved 6 bytes thanks to mazzy.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L<ãí',ý» ``` Exactly as the challenge description: prints the 0-indexed coordinates ordered by y-then-x comma- and newline-delimited to STDOUT. [Try it online.](https://tio.run/##yy9OTMpM/f/fx@bw4sNr1XUO7z20@/9/YwA) **Explanation:** ``` L # Create a list in the range [1, (implicit) input] # i.e. 3 → [1,2,3] < # Decrease each by 1 to make the range [0, input) # i.e. [1,2,3] → [0,1,2] ã # Create each possible pair with itself # i.e. [0,1,2] → [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]] í # Reverse each pair so they're sorted by y-then-x instead of x-then-y # i.e. [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]] # → [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]] ',ý '# Join each pair with a space delimiter # i.e. [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]] # → ["0,0","1,0","2,0","0,1","1,1","2,1","0,2","1,2","2,2"] » # And then join everything with a newline delimiter (and output implicitly) # i.e. ["0,0","1,0","2,0","0,1","1,1","2,1","0,2","1,2","2,2"] # → "0,0\n1,0\n2,0\n0,1\n1,1\n2,1\n0,2\n1,2\n2,2" ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Lã ``` Returns a list of 1-indexed coordinates ordered by x-then-y. [Try it online.](https://tio.run/##yy9OTMpM/f/f5/Di//@NAQ) **Explanation:** ``` L # Create a list in the range [1, (implicit) input] # i.e. 3 → [1,2,3] ã # Create each possible pair with itself (and output implicitly) # i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] ``` [Answer] # C#, 59, 65 First time posting. Apologies if I do something wrong! `l=>{for(int j=0;j<l*l;)System.Console.Write($"{j%l},{j++/l}\n");}` [Try it online!](https://tio.run/##LY2xCsIwGIT3PsVPUUisVsExbUGcBcHBxSXGtCT8TSSJgoQ8e2zF6Y77jjvhN8I6mQVy7@Hs7OD4GAuA5@uOSoAPPEzytuoBJ64MoTMEuHx8kGN9EEFZ0ygTOuihzdh2sbeOTAHodsd0gytk9N8@WuMtyvrqVJBkUUa9xLSOuqq2mG6mpCzleZz9Lnqyp7NLRcpf) -per Kevin Crujissen's TIO Link. [Answer] # [Tcl](http://tcl.tk/), 70 bytes ``` proc C {n i\ 0} {time {set j 0 time {puts $i,$j incr j} $n incr i} $n} ``` [Try it online!](https://tio.run/##NYs7CoAwEAX7PcVDUloE9AZeI40Eiw1xDSaCEPbs8YfdzGNe8bG1tG8eE6qAHayiFl4X1LwUBFj6LB0lw3BvArH4HUFh5EN@UFtc5wRBpYFG0v8h7ry76Ynfoeu0XQ "Tcl – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda n:[(i%n,i/n)for i in range(n*n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojUzVPJ1M/TzMtv0ghUyEzT6EoMS89VSNPK08z9n9BUWZeiUKahrEmF5jJBRMw1fwPAA "Python 2 – Try It Online") [Answer] # Pyth, 4 bytes ``` ^UQ2 ``` Full program. Outputs list of coordinate pairs. ``` ^UQ2 Implicit: Q=eval(input()) UQ [0-Q) ^ 2 Take the cartesian product of the previous result with itself ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes ``` r■ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7/o0bQF//8b/wcA "MathGolf – Try It Online") ## Explanation ``` r Range(0, n) ■ Cartesian product with self for lists ``` For pretty-printing, you could add `n` to have it print one list item per line. [Answer] # APL+WIN, 11 bytes ``` (⍳n)∘.,⍳n←⎕ ``` Index origin = 0. Prompts for input for n and outputs the following for n=4: ``` 0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3 ``` [Answer] # [Pepe](https://github.com/soaku/pepe), 88 bytes I've never done 2D iterating in Pepe before and it doesn't seem to work pretty well due to labels being dynamic. There's quite a lot of two byte commands to avoid moving the pointer. ``` REREeErEErerErEReREErEEEErreEEreeeEeEEeerEEeerreEErEEEEEreeEReererEEEEErERRREEEEEeRrEree ``` [Try it online!](https://soaku.github.io/Pepe/#&RE$__.F!q@MUw!k@M-iI/$-i_--&1-_*) **Warning:** Do not run it with input below 1 - it will kill your browser. [Answer] # [Perl 5](https://www.perl.org/) `-na`, 35 bytes ``` map{//;say"$',$_"for 0..$F[0]}0..$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBaX9@6OLFSSUVdRyVeKS2/SMFAT0/FLdogthbEiP//3/hffkFJZn5e8X/dvMT/ur6megaGBgA "Perl 5 – Try It Online") [Answer] # Powershell, 43 bytes ``` param($n)$i--..--$n*++$n|%{$i+=!$_;"$i,$_"} ``` Explanation: One row `0..$n-1` repeated `$n` times. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 35 ``` eval echo {0..$[$1-1]},{0..$[$1-1]} ``` [Try it online!](https://tio.run/##S0oszvhfnFqioKurYPw/tSwxRyE1OSNfodpAT08lWsVQ1zC2VgeZ8/8/AA "Bash – Try It Online") [Answer] # [Lua](https://www.lua.org), 63 bytes ``` s=io.read()-1 for i=0,s do for j=0,s do print(i..','..j)end end ``` [Try it online!](https://tio.run/##yylN/P@/2DYzX68oNTFFQzPL1kAhLb9IIdPWQKdY11AhJR/MBQrrGIE4BUWZeSUamXp66jrqenpZmql5KQpA/P@/MQA "Lua – Try It Online") [Answer] # Perl5, ~~42~~ 38 bytes ``` for$i(0..--$n){for(0..$n){say"$i,$_"}} ``` (The inner loop saves a few bytes by using the implicit variable "$\_" as an index.) ]
[Question] [ # Task Take the (integer) number of human years that the dog has lived, \$n\$, as input and return its age in dog years, \$d\$, to two decimal places. The number of human years, \$n\$, will be between \$1\$ and \$122\$ inclusive: \$n \in [1,122], n \in \Bbb{N}\$. According to [BBC's Science Focus Magazine](https://www.sciencefocus.com/news/new-trick-to-calculate-your-old-dogs-age/), the correct function for determining your dog's age is: $$ n = 16 \times \ln(d) + 31 $$ Where *\$n\$ is the age in human years* *\$d\$ is the age in dog years* # Rules The final output in dog years must be a decimal, **rounded to 2 decimal places.** [Answer] # [Io](http://iolanguage.org/), 114 bytes While you all are enjoying rounding built-ins in your language, Io doesn't have any of those convenient rounding built-ins... ``` method(x,I :=((((x-31)/16)exp*100)round asString);I=if(I size<3,"0","").. I;I asMutable atInsertSeq(I size-2,".")) ``` [Try it online!](https://tio.run/##RcyxDsIgFIXh3ae4YeIaitAmDtY@AINTV5eagpJUqEAT4ssjJiae7Uv@HOuLgdMA1/LU6eFnmpmqpnW56SQe5BF1XvdSCAx@czNMcUzBujv2arCGKoj2rc8dI4IwQpBzUL2q1WVL023RMCXlog5p1K9f3LSMcIJYDJUtwlrf0uJ2X/1ZPg "Io – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~36~~ 31 bytes ``` printf"%.2f",1.0644944**($_-31) ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1JVc8oTUnHUM/AzMTE0sRES0tDJV7X2FDz/39To3/5BSWZ@XnF/3XzAA "Perl 5 – Try It Online") Command line one-liner examples: ``` echo 52 | perl -ne 'printf"%.2f\n",2.71828**(($_-31)/16)' echo 52 | perl -ne 'printf"%.2f\n",1.06449445**($_-31)' echo 52 | perl -ne 'printf"%.2f",1.06449445**($_-31)' echo 52 | perl -ne 'printf"%.2f",1.0644944**($_-31)' for a in {1..122};do echo "Man: $a Dog: "`echo $a|perl -ne'printf"%.2f\n",1.0644944**($_-31)'`;done ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-pag) ``` _31÷⁴Æeær2 ``` A monadic Link accepting a float which yields a float. (As a full program a decimal input causes the result to be printed.) **[Try it online!](https://tio.run/##y0rNyan8/z/e2PDw9keNWw63pR5eVmT0//9/EwMA "Jelly – Try It Online")** ### How? ``` _31÷⁴Æeær2 - Link: float, n 31 - 31 _ - subtract -> n-31 ⁴ - 16 ÷ - divide -> (n-31)/16 Æe - exp(x) -> exp((n-31)/16) 2 - 2 ær - round to 10^(-y) -> round(exp((n-31)/16), 2) ``` [Answer] # [Orst](https://github.com/cairdcoinheringaahing/Orst-Geo), 9 [bytes](https://github.com/cairdcoinheringaahing/Orst-Geo/wiki/Code-Page) ``` 31FᎽGć2Š ``` [Try it online!](https://tio.run/##yy8qLvn/39jQ7WHfXvcj7UZHF/y/0Pn/v4nBv/yCksz8vOL/ujkA "Orst – Try It Online") As bytes, this is ``` F3 F1 1B FF 30 1C 64 F2 42 ``` Or, encoded as UTF-8, ``` óñÿ0 dòB ``` which can be run by omitting the `-u` flag (filled by default on TIO). Note the not shown `0x1b` and `0x1c` bytes ## How it works ``` 31FᎽGć2Š - Full program. n is pushed to the stack 31 - Push 31 F - Subtract; n-31 Ꮍ - Push 16 G - Divide; (n-31)÷16 ć - Exp; exp((n-31)÷16) 2Š - Round to 2 decimal places ``` [Answer] # APL+WIN, 13 bytes Prompts for input of n: ``` ⍎2⍕*(⎕-31)÷16 ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6u0zetQ7VUsDKK5rbKh5eLuh2X@gzP80LkMjIy4uAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Integral](https://github.com/nph278/integral), ~~14~~ 11 Bytes My first Integral answer! ``` x▼◄w‼5*↕u*‼ ``` [Try it!](https://a-ee.github.io/integral/?code=eB8RdxM1KhJ1KhM&input=MTI) An alternative: [`▲w‼!◄5*↕u*‼` (11 bytes)](https://a-ee.github.io/integral/?code=HncTIRE1KhJ1KhM&input=ICAgICAgICA) ## Explanation ``` x Push 32 ▼ x-1 ◄ Subtraction w Push 16 ‼ Divide 5 e ^ a * 100 ↕ Multiplicaiton u Round to the closest integer * 100 ‼ Division ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 23 bytes ``` 31-16/W∆ehS\.€ḣh2wi\.$W ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=31-16%2FW%E2%88%86ehS%5C.%E2%82%AC%E1%B8%A3h2wi%5C.%24W&inputs=40&header=&footer=) From this answer two stupid features of Vyxal: * Why \$ln(x)^{-1}\$ needs to take a list instead of digit? * Seriously it cannot round a digit to n decimal places, so that part is handrolled. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~33~~ 32 bytes ``` a=>Math.exp(-~a/16-2).toFixed(2) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/0dbON7EkQy@1okBDty5R39BM10hTryTfLbMiNUXDSPO/dXJ@XnF@TqpeTn66RpqGoZGmpvV/AA "JavaScript (V8) – Try It Online") ***Thanks to @my pronoun is monicareinstate for -1 byte*** [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 24 bytes ``` :b$)/100 :R100*x_+$/16-2 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/3ypJRVPf0MCAyyoISGpVxGur6Bua6Rr9/29sCAA "cQuents – Try It Online") For some reason, rounding works on the whole line. I would do `/100/R100*`, but floats went all `9`y on me. [Answer] # [R](https://www.r-project.org/), 28 bytes ``` round(exp((scan()-31)/16),2) ``` [Try it online!](https://tio.run/##K/r/vyi/NC9FI7WiQEOjODkxT0NT19hQU9/QTFPHSPO/IZepEZehkeF/AA "R – Try It Online") There seems to be some controversy about whether trailing zeros must be printed. If so, the following 35 byte solution works: ``` sprintf("%.2f",exp((scan()-31)/16)) ``` [Answer] # [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 40 bytes ``` scale=2 define f(n){return e((n-31)/16)} ``` [Try it online!](https://tio.run/##S0r@/784OTEn1daIKyU1LTMvVSFNI0@zuii1pLQoTyFVQyNP19hQU9/QTLP2f5qGoZEm1/9/@QUlmfl5xf91cwA "bc – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~35~~ ~~44~~ ~~38~~ 36 bytes Saved a byte thanks to [my pronoun is monicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate)!!! Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Added 10 bytes to fix a bug kindly pointed out by [Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s). ``` f(n){printf("%.2f",exp(-~n/16.-2));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqAoM68kTUNJVc8oTUkntaJAQ7cuT9/QTE/XSFPTuvZ/bmJmnoamQjWXAgikaRgaaVpz1f7/l5yWk5he/F83JxcA "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) -1 byte thanks to @Shaggy ``` Me°U/G-2 x2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TWWwVS9HLTIgeDI&input=MTI) ## Explanation ``` Me°U/G-2 x2 Me // exp( °U // (U + 1) /G-2 // / 16 - 2 // ) x2 // round to 2 decimal digits ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~52~~ ~~36~~ 35 bytes Saved a whopping ~~16~~ 17 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!! ``` lambda n:round(1.0644944**(n-31),2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqii/NC9Fw1DPwMzExNLEREtLI0/X2FBTx0jzf0FRZl6JRpqGoZGm5n8A "Python 3 – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 19 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` T-☻/e▬♪*i♂‼/%5≥+♀∩* ``` If only MathGolf had a round builtin.. :/ 6 bytes are used for the actual formula, 13 for rounding to 2 decimals, haha. I/O both as a float. [Try it online.](https://tio.run/##y00syUjPz0n7/z9E99GM3fqpj6ateTRzlVbmo5lNjxr26KuaPupcqv1oZsOjjpVa//8b6BlwGYIwiGECIkzBQgZg0shIzwAA) **Explanation:** ``` T- # Subtract 31 from the (implicit) input-float # i.e. 50.0 → 19.0 ☻/ # Divide it by 16 # → 1.1875 e▬ # Push 2.718281828459045 to the power this value # → 3.2788737679386735 ♪* # Multiply it by 1000 # → 3278.8737679386735 i # Convert it to an integer, truncating the decimal values # → 3278 ♂ # Push 10 ‼ # Apply the following two commands separated to the stack: / # Integer-division % # Modulo # → 327 and 8 5≥ # Check if the modulo-10 result (the last digit) is >= 5 # (1 if truthy; 0 if falsey) # → 327 and 1 + # Add that to the division-by-10 result # → 328 ♀∩ # Push 1/100 * # Multiply that to the integer # → 3.28 # (note: `♀/` cannot be used, because it would act as integer division) # (after which the entire stack is output implicitly as result) ``` [Answer] # [Rust](https://www.rust-lang.org/), 38 bytes ``` |n|print!("{:.2}",((n-31.)/16.).exp()) ``` [Try it online](https://tio.run/##RY3BCoMwEETv@YrR0y5oirb0oNWj/yHUUKHdSkxpQfPtaRRKT8Mwu@/Z1@yCETz6UYixKMANs6OwyjrZUVxC6VLp0qcZkeTHQvOhOGvWw2ci5gBwrbxSEbH9XbqWTIWO1fs22CHSutiEzPnEyFsQq01hnhaCUVBo3RRluXuBn1DQYPEZrjHTDBIV22xI0M/YWPX//i4J7d0rH74) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ﹪%.2fX¹·⁰⁶⁴⁴⁹⁴⁴⁵⁻N³¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3P6U0J19DSVXPKE1JRyEgvzy1SMNQz8DMxMTSxMRUR8E3M6@0WMMzr6C0xK80Nwkoq6mjYGyoCQTW//@bmP/XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Numeric constant stolen from @JonathanAllan. Explanation: ``` N Input as a number ⁻ ³¹ Subtract literal 31 X¹·⁰⁶⁴⁴⁹⁴⁴⁵ Raise literal 1.06449445 to that power ﹪%.2f Format using literal format string `%.2f` Implicitly print ``` [Answer] # Zsh, 50 bytes ``` zmodload zsh/mathfunc printf %.2f $[16*log($1)+31] ``` [Try it Online!](https://tio.run/##VYw9b4MwFEV3/4onQSWTyhgb0qgRUqZ269KMEQOyzYdqMMJGBKL8dho6pGJ590nn3jPbapETDm7L3BipTS5hthVtclcVQytQ19etK@Al5AX4F/a206bEPgteY5YtXpqm/g1/BT7GGxQE3i48ne5IicqgO5ITMABPXTslHMQRHKFTPVxYtqLkH@35FjH@RIfnimcIefD98Xl@xKMIlXOdPVI6jmNoRa1aoQojBhsK09BWjXY9xPW1@CHOEJFrMejcKTKZoSdGSyJNaUleKroa@dYolNZ/pvUhdrJONZYWg9ZOXR098yTak@TAOOZREEc8isn78gs) Gives "dog years" per the **original** refs and examples. For example, the "[ScienceFocus](https://www.sciencefocus.com/news/new-trick-to-calculate-your-old-dogs-age/)" article gives 2 examples, and the "[Cell Systems](https://www.cell.com/cell-systems/fulltext/S2405-4712(20)30203-9)" paper gives 1 example, as tabulated: **`dog age | equivalent human age`** **`actual years | approx. "dog years"`** `1 | ~30` `4 | ~52` `12 | ~70` Do programmers ever read requirements? [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` >16/Ížrsm2.ò ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fztBM/3Dv0X1FxblGeoc3/f9vaGQEAA "05AB1E – Try It Online") ``` >16/Ížrsm2.ò # full program .ò # round... žr # 2.718281828459045... sm # to the power of... # implicit input... > # plus 1... / # divided by... 16 # literal... Í # minus 2... .ò # to... 2 # literal... .ò # decimal places # implicit output ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6576/edit). Closed 3 years ago. [Improve this question](/posts/6576/edit) A basket is full with \$n\$ colored balls. For each color except one, there are at least 2 balls with that color. Find the color which only has one ball. in \$O(n)\$ space complexity. What if each ball is repeated exactly twice? You can consider the input to be an array or a list or any container of colors as strings with a maximum length of 100 This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. [Answer] # Python - 17 chars Solely as an expression: ``` min(B,key=B.count) ``` Full, standalone program with input and output, **34 chars**: ``` B=input() print min(B,key=B.count) ``` edit: What gnibbler said. [Answer] # K, 17 15 ``` &1=#:'=" "\:0:0 ``` Takes input from stdin as a space separated list ``` k)&1=#:'=" "\:0:0 red red green blue blue "green" ``` [Answer] ## J, 31 24 20 characters ``` {.(~./:#/.~);:1!:1[1 ``` A lot prettier than the previous attempt. Takes input from keyboard. Makes an assumption that wasn't necessary in the previous version - that there is exactly one colour with one ball. If there are 2 colours with one ball you'll get the first that appears in the list, if there are no colours with only one ball you'll get the colour with the least balls. Example: ``` {.(~./:#/.~);:1!:1[1 green green red blue blue ┌───┐ │red│ └───┘ ``` [Answer] # SQL - 44 ### Find Unique Color ``` SELECT C FROM B GROUP BY C HAVING COUNT(C)=1 ``` ### Find Duplicate Colors ``` SELECT C FROM B GROUP BY C HAVING COUNT(C)>1 ``` [Answer] ### Python 2.7, 44 chars Using the same sort of format as Keith Randall's [answer](https://codegolf.stackexchange.com/a/6584/62) of a function that takes an array and returns the element/colour that only occurs once. ``` R=lambda B:[a for a in B if B.count(a)<2][0] ``` Alternatively, if I need to read in colours from the command line and output the colour that is unique (which takes 60 chars): ``` B=raw_input().split();print[a for a in B if B.count(a)<2][0] ``` [Answer] # Clojure - 44 ``` #(some(fn[[c n]](if(= n 1)c))(frequencies%)) ``` That's a lambda function. Example: ``` (#(some(fn[[c n]](if(= n 1)c))(frequencies%)) [:red :red :red :blue :green :blue :yellow :yellow]) => :green ``` [Answer] # Mathematica 23 `n` contains the list. ``` Cases[Tally@n,{x_,1}:>x] ``` [Answer] # GolfScript, 23 After a tremendous amount of help from [w0lf](https://codegolf.stackexchange.com/users/3527/w0lf), here's the source code. ``` ' '/:x.&{x{1$=},,1=\;}, ``` **[DEMO](http://golfscript.apphb.com/?c=OydibHVlIGJsdWUgeWVsbG93JwonICcvOnguJnt4ezEkPX0sLDE9XDt9LA%3D%3D)** --- ## 28 characters with the error checking `?` is displayed if there is not one unique color. For the sake of keeping the number of characters down to a minimum, the question mark was used (this of course can be changed to something more meaningful). ``` ' '/:x.&{x{1$=},,1=\;},'?'or ``` **[DEMO](http://golfscript.apphb.com/?c=OydibHVlIGJsdWUgeWVsbG93IHllbGxvdycKJyAnLzp4LiZ7eHsxJD19LCwxPVw7fSwnPydvcg%3D%3D)** --- ### Commentary ``` ' '/:x # split up each element and assign it to 'x' .& # copy the last element in the stack and do a "setwise and" {x # start filtration process and invoke 'x' {1$=} # checks for an equality comparison ,, # find the count of each unique character 1= # compare value to '1' \; # leave only value that has count of '1' on the stack }, # close filtration process and print element on stack '?'or # OPTIONAL: is printed if no element with a count of '1' is found ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` .m ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fL/f//2il9KLU1DwlHQUEoyg1BUQl5ZSmwulYAA "05AB1E – Try It Online") .m is a builtin function which return the least frequent element in a list. If you are not allowed to use a builtin to solve the challenge, then it's ~~4~~ 2 bytes: -2 thanks to @caird coinheringaahing ``` ʒ¢ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//1KRDi/7/j1ZKL0pNzVPSUUAwilJTQFRSTmkqnI4FAA "05AB1E – Try It Online") [Answer] ## Python 2.7, 67 chars ``` from collections import* R=lambda B:Counter(B).most_common()[-1][0] ``` [Answer] # R - 18 chars ``` which(table(x)==1) ``` [Answer] ## APL (14) ``` B/⍨1=+/B∘.≡B←⎕ ``` Takes input from the keyboard in the form of an APL list, so you need to put quotes around the colors `'like' 'this'`. (Or use numbers.) ``` B/⍨1=+/B∘.≡B←⎕ ⎕: 'green' 'green' 'red' 'blue' 'blue' red ``` As a function (that takes a list, also 14 characters): ``` {⍵/⍨1=+/⍵∘.≡⍵} ``` [Answer] ## Groovy - 22 chars ``` it.min{a->it.count(a)} ``` Attribution and test case: ``` lone={it.min{a->it.count(a)}} l = ['red','green', 'red', 'blue', 'green'] assert lone(l) == 'blue' assert lone(l) != 'red' ``` ]
[Question] [ # Through the bases In this challenge, you will be taking a number through all the bases of the rainbow Given an input, `n`, you will output `n` in every base from 9 to 2, and back up to 9. That's `9 8 7 6 5 4 3 2 3 4 5 6 7 8 9`. **Example:** ``` >>> 16 17 20 22 24 31 100 121 10000 121 100 31 24 22 20 17 ``` **Rules:** * You input can be a string or a number. * Your output may be separated by new lines, spaces, commas, or tabs. * You may use built in functions. * Shortest code wins! [Answer] # CJam, 14 bytes ``` riF,f{7-z2+bN} ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=riF%2Cf%7B7-z2%2BbN%7D&input=16). ### How it works ``` ri e# Read an integer I from STDIN. F, e# Push [0 ... 14]. f{ } e# For each B in that range, push I and B; then: 7-z2+ e# Compute abs(B - 7) + 2. e# This maps [0 ... 14] to [9 ... 2 ... 9]. b e# Perform base conversion. N e# Push a linefeed. ``` [Answer] # Pyth, 14 bytes ``` V+_Jr2TtJjkjQN ``` Needs more work, most code is spent generating 9..2..9. [Answer] # Pyth, ~~18~~ ~~15~~ 14 bytes Saved 3 bytes thanks to Dennis and 1 thanks to Jakube! ``` V+r9 1r3TjkjQN ``` Explanation: ``` V For N in +r9 1r3T the list [9,8,...3,2,3,...,8,9], jQN convert the input to base N (returns a list), jk join the list into a string, implicitly printed. ``` [Try it online](https://pyth.herokuapp.com/?code=V%2Br9+1r3TjkjQN&input=5&debug=0). [Answer] ## Haskell, 59 ``` 0%_=0 k%b=div k b%b*10+mod k b g n=map(n%)$[9,8..3]++[2..9] ``` First, recursively defines a binary operator `%` to do base conversion, representing the output as a decimal number rather than a string. The function `g` converts the input `n` to each base from 9 to 2 and back up. There's probably a shorter approach, advice is welcome. Saved 2 chars on parens thanks to nimi. [Answer] # Julia, 43 bytes ``` n->for i=[9:-1:2,3:9] println(base(i,n))end ``` This creates an unnamed function that accepts and integer and prints to STDOUT on separate lines. The `base` function takes two integers: a base (`i`) and a number (`n`) and returns the string representation of the number in the given base. Here we just loop through the required bases and print. [Answer] # Bash + dc, 27 ``` echo {{9..2},{3..9}}o$1p|dc ``` [Answer] ## JavaScript (ES6), 57 bytes ``` f=n=>[...`987654323456789`].map(v=>n.toString(v)).join` ` ``` ## CoffeeScript, 57 bytes Different approach: ``` f=(n)->[-7..7].map((v)->n.toString 2+Math.abs v).join ' ' ``` ## JavaScript (ES5), 97 bytes ``` function f(n){return'987654323456789'.split('').map(function(v){return n.toString(v)}).join(' ')} ``` ### Demo ``` function f(n) { return '987654323456789'.split('').map(function(v) { return n.toString(v) }).join(' ') } document.body.innerHTML = f(16) ``` [Answer] ## Python 2, 79 ``` g=lambda b,k=input():k and g(b,k/b)*10+k%b c=7;exec"print g(abs(c)+2);c-=1;"*15 ``` The function `g` converts a number `k` to a base `b`. We can take `k` as the program input because Python initializes default arguments when the function is defined, not each time it's called. We get the desired sequence of bases by taking the range `[-7, -6, ..., 6, 7]`, taking the absolute value, and adding 2. [Answer] # Pip, 14 = 13 + 1 bytes Uses the `-n` flag. ``` aTB2+AB(-7,8) ``` [GitHub repository for Pip](http://github.com/dloscutoff/pip) Takes the number as a command-line argument. ``` -7,8 Range containing integers from -7 through 7 AB( ) Absolute value of each 2+ Add 2 to each aTB Convert command-line arg to each base Print resulting list, newline-separated (-n flag) ``` It's amazing how all the golfing languages are getting the same score here. [Answer] ## JavaScript (ES5), ~~69~~ ~~66~~ 65 bytes ``` function f(o){for(i=15;i--;)console.log(o.toString(i>7?i-5:9-i))} ``` [Answer] # JavaScript SpiderMonkey 31 (1.8), 47 bytes ``` n=>[for(i of`987654323456789`)n.toString(i)]+'' ``` It doesn't get simpler than this. [Answer] # APL, 52 bytes I'll admit, this could use more golfing. ``` {n←⍵⋄⊃{⍺,' ',⍵}/{⊃,/⍕¨(~∧\0=e)/e←(10⍴⍵)⊤n}¨2+|8-⍨⍳15} ``` it is limited to at most 10 digits output suggestions for improvement welcome output for 16 looks like ``` 17 20 22 24 31 100 121 10000 121 100 31 24 22 20 17 ``` [Answer] ## Ruby, 44 bytes ``` a=->n{(0..14).map{|j|p n.to_s((j-7).abs+2)}} ``` Call the lambda with `a.call(number)`. This prints out with quotes around each line because `p` is shorter than `puts`. I'm assuming this is allowed. ]
[Question] [ Implement an integer parser in the shortest code possible, with the following restrictions: 1. The function or program can only take one argument: a string (or equivalent). Assume it to be signed and always valid (don't worry about decimals, etc.). The input may optionally omit the sign, in which it is assumed to be positive. 2. The function or program must output an integer (or equivalent). 3. No pattern matching, regular expressions, etc. are allowed. This includes utilities such as `tr` for \*nix. 4. No string parsing utilities are permitted, even from the standard library. This includes, but is not limited to, `parseInt()` from JavaScript, `int()` in Python, and `Int32.parse()` from VBScript. 5. The only permitted predefined string manipulation functions, methods, etc. fall into one of the following categories: * extract a substring (e.g. `substr()`, `slice()`) * get code point from character, vice versa (e.g. `toCodePoint()`, `fromCodePoint()`) * concatenate strings (e.g. `append()`, `concat()`, `strcpy()`) 6. No external libraries are permitted. 7. No string parsing utilities are permitted, even from the standard library. 8. Implicit conversion to string is disallowed (e.g. `1+''` in JavaScript) Shortest code wins, so happy golfing! **EDIT:** Sorry for the confusion, but implicit conversion is also disallowed. [Answer] # Python 3 (68) ``` s=input() n=s<'0' t=0 for c in s[n:]:t=t*10+ord(c)-48 print(t-t*2*n) ``` The Boolean `n` remembers whether the string started with a minus sign by using the lexicographic string ordering, in which `'-'` is less then the lowest digit `'0'`. The expression `s[n:]` casts n to a number (0 or 1), skipping the minus sign if it was there. The expression `t-t*2*n` is a shortening of `[t,-t][n]`. [Answer] # GolfScript, 19 / 24 / 28 chars Assuming that positive numbers are always preceded by a `+` sign (19 chars; [online demo](http://golfscript.apphb.com/?c=IyBUZXN0IGlucHV0czoKWwogICIwIiAiKzAiICItMCIKICAiKzEiICItMSIgIisxMjMiICItMTIzIgogICIrOTg3NjU0MzIxMCIgIi05ODc2NTQzMjEwIgpdCiMgUnVuIGNvZGUgZm9yIGVhY2ggdGVzdCBpbnB1dCBhbmQgcHJpbnQgcmVzdWx0Ogp7CiAgKDQ1LX4wQHs0OC1cMTAqK30vKgpwIH0gJQ%3D%3D)): ``` (45-~0@{48-\10*+}/* ``` Assuming that positive numbers *never* have a `+` sign (24 chars; [online demo](http://golfscript.apphb.com/?c=IyBUZXN0IGlucHV0czoKWwogICIwIiAiLTAiCiAgIjEiICItMSIgIjEyMyIgIi0xMjMiCiAgIjk4NzY1NDMyMTAiICItOTg3NjU0MzIxMCIKXQojIFJ1biBjb2RlIGZvciBlYWNoIHRlc3QgaW5wdXQgYW5kIHByaW50IHJlc3VsdDoKewogICItIi8pMFx7NDgtXDEwKit9Ly0xQCw%2FKgpwIH0gJQ%3D%3D)): ``` "-"/)0\{48-\10*+}/-1@,?* ``` Assuming that positive numbers may or may not have a `+` sign (28 chars; [online demo](http://golfscript.apphb.com/?c=IyBUZXN0IGlucHV0czoKWwogICIwIiAiKzAiICItMCIgIjEiICIrMSIgIi0xIgogICIxMjMiICIrMTIzIiAiLTEyMyIKICAiOTg3NjU0MzIxMCIgIis5ODc2NTQzMjEwIiAiLTk4NzY1NDMyMTAiCl0KIyBSdW4gY29kZSBmb3IgZWFjaCB0ZXN0IGlucHV0IGFuZCBwcmludCByZXN1bHQ6CnsKICAiKyItIi0iLykwXHs0OC1cMTAqK30vLTFALD8qCnAgfSAl)): ``` "+"-"-"/)0\{48-\10*+}/-1@,?* ``` (This is the same as the 24-char solution about, but with `"+"-` prepended to strip away any `+` signs.) All of these are based on the following 13-character program, which converts an unsigned base-10 digit string into an integer: ``` 0\{48-\10*+}/ ``` It works by keeping a running total on the stack and iterating over (the ASCII codes of) the characters in the string. For each character, it subtracts 48 (the ASCII code of `0`) from the ASCII code, multiplies the running total by 10, and adds the two together to give the new running total. The rest of the code is for sign handling. The always-signed case is easiest, because we can just chop the first character off the string and test its ASCII code to see if it's `+` (43) or `-` (45). Conveniently, the ASCII codes of those two characters differ by two, so we can easily remap them to 1 and -1 via subtraction and negation. (The code happens to also give the right answer for an unsigned zero, but mostly by accident.) For the only-negatives-signed case, we use a different strategy: we split the input string at `-` signs, take the last segment as the number, and count the number of earlier segments to determine whether to negate the number or not. The code for the maybe-signed case is exactly the same, but we first strip off any plus signs to reduce it to the previous case. --- **Ps.** If we can cheat and use eval, the obvious GolfScript solution is just one character long: ``` ~ ``` It doesn't handle leading `+` signs, though, since GolfScript integer literals don't allow them. [Answer] ## Python, 164 125 121 characters ``` n=raw_input() d=[i-48for i in map(ord,n[::-1])if i!=45] x=0 for i in range(len(d)):x+=d[i]*10**i if'-'==n[0]:x=-x print x ``` Prints out the value with a .0 on the end but that should be all right for the purposes of the exercise, right? Either way, it's a complete script in and of itself. Idea's pretty simple: get ASCII values of the characters passed in, convert those to numbers, multiply each digit by a relevant power of 10 and sum the lot. Test the first character passed in to see if it's negative. It can almost certainly be shortened but since I'm really new to this whole golfing thing (2nd submission) I reckon it's not bad. Edit: further golfed by TheRare [Answer] # GolfScript, 33 characters I'm still pretty new to GolfScript, so I'm not sure how well this came out. I could be missing some better approaches/optimizations. If you see any, let me know so I can hopefully learn! I believe this code works correctly for any signed integer of the form: `[-+]?[0-9]+` [Fully golfed](http://golfscript.apphb.com/?c=Ii0wMTIzNDU2Nzg5MCIKCiguNDU9ITIqKDpzOzQ4LS4wPipcezQ4LXMqXDEwKit9Lw%3D%3D): ``` (.45=!2*(:s;48-.0>*\{48-s*\10*+}/ ``` [Expanded source with C-ish pseudocode](http://golfscript.apphb.com/?c=Ii0wMTIzNDU2Nzg5MCIgICMgY2hhciBpbltdID0gIi0wMTIzNDU2Nzg5MCI7CgooICAgICAgICAgICAgICAgIyBjaGFyIGMwID0gaW5bMF07Ci40NT0hMiooOnM7ICAgICAjIGludCBzID0gYzAgPT0gJy0nID8gLTEgOiAxOwo0OC0uMD4qXCAgICAgICAgIyBpbnQgeCA9IGMwID4gJzAnID8gYzAgLSAnMCcgOiAwOwp7ICAgICAgICAgICAgICAgIyBmb3IgKGNoYXIgYyA6IGluWzEtXSkgewogIDQ4LXMqXDEwKisgICAgIyAgIHggPSB4ICogMTAgKyAoYyAtICcwJykgKiBzOwp9LyAgICAgICAgICAgICAgIyB9CiAgICAgICAgICAgICAgICAjIHJldHVybiB4Ow%3D%3D): ``` "-01234567890" # char in[] = "-01234567890"; ( # char c0 = in[0]; .45=!2*(:s; # int s = c0 == '-' ? -1 : 1; 48-.0>*\ # int x = c0 > '0' ? c0 - '0' : 0; { # for (char c : in[1-]) { 48-s*\10*+ # x = x * 10 + (c - '0') * s; }/ # } # return x; ``` [Answer] # C 75 76 80 chars ``` p(char*s){int c,r=0,m=*s-45;for(;c=*s++;)r=c<48?r:r*10+c-48;return m?r:-r;} ``` No checks for valid inputs, as by rule 1. THX bebe for edit - Now still 1 less [Answer] # Haskell - 51 ~~69~~ chars ``` p('-':n)= -p n p n=foldl(\v->(10*v-48+).fromEnum)0n ``` [Answer] # Python 3 - ~~92~~ 84 I'm pretty happy with this. ``` x=lambda n:[1,-1][n<'0']*sum(10**i*(ord(c)-48)for i,c in enumerate(n[n<'0':][::-1])) ``` Alternatively, without a lambda: (92) ``` def x(n):j=n[0]=='-';return((j*2-1)*sum(10**i*(ord(c)-48)for i,c in enumerate(n[j:][::-1]))) ``` Thanks to xnor for `n<'0'`. [Answer] # CJam - 14 ``` q(',\-\'0f-Ab* ``` It assumes the input is signed, that is, it always starts with a "+" or "-". Try it online at <http://cjam.aditsu.net/> `q` reads the input `(` takes out the first character `',\-` subtracts it from the ',' character, resulting in 1 for '+' and -1 for '-' `\` swaps the sign with the rest of the number `'0f-` subtracts the character '0' from each character, obtaining an integer array `Ab` converts this array to a number in base 10 (A=10) `*` multiplies the number with the sign Thanks Runer112 [Answer] ## Mathematica - 33 or 37 ``` Fold[10#+#2&,0,ToCharacterCode@#-48]& ``` or ``` FromDigits[ToCharacterCode@#-48]& ``` if [`FromDigits`](http://reference.wolfram.com/language/ref/FromDigits.html) is permissible. `FromDigits` takes a list of integers and interprets it as the digits of a number (in arbitrary base). In contrast, `Fold` can be considered a fundamental part of the language (even though what is fundamental and what isn't is a bit subjective in Mathematica). [Answer] # AWK, 120 characters ``` {for(i=0;i<10;i++)o[sprintf("%c",i+48)]=i;for(i=l=length($0);i>0;i--)(c=substr($0,i,1))in o?r+=o[c]*10^(l-i):r=-r;$0=r}1 ``` Usage: ``` $ echo -0123456789 | awk -f parse-int.awk -123456789 ``` AWK is a language where numbers are strings. (Perl, Tcl, and the Unix shell are also such languages.) My code is stupid because it pretends that numbers and strings are different. AWK has no function to convert a string to a code point, so I do the inverse, using `sprintf("%c",i+48)` to convert a code point to a string. I then loop from 0 to 9, storing `o["0"] = 0` through `o["9"] = 9` in an associative array. Later, I use `o[c]` to get the number 9 from the string "9". This is stupid because 9 and "9" are already the same thing. The usual ways to split a string into characters are with `FS=""` or `split(string,array,"")`, but these use `""` as an empty regular expression, and I can't use regular expressions. So, I use `c=substr($0,i,1)` to get each character `c` from the input line `$0`. I check if `c` is an index in array `o`. If yes, I add the product of `o[c]` and a power of 10 to the result. If no, I assume that `c` is a negative sign and negate the result. # AWK, 1 character, no parser! ``` 1 ``` Usage: ``` $ echo -0123456789 | awk 1 -01234567890 ``` This 1-character answer implements all the requirements except for parsing the integer, just by copying input to output. To print the parsed integer, I must format it as a string. The input is already a valid integer formatted as a string. So I optimize my program to skip the parse! [Answer] # Java 7 - 107 Boring and long (typical for Java), but the other Java answer is an embarrassment so I had to remedy the situation. ``` int p(String i){for(int x=1,l=i.length(),a=0;;a=a*10+i.charAt(x++)-48)if(x==l)return i.charAt(0)==45?-a:a;} ``` Ungolfed: ``` int parseInt(String input) { for(int index = 1,len = input.length(),accumulator=0,num;; num = input.charAt(index) - '0', accumulator = accumulator * 10 + num,index++) if (index == len) return input.charAt(0)=='-'?-accumulator:accumulator; } ``` [Answer] # JavaScript (ECMAScript 6) - ~~83~~ ~~80~~ ~~71~~ 67 Characters **Version 4:** Since the input is always signed (i.e. has a leading `+` or `-`) then: ``` f=x=>(t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t) ``` However, if it can be unsigned then (+5 characters): ``` f=x=>(s=-1,t=0,[(k=48-c.charCodeAt())>0?s=4-k:t=10*t+k*s for(c of x)],t) ``` **Version 3:** Since the input is always signed (i.e. has a leading `+` or `-`) then: ``` f=x=>[...x].reduce((p,c)=>(k=48-c.charCodeAt())>0?(s=4-k,0):10*p+k*s,0) ``` **Version 2:** ``` f=x=>[...x].reduce((p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1) ``` **Version 1:** ``` f=x=>[].reduce.call(x,(p,c)=>((k=c.charCodeAt()-48)<0?p:k+10*p),0)*(x[0]=='-'?-1:1) ``` # JavaScript (ECMAScript 6) - 8 Characters JavaScript will implicitly try to convert any variable to a number if you perform an arithmetic operation on it **as part of the language** (i.e. without using any external libraries). So any of the solutions below will convert a string containing a valid number to a number. ``` f=x=>~~x f=x=>x-0 f=x=>x*1 f=x=>x|0 ``` # JavaScript (ECMAScript 6) - 7 Characters ``` f=x=>+x ``` # JavaScript (ECMAScript 6) - 5 Characters Or as an anonymous function: ``` x=>+x ``` [Answer] # Fortran - 46 characters ``` function i(s);character(len=*)s;read(s,*)i;end ``` Call like: ``` i('100') ``` [Answer] # C (82 chars) I'm late to the party and I guess my answer is really close to edc's. ``` int i(char*s){int v=0,n=*s-'-';if(!n)s++;for(;*s;s++)v=v*10+*s-'0';return n?v:-v;} ``` [Answer] ## Scala, 115 characters ``` def p(s:String)=((0,1)/:s.reverse){case(a,'+')=>a;case(a,'-')=>(-a._1,0);case((t,n),d)=>(t+(d.toInt-48)*n,n*10)}._1 ``` Ungolfed: ``` def parseInt(input: String) = ((0, 1) /: input.reverse) { case (acc, '+') => acc case (acc, '-') => (-acc._1, 0) // place never used again case ((total, place), digit) => (total + (digit.toInt - 48) * place, place * 10) }._1 ``` [Answer] # Python 2.7 - 102 bytes ``` def p(n): a,r,l=0,range(10),list(n);d=dict(zip(map(str,r),r)) while l:a*=10;a+=d[l.pop(0)] return a ``` I believe this is valid, but I'm not 100% sure about rule 3. Creates a dictionary where the keys are the strings `'0'`, `'1'`, `'2'`... `'9'` and the values are the int representing that key. Creates a list of the characters in the input, and assigns `a`to 0. While the list we made isn't empty, multiply `a` by 10, take off the first item of that list and use it as a key in the dictionary, adding the value to `a`. Then just return `a`. [Answer] ## Java - 274 Characters ``` static int parseInt(String arg) { int length = arg.length(); String reversed = new StringBuilder(arg).reverse().toString(); int sum = 0; for(int i=0; i<length-1; i++) sum += (reversed.charAt(i)-48) * Math.pow(10, i); if(arg.charAt(0) == '-') sum = -1*sum; else sum += (reversed.charAt(length-1)-48) * Math.pow(10, length-1); return sum; } ``` [Answer] ## C# - 82 characters ``` int p(string t) { var n=t(0)=='-'; var i=n?1:0; var v=0; while(i<t.length) { v=(10*v)+(t(i)-'0'); i++; } return n ? -v : v; } ``` I think this would also parse a string `t` into an int. ``` var i = t.skip(t(0)=='-'?1:0).Aggregate(0,(p,c)=>(10*p)+(c-'0'))*(t(0)=='-'?-1:1); ``` [Answer] ## C 226 Parses positive and negative integers. ``` #include <stdio.h> #define P(x) printf("%d",x) char c; int n,x,y; int main() { while(((c=getchar())=='-') || ((c>='0')&&(c<='9'))) { if(c=='-')y=1; else{ n*=10; x=c-'0'; n+=x; } } if(y)n=-1*n; P(n); getchar(); return 0; } ``` [Answer] # Go - 141 characters ``` func p(s string) (t int) { for i, x := range s { y := int(x) - 48 for j := len(s) - 1; j > i; j-- { y *= 10 } t += y } return } ``` int() here is a straight conversion from a rune (a type identical to int32) to a longer int - and it has to be in the code somewhere to get the function to return an int rather than a rune. The above code is standard go formatting, but technically some of the whitespace is optional. (If you copy/paste the above, before you count the characters, put it in play.golang.org and hit format.) [Answer] in :r4 (<http://code.google.com/p/reda4/>) ``` ::str>int | str -- int 0 swap ( c@+ $2f >? )( $39 >? ( 2drop ; ) $30 - rot 10 * + swap ) 2drop ; ``` is in standard library <http://code.google.com/p/reda4/source/browse/trunk/r4/Lib/parse.txt> line 92 [Answer] ## J - 19 characters ``` 10#.'0123456789'&i. ``` No string manipulation at all. Just index each character into the vector of decimal digits, and take the base-10 representation of that array. [Answer] # Javascript (E6) 80 ~~92~~ Edit: apply 'reduce' directly, no need to 'split'. Thanks to MTO **Esoteric** ``` Q=S=>(m=1,[].reduce.call(S,(p,x)=>(c=48-x.charCodeAt())>0?(m=c-4)&0:p*10-c*m,0)) ``` **Simple loop** stay behind at 92 ``` P=S=>{for(n=i=0,m=S[0]>'/'||(S[i++]>'+'?-1:1);d=S.charCodeAt(i++);n=n*10+m*(d-48));return n} ``` Anyway, assume valid input: first letter can be '-' or '+' or digit, then digits only ... or even ``` F=S=>1*S ``` No library function used [Answer] ## J, 41 chars Here's a J solution that should follow the spec... I'm not very fond of the sign handling; it's too verbose. I can't think of a more compact way, though. ``` (u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|. ``` Sample use: ``` atoi =: (u:48+i.10)&((_1^'-'e.])*10 p.~e.~#i.)@|. atoi '-1234' _1234 ``` [Answer] # C - 69 characters ``` c,r,m;p(char*s){for(m=2,r=0;c=15&*s++;r=c>9?m=r:r*10+c);return--m*r;} ``` [Answer] # Python ~~116~~ ~~108~~ 146 ``` O=b=0 I=list(input()) if I[0]=='-':I.pop(0);b=1 a=range(len(I)) for c in a:I[c]=ord(I[c])-48 for i in a:O+=I[i]*10**(len(I)-i-1) if b:O=-O print O ``` [Answer] # Ruby, 43 characters ``` a=0;$*[0].each_char{|n|a=a*10+n.ord-48};p a ``` Alternate answer (also 43 characters) ``` p $*[0].chars.inject(0){|a,b|a*10+b.ord-48} ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 3 years ago. [Improve this question](/posts/4019/edit) STDIN: Array of integers STDOUT: Smallest difference (the difference between the closest two numbers in the array). Rules: Given an array of positive integers find the difference between the closest two numbers in the array. Performance should be taken into consideration. Example: STDIN: [55, 99, 6, 29, 1, 523, 3] STDOUT: 2 (e.g. 3-1) Scoring: Although somewhat informal, the shortest, most efficient (performance wise) will win. Creativity will also be taken into consideration. [Answer] # The R language **23 characters, O(n log n)** ``` min(diff(sort(scan()))) ``` Example: ``` > min(diff(sort(scan()))) 1: 55 99 6 4: 29 1 523 3 8: Read 7 items [1] 2 ``` ...The `[1] 2` shows the result `2`. (the [1] is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1) [Answer] ## Mathematica, 23 ``` Min@Differences@Sort@#& ``` [Answer] ### JavaScript, 127 characters This is a function that takes the array as a string. It may be O((n-1)²/2+n/2-1/2). I have no idea. ``` function(s){s=eval(s);a=Math.abs;m=a(s[i=0]-s[j=1]);for(;i<s.length;j=++i)for(;++j<s.length;)m=(v=a(s[i]-s[j]))<m?v:m;return m} ``` [Answer] # Scala, O(n log n) ## Script that reads from STDIN (113 chars) ``` val s=Console.readLine.split(",").map(_.toInt).sortBy(i=>i) if(s.size<2)0 else s.tail.zip(s).map(x=>x._1-x._2).min ``` ## Function (94 chars) ``` def m(l:Seq[Int])=if(l.size<2)0 else{val s=l.sortBy(i=>i);s.tail.zip(s).map(x=>x._1-x._2).min} ``` [Answer] # J, 28 ``` <./&(}.-}:)@/:~&.(".&stdin)_ ``` Very straightforward J, drawn down by I/O and parsing. For those who don't read J fluently: * `&` and `@` compose verbs * `<. /` yields a vector's minimum * `( }. - }: )` performs pairwise substraction * `/: ~` sorts up * `&.` performs dark magic so that the next two are used both in the input and output directions * `".` parses/presents J data * `stdin` takes care of I/O * `_` is a dummy argument to `stdin` [Answer] # O(n) space and time ## C++ (1644 chars) Reads from stdin ``` #include <vector> #include <iostream> #include <iterator> #include <algorithm> int radix(int const& a, int const& r) {return (a >> (r << 3)) & 0xFF;} template <int R_> int radix(int const& a) {return radix(a, R_);} template <typename It_, typename Cont_> void distribution(It_ first, It_ const& last, Cont_& d_vector, int const& r) { d_vector.resize(256, 0); std::fill(d_vector.begin(), d_vector.end(), 0); for(; first != last; ++first) d_vector[radix(*first, r)]++; } template <typename It_, typename Cont_> void split(It_ first, It_ const& last, Cont_& d_vector, Cont_& slots, int const& r) { int cnt = 0; for(int i=0; i<256; cnt += d_vector[i++]) std::swap(d_vector[i], cnt); slots.resize(cnt, 0); for(; first != last; ++first) slots[d_vector[radix(*first, r)]++] = *first; } int main(int argc, char* const argv[]) { std::istream_iterator<int> in(std::cin); std::istream_iterator<int> end; std::vector<int> numbers; /// Read numbers std::copy(in, end, std::back_inserter(numbers)); /// Sanity checks if(1 >= numbers.size()) { std::cerr << "not enough numbers" << std::endl; return -1; } /// Sort the numbers 4 times using different radix std::vector<int> d_vector(256, 0); std::vector<int> slots; for(int r=0; r<4; ++r) { distribution(numbers.begin(), numbers.end(), d_vector, r); split(numbers.begin(), numbers.end(), d_vector, slots, r); numbers.swap(slots); } /// Compute the min difference int prev = numbers[1]; int min = prev-numbers[0]; for(std::size_t i=2; i<numbers.size(); ++i) { min = std::min(min, numbers[i]-prev); } std::cout << min << std::endl; return 0; } ``` [Answer] ## APL, 16/18 characters ``` x←⎕⋄⌊/2-/(x[⍒x]) ``` Or with explicit output: ``` x←⎕⋄⎕←⌊/2-/(x[⍒x]) ``` Example: ``` x←⎕⋄⌊/2-/(x[⍒x]) ⎕: 55 9 6 29 1 523 3 2 ``` Explanation: * First expression: + `x←⎕`: Get the input array ( `⎕` ) and assign it ( `←` ) to `x`. * `⋄`: Expression separator. * Second expression, right to left: + `(x[⍒x])`: Sort the input. `⍒x` returns the set of indices needed to sort `x` in descending order, which is used to index `x` ( `x[...]` ). + `2-/`: Splits ( `/` ) the input array into pairs ( `2` ) and finds the difference ( `-` ) between each pair. + `⌊/`: Reduce ( `/` ) the array using the floor function ( `⌊` ). I used [Dyalog APL](http://www.dyalog.com) for this. [Answer] # K, 15 ...... ``` {min@1_-':x@<x} ``` [Answer] ## APL 14 (original...21 chars) ``` {⌊/|{(0≠⍵)/⍵},⍵∘.-⍵}⎕ ``` (edit new shorter...15 chars) ``` {⌊/|0~⍨,⍵∘.-⍵}⎕ ``` (edit again...14 chars) ``` ⌊/|0~⍨,y∘.-y←⎕ ``` assuming no two numbers are the same ``` ⍝ y←⎕ bring in input ⍝ y∘.-y create subtraction table of array y against array y ⍝ 0~⍨ remove zeros (from same element against itself ⍝ on diagonal) ⍝ | absolute value ⍝ ⌊/ reduce with minimum ``` [Answer] ## D (124 chars) O(n log n) time complexity ``` void main(){int[]a;int b;while(readf("%d ",&b))a~=b;b=~0>>>1;sort!(d,c){d-=c;c=d<0?-d:d;b=b<c?b:c;return d;}(a);writeln(b);} ``` using the comparator to keep a running min *while* sorting [Answer] # Haskell, 71 characters, O(n log n) ``` import List;f x=zipWith(-)(tail x)x main=readLn>>=print.minimum.f.sort ``` [Answer] # Python 2.6, 56 48 characters, O(n log n) New version utilizing `min`, `diff`, and `sort` from numpy. Inspired by Tommy's answer. ``` from numpy import* print min(diff(sort(input())) ``` Original version. Inspired by Zachary Vance's answer. ``` a=sorted(input()) print min(y-x for x,y in zip(a,a[1:])) ``` [Answer] **C# 180 Characters** ``` using System;using System.Linq;class P{static void Main(int[]a){Action<int[]> b=Array.Sort;b(a);a=a.Select((c,d)=>(a.Length>d+1?a[d+1]-c:-1)).ToArray();b(a);Console.Write(a[1]);}} ``` Readable: ``` using System; using System.Linq; class P { static void Main(int[]a) { Action<int[]> b = Array.Sort; b(a); a = a.Select((c, d) => (a.Length > d + 1 ? a[d + 1] - c : -1)).ToArray(); b(a); Console.Write(a[1]); } } ``` [Answer] ## Java ``` public static int minDifference(int[] A) { Arrays.sort(A); if (A.length > 1) { int d = Math.abs(A[0] - A[1]); for (int i = 0; i <= A.length; i++) { if (i + 1 < A.length) { int t = Math.abs(A[i] - A[i + 1]); if (t < d) d = t; } } return d; } return -1; } ``` -1 is returned when an array is too short [Answer] # Mathematica 39 Sort standard input,subtract each element n from each element n+1, take the absolute value of those differences, and find the minimum of those. ``` Min[Abs[RotateLeft@# - #] &[Sort@Input[]]] ``` [Answer] ## Perl, 49 characters, O(n log n) ``` say+(sort{$a-$b}map$a*1-($a=$_),sort{$b-$a}<>)[1] ``` The input should be on separate lines; the output is printed after input ends. (I can also make it parse comma-separated input on one line by using the `-naF,` command line switches and replacing `<>` with `@F`.) The `say` command is available since Perl 5.10.0 with the `-E` switch or with `use 5.010`; per [meta](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions) its use is allowed at no extra cost. This uses the same sort-and-diff trick as almost everyone else, with a slight twist to deal with the fact that Perl has no built-in diff command. It first sorts the input in descending order, substracts each number from the previous one in the list and re-sorts the result in ascending order. This leaves one negative value (zero minus the largest input) in front of the list, so the code actually outputs the *second* smallest value. Of course, this only works as long as the input contains at least one positive number, but fortunately the spec says that *all* input values must be positive. (Also, the latest version plays silly tricks with expression evaluation order to shave off a few more chars: apparently `$a-($a=$_)` always evaluates to 0, but `$a*1-($a=$_)` ends up saving the previous value of `$a` on stack before changing it, avoiding the need to store it in a separate variable. With Perl, there ain't no such thing as "undefined behavior"... :) [Answer] # J, 10 chars ``` <./2-/\\:~ ``` It doesn't include explicit input/output, but appending a list to the end like `<./2-/\\:~1,2,3` or `<./2-/\\:~1 2 3` works as one would expect. I'm not too familiar with J's explicit I/O, unfortunately. Explanatory refactoring: ``` sort_down =: \:~ pair_sub =: 2&(-/\) min =: <./ min pair_sub sort_down 1 2 3 ``` `pair_sub` is slightly altered, since J has some rules for precedence and verb composition that makes `pair_sub =: 2-/\` give an error and `pair_sub =: 2&-/\` give a different output when used in the sentence `min pair_sub sort_down 1 2 3` as compared to `<./2-/\\:~ 1 2 3`. [Answer] Java O(n) ``` public int minimumDifference(int[] arr) { int minimum = 0; if (null != arr) { int length = arr.length; if (length == 1) { minimum = arr[0]; } if (length == 2) { minimum = Math.abs(arr[0] - arr[1]); } else if (length > 2) { int minimumSoFar = arr[0]; int secondMinimumSoFar = arr[0]; for (int i = 0; i < length; i++) { if (arr[i] < minimumSoFar) { minimumSoFar = arr[i]; } if (arr[i] > minimumSoFar && arr[i] < secondMinimumSoFar) { secondMinimumSoFar = arr[i]; } } minimum = secondMinimumSoFar - minimumSoFar ; } } return minimum; } ``` [Answer] Python 3.1.3, 77 chars ``` a=sorted(eval(input())) print(min([abs(x-y)for x,y in zip(a[::2],a[1::2])])) ``` ]
[Question] [ **This question already has answers here**: [Obfuscated Hello World](/questions/307/obfuscated-hello-world) (145 answers) Closed 9 years ago. The Oscars are coming up soon and we all know who's going to win Best Actor in a Leading Role this year right? The great Leonardo DiCaprio of course! Despite his superb performances in all of his films during his career, he has yet to win an Academy Award. So as tribute and as a way to wish him luck during the Awards Ceremony this year, your task is to print "Leonardo DiCaprio" (without quotes and case-sensitive) without using any letters in his name in your code. This is code-golf so the shortest code wins. Score is based on your code in bytes. Any language is acceptable. **-100 Points** if you can print his name on an `ascii` plate like so (Best Actor not required): ``` _____________________________ | | | Leonardo DiCaprio | | Best Actor | |_____________________________| ``` **Edit** For clarification, the rule for not "using any letters in his name in your code" is **case-insensitive**. Also **another edit** you may use spaces. [Answer] ## J, 54 - 100 = -46 ``` <17$3(3!:4)8026666198671254860 7598259084372558880 111 ``` Output: ``` ┌─────────────────┐ │Leonardo DiCaprio│ └─────────────────┘ ``` [Answer] ## HTML/Markdown, 96 bytes ``` &#76;&#101;&#111;&#110;&#97;&#114;&#100;&#111;&#32;&#68;&#105;&#67;&#97;&#112;&#114;&#105;&#111; ``` This works even with the strictest rule (no space, no letter case-insensitive). ## Markdown, 194 - 100 = 94 bytes This is the fancy version, so it uses quite a lot of bytes (UTF-8). At the end of the first 2 lines are 2 spaces. ``` ╔════════════╗ ║&#76;&#101;&#111;&#110;&#97;&#114;&#100;&#111;&#32;&#68;&#105;&#67;&#97;&#112;&#114;&#105;&#111;║ ╚════════════╝ ``` How it looks (may or may not look good depending on the font face): ╔════════════╗ ║Leonardo DiCaprio║ ╚════════════╝ ## Markdown, 142 - 100 = 42 bytes This is the poor man's version. No Unicode character is used, so quite lightweight. ``` ~~~~~~~~~~~~~~~~~ | &#76;&#101;&#111;&#110;&#97;&#114;&#100;&#111;&#32;&#68;&#105;&#67;&#97;&#112;&#114;&#105;&#111; | ~~~~~~~~~~~~~~~~~ ``` It looks like a cookie to me: ~~~~~~~~~~~~~~~~~ | Leonardo DiCaprio | ~~~~~~~~~~~~~~~~~ [Answer] # BF, 77 203 chars = 609 bits = 77 bytes ``` -[------->+<]>+++.-[--->++++<]>+.++++++++++.-.-------------.--[--->+<]>---.--------------.+++++++++++.[--->+<]>-----.++[->++<]>.++[-->+++<]>.++[->+++<]>++.-[-->+++<]>--.-[++>-----<]>.++.---------.++++++. ``` Output: ``` Leonardo DiCaprio ``` [Answer] ## Sclipting, 39 bytes ``` 丟냆녯닦굲뉆묠끆땃눗걲늖및 ``` Based on the Hello, world! program, just encode the name as string. [Answer] # JavaScript 221 - 100 = 121 This took a little working out... instead of printing, it pushes the result as an `alert`... best I could do... trying to make this code do a `document.write` would have floored me... `3[z=(y=''+{})[5]+y[1]+(''+1/0)[1]+'st'+(x=''+!0)[1]+'u'+y[5]+'t'+y[1]+x[1]][z]("\141\154\145\162t('"+(v="+--------------------+")+"\\\156|\114\145\157\156\141\162\144\157 \104\151\103\141\160\162\151\157|\\\156"+v+"')")()` ]
[Question] [ Per the fundamental theorem of arithmetic, for a given number \$n\$, it is possible to find it's prime factors, and they are unique. Let's imagine we talk only of \$n\$ that is non-prime (composite). We can also find the factors of all the composite numbers smaller than \$n\$. For example if \$n\$ is 10, then it has factors 5 and 2. 9 has 3 and 3. 8 has 2, thrice. 6 has 3 and 2. 4 has 2 and 2. So for the number 10, all the prime factors of all the composite numbers smaller than 10 would be listed as 2,3, and 5. Now if you put a lot of vegetables in a pot for soup, often the largest will rise to the top. So if we put all of these factors in a big pot, which one will be the largest and rise to the top? For 10 soup, that answer is 5. "Silly", you might think, "the number \$n\$ itself will have the largest factors, larger than the factors of numbers smaller than \$n\$". But this is where you are wrong my friend! For example, the factors of 16 are all 2, repeated four times. The factors of 15 are 5 and 3, now, I don't have to be a mathematician to tell that 15 is smaller than 16, but 5 is bigger than 2! Your challenge is to explore how this works for bigger \$n\$. For any number given input number \$n\$, assumed natural, composite, and less than 2^32, find out which is the "largest factor" of all the prime factors of all the composite numbers less than or equal to \$n\$. Good luck and have fun! Smallest byte count wins. [Answer] # [Neim](https://github.com/okx-code/Neim), 3 bytes ``` ᚺ>: ``` Explanation: ``` ᚺ halve > increment : previous prime ``` [Try it online!](https://tio.run/##y0vNzP3//@GsXXZW//9bWloCAA "Neim – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ;ÅPθ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f@nBrwOEF//8bGhgYAAA) or [verify first \$[4,n]\$ numbers](https://tio.run/##yy9OTMpM/W/ieXRHWaW9ksKjtkkKSvaV/60PtwYcXvBf57@hgQEA). **Explanation:** Implementation of the observation [@xnor's made in his comment](https://codegolf.stackexchange.com/questions/185381/composite-factor-soup#comment444372_185381): largest prime \$\leq\frac{1}{2}n\$. Which I've literally implemented now (after *@Arnauld* reported some bugs in my initial program): ``` ; # Halve the (implicit) input ÅP # Get a list of primes smaller than or equal to this à # And only leave the largest prime # (which is output implicitly as result) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` Prime@PrimePi[#/2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6AoMzfVAUwGZEYr6xvFqoHE8kqilXXt0hyUY9X0HYIS81Lyc4MTcwtyUqODU3NSk0uigWLpqdEmOsYGBgaxOopgAwIdlNVidQwNYv8DAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v1.4.5 [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 6 bytes ``` z o fj ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&flags=LWg&code=eiBvIGZq&input=MTY) [Answer] # [J](http://jsoftware.com/), 10 bytes ``` _4 p:-:@>: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/400UCqx0rRzsrP5rcilwpSZn5CukKRgawFiWlpYwppG5qRGMbW4JZxoZ/gcA "J – Try It Online") Uses the xnor's observation ## Explanation: ``` _4 p: the next prime smaller than >: the input plus 1 -:@ divided by 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ‘HÆp ``` [Try it online!](https://tio.run/##y0rNyan8//9RwwyPw20F////NzIEAA "Jelly – Try It Online") As others have observed, the answer is the largest prime \$≤ n/2\$ Thanks to @Arnauld for correcting my order of halving/incrementing [Answer] # [Factor](https://factorcode.org/), 37 bytes ``` : p ( n -- n ) 2 / primes-upto last ; ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVCcWliampecWgzm6hUUZeYC2QVFqSUllUBOXomCNZenn5VCQICz@38rhQIFDYU8BV1dIKGpYKSgrwDRoFtaUJKvkJNYDFT@v1rB0EDByFDBTMFEoVYhGqgnFmh4gYIe138A "Factor – Try It Online") [Answer] # JavaScript (ES6), 40 bytes After a careful analysis of (xnor's comment on) the challenge, it turns out that ~~42 41~~ 40 is the answer. ``` n=>(g=k=>n%--k?g(k):k<2?n:g(--n))(n>>=1) ``` [Try it online!](https://tio.run/##FdBLTsMwFIXhOavwBNUWcVW/TcHpiFUgBlFoAqSyUYvYfvpncCTrfr5Hln@G/@E2Xr9//3Rtn@d1KmstvZzLUvr6qPVymuWijsurPdXjLLWuSsna98Wo9eXddyJ2InfiuRPmQCxhaAJBDGSZW0Mwi1nMYjYR3OEOc47gDne424xej3vcYx7zmMc8FrBAd8ADHvCAB7oDdyIesUh33B6LRzxuxn7CE56whCUssZvwjGW6M57xHD4e9lO7vg3jl6yi9GJs9dYu5/2lzQyexG4b7jhMkl9S6x0 "JavaScript (Node.js) – Try It Online") ### Commented We look for the highest prime \$p\le\left\lfloor\dfrac{n}{2}\right\rfloor\$. ``` n => ( // n = input g = k => // g = recursive function looking for the highest divisor k < n of n n % --k ? // decrement k; if k is not a divisor of n: g(k) // do recursive calls until it is : // else: k < 2 ? // if k is less than 2 (i.e. n is prime): n // stop recursion and return n : // else: g(--n) // try again with n - 1 )(n >>= 1) // initial call to g with n = floor(n / 2) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~34~~ 32 bytes ``` .+ $* (.+)(?<!^\2+(..+))\1.* $.1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLQ09bU8PeRjEuxkhbQw/I0Ywx1NPiUtEz/P/f0AwA "Retina 0.8.2 – Try It Online") Edit: Saved 2 bytes thanks to @Grimy. Explanation: ``` .+ $* ``` Convert to unary. ``` (.+) ``` Find the largest number... ``` (?<!^\2+(..+)) ``` ... that is prime ... ``` \1.* ``` ... and a factor of a number not greater than the input. ``` $.1 ``` Convert to decimal. [Answer] # [Ruby](https://www.ruby-lang.org/), 24+8 = 32 bytes 8 bytes for the `-rprime` flag (plus space) to import the Prime module. `Prime.each(n)` gets all primes up to `n`, then we just take the largest one. (We could take the last item since it's in order, but that costs more bytes.) ``` ->n{Prime.each(n/2).max} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9curzqgKDM3VS81MTlDI0/fSFMvN7Gi9n@BQlq0SrxeSX58Zux/QwMuQzMuc3Pzf/kFJZn5ecX/dYsKQLr@6@YBAA "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` →`↑İp≤½ ``` [Try it online!](https://tio.run/##ARoA5f9odXNr///ihpJg4oaRxLBw4omkwr3///8xMA "Husk – Try It Online") ]
[Question] [ Create a program that outputs "Hi, Hello!" in `k` bytes. By altering `n` bytes, the code should output all odd numbers in the range 5 <= x <= 25. Changing another `m` bytes should result in a code that prints the following frame in ASCII-art: ``` +-+ | | +-+ ``` Change another `o` bytes, and print `Hello, bye!`. `m`, `n` and `o` are calculated in [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) (cumulative). `n` is the distance from the first to the second code. `m` is the distance between the second and third and so on. The score of your submission will be `0.5*k + n + m + o`. As an example: ``` The code that prints `Hi, Hello!` is 30 bytes. 15 Add two bytes and remove one and print the odd numbers + 3 Alter three bytes in place, and add one to print the box + 4 Remove four bytes and print `Hello, bye!` + 4 Total score: 26 ``` Rules * All codes must be in the same language * You have to follow the given order (i.e. the first code prints `Hi, Hello`, the second prints the numbers etc.) * The strings and ASCII-box must be exactly as specified. The list of digits can be on any suitable format [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 42 ÷ 2 = 21 + 1 + 1 + 1 = 24 `Hi, Hello` code: ``` ”Hi,Ÿ™!”25Åɦ¦"+-+ "©"| | "®««“Ÿ™,Þ¡!“ª\\\ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCdSGksxbjihKIh4oCdMjXDhcOJwqbCpiIrLSsKIsKpInwgfAoiwq7Cq8Kr4oCcxbjihKIsw57CoSHigJzCqlxcXA&input=). --- Odd numbers code: ``` ”Hi,Ÿ™!”25Åɦ¦"+-+ "©"| | "®««“Ÿ™,Þ¡!“ª\\ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCdSGksxbjihKIh4oCdMjXDhcOJwqbCpiIrLSsKIsKpInwgfAoiwq7Cq8Kr4oCcxbjihKIsw57CoSHigJzCqlxc&input=). --- Box code: ``` ”Hi,Ÿ™!”25Åɦ¦"+-+ "©"| | "®««“Ÿ™,Þ¡!“ª\ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCdSGksxbjihKIh4oCdMjXDhcOJwqbCpiIrLSsKIsKpInwgfAoiwq7Cq8Kr4oCcxbjihKIsw57CoSHigJzCqlw&input=) --- `Hello, bye` code: ``` ”Hi,Ÿ™!”25Åɦ¦"+-+ "©"| | "®««“Ÿ™,Þ¡!“ª ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCdSGksxbjihKIh4oCdMjXDhcOJwqbCpiIrLSsKIsKpInwgfAoiwq7Cq8Kr4oCcxbjihKIsw57CoSHigJzCqg&input=). Uses **CP-1252** encoding. [Answer] # Pyth - ~~49~~ ~~46~~ 44/2 + 1 + 1 + 1 = 25 Hello code: ``` h["Hi, Hello!":5lG2"+-+ | | +-+""Hello, bye! ``` Odd numbers code: ``` ht["Hi, Hello!":5lG2"+-+ | | +-+""Hello, bye! ``` Box code: ``` htt["Hi, Hello!":5lG2"+-+ | | +-+""Hello, bye! ``` Bye Code: ``` httt["Hi, Hello!":5lG2"+-+ | | +-+""Hello, bye! ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 23 ### First program, 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “"©ĊĠȦẋạ» 5r25m2 “+-+¶| ”ȮṖṚ “(ʠƤ,ụȤ» 1£ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcIsKpxIrEoMim4bqL4bqhwrsKNXIyNW0yCuKAnCstK8K2fCDigJ3IruG5luG5mgrigJwoyqDGpCzhu6XIpMK7CjHCow&input=) ### Second program, edit distance 1 ``` “"©ĊĠȦẋạ» 5r25m2 “+-+¶| ”ȮṖṚ “(ʠƤ,ụȤ» 2£ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcIsKpxIrEoMim4bqL4bqhwrsKNXIyNW0yCuKAnCstK8K2fCDigJ3IruG5luG5mgrigJwoyqDGpCzhu6XIpMK7CjLCow&input=) ### Third program, edit distance 1 ``` “"©ĊĠȦẋạ» 5r25m2 “+-+¶| ”ȮṖṚ “(ʠƤ,ụȤ» 3£ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcIsKpxIrEoMim4bqL4bqhwrsKNXIyNW0yCuKAnCstK8K2fCDigJ3IruG5luG5mgrigJwoyqDGpCzhu6XIpMK7CjPCow&input=) ### Fourth program, edit distance 1 ``` “"©ĊĠȦẋạ» 5r25m2 “+-+¶| ”ȮṖṚ “(ʠƤ,ụȤ» 4£ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcIsKpxIrEoMim4bqL4bqhwrsKNXIyNW0yCuKAnCstK8K2fCDigJ3IruG5luG5mgrigJwoyqDGpCzhu6XIpMK7CjTCow&input=) ## How it works In all Jelly programs, every line defines a *link*. The last one is the *main link* and is executed automatically by the interpreter. The quick `£` inspects the number before it and calls the link on that line, so it suffices to place the four individual programs on different lines and call the appropriate one. ### First program ``` “"©ĊĠȦẋạ» ``` This simply uses Jelly's built-in [compression](https://codegolf.stackexchange.com/a/70932), constructing the string as `Hi,` (bare string), `Hello` (dictionary word) and `!` (bare string). ### Second program ``` 5r25m2 ``` `5` sets the left argument to **5**, `r25` creates a range up to **25** and `m2` selects every second element. ### Third program ``` “+-+¶| ”ȮṖṚ ``` `“+-+¶| ”` sets the left argument to that string, `Ȯ` prints it explicitly, `Ṗ` removes the last character and `Ṛ` reverses the result. The reversed string gets printed implicitly. ### Fourth program ``` “(ʠƤ,ụȤ» ``` Akin to the first program, this compresses the output string as `Hello` (dictionary word), `,` (bare string), `bye` (dictionary word, leading space) and `!` (bare string). [Answer] # J, ~~33~~ 31 ``` 3{(a,', bye!');(<' ');(>:+:i.13);'Hi, ',(a=:'Hello'),'!' 2{(a,', bye!');(<' ');(>:+:i.13);'Hi, ',(a=:'Hello'),'!' 1{(a,', bye!');(<' ');(>:+:i.13);'Hi, ',(a=:'Hello'),'!' 0{(a,', bye!');(<' ');(>:+:i.13);'Hi, ',(a=:'Hello'),'!' ``` We select the element from the boxed list that we need. ## Old solution, 33 bytes ``` 'Hi, Hello!' 'Hi']>:+:i.13 'Hi']<' ' 'Hello, bye!' ``` [Calculated here, requires ES6 browser](http://conorobrien-foxx.github.io/Jolf/#code=b2ldwqsKCidIaSwgSGVsbG8hJwonSGknXT46KzppLjEzCidIaSddPCcgJwonSGVsbG8sIEJ5ZSEnCgrCuzJfMgpveEdpUwoKdSt-Oi9sRngyfm1deDBfMWR-TEgueGhT) ``` 'Hi, Hello!' 12 / 2 = 6 'Hi']>:+:i.13 + l.d. 10 'Hi']<' ' + l.d. 8 'Hello, bye!' + l.d. 9 = 33 ``` Requires the console interpreter for `'Hi']<' '`, which uses the fact that displayed boxed items use the required ASCII border; we just box a space in this case. --- Bonus code in jolf: ``` u+~:/lFx2~m]x0_1d~LH.xhS ``` Just call this with an array containing your solutions to calculate the scores! Alternatively, open up the console and type in: ``` jolf("u+~:/lFx2~m]x0_1d~LH.xhS", ["p1", "p2", "p3", "p4"]); ``` [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 58/2 + 1 + 1 + 1 = 32 byte-points ``` "Hi, Hello!""Hello, bye!"%@0{25*!5[X2a]@}"+-+"X"| |"X"+-+" ``` This code as-is prints `Hi, Hello!`. By changing the `%` to a space (), you get `Hello, bye!`. By changing the first `@` to a space (), you get the list of odd numbers, starting with 5 and ending with 25.. And finally, by changing the `0` to a space, , you get `+-+\n| |\n+-+`. The 4 pieces of code (iterated removals): ``` "Hi, Hello!""Hello, bye!"%@0{25*!5[X2a]@}"+-+"X"| |"X"+-+" "Hi, Hello!""Hello, bye!" @0{25*!5[X2a]@}"+-+"X"| |"X"+-+" "Hi, Hello!""Hello, bye!" 0{25*!5[X2a]@}"+-+"X"| |"X"+-+" "Hi, Hello!""Hello, bye!" {25*!5[X2a]@}"+-+"X"| |"X"+-+" ``` [Answer] ## Haskell, 41 ``` "Hi, Hello!" --[5,7..25] --"+-+\n| |\n+-+" --"Hello, bye!" --"Hi, Hello" [5,7..25] --"+-+\n| |\n+-+" --"Hello, bye!" --"Hi,Hello" --[5,7..25] "+-+\n| |\n+-+" --"Hello, bye!" --"Hi,Hello" --[5,7..25] --"+-+\n| |\n+-+" "Hello, bye!" ``` The initial program is 58 bytes, i.e. a score of 29. Each of the successors adds `--` and removes `--` for a score of 4, so the total is 29 + 3\*4 = 41. ## Haskell 33.5 If returning the list of numbers as a String, i.e. `"[5,7,9,11,13,15,17,19,21,23,25]"` is fine, then ``` ["Hi, Hello!",show[5,7..25],"+-+\n| |\n+-+","Hello, bye!"]!!0 ["Hi, Hello!",show[5,7..25],"+-+\n| |\n+-+","Hello, bye!"]!!1 ["Hi, Hello!",show[5,7..25],"+-+\n| |\n+-+","Hello, bye!"]!!2 ["Hi, Hello!",show[5,7..25],"+-+\n| |\n+-+","Hello, bye!"]!!3 ``` works for 61/2 + 1 + 1 +1 = 33.5 [Answer] # Octave, 34 Managed to get it down to 62 bytes. A Levenshtein distance of 3 takes the score up to 34. ``` disp({'Hi, Hello!',["+-+\n| |\n+-+"],5:2:25,'Hello, bye!'}{1}) ``` Using double quoted strings, we can use the newline character `\n` instead of the ASCII value `10`. Tests: ``` disp({'Hi, Hello!',["+-+\n| |\n+-+"],5:2:25,'Hello, bye!'}{1}) Hi, Hello! disp({'Hi, Hello!',["+-+\n| |\n+-+"],5:2:25,'Hello, bye!'}{2}) +-+ | | +-+ disp({'Hi, Hello!',["+-+\n| |\n+-+"],5:2:25,'Hello, bye!'}{3}) 5 7 9 11 13 15 17 19 21 23 25 disp({'Hi, Hello!',["+-+\n| |\n+-+"],5:2:25,'Hello, bye!'}{4}) Hello, bye! ``` [Answer] ## JavaScript, 80 ÷ 2 + 1 + 1 + 1 = 43 ``` _=>[`Hi, Hello!`,`5 7 9 11 13 15 17 19 21 23 25`,`+-+ | | +-+`,`Hello, bye!`][0] ``` Change the 0 to 1, 2, or 3 as appropriate. I tried generating the odd numbers but that cost me a byte. [Answer] # Python 3, 69/2 + 1 + 1 + 1 = 37.5 points. It's the same approach as the other answers, but in Python. ``` print(['Hi, Hello!',*range(5,27,2),'+-+\n| |\n+-+','Hello, bye!'][1]) ``` Change the number to the one you want for a distance of 1. [Answer] # Python 2, 66 / 2 + 1 + 1 + 1 = 36 [Python 3 answer](https://codegolf.stackexchange.com/a/80450/41024) by @MorganThrapp ``` Hi, Hello! ``` ``` print('Hi, Hello!',range(5,26,2),'+-+\n| |\n+-+','Hello, bye!')[0] ``` ``` [5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] ``` ``` print('Hi, Hello!',range(5,26,2),'+-+\n| |\n+-+','Hello, bye!')[1] ``` ``` +-+ | | +-+ ``` ``` print('Hi, Hello!',range(5,26,2),'+-+\n| |\n+-+','Hello, bye!')[2] ``` ``` Hello, bye! ``` ``` print('Hi, Hello!',range(5,26,2),'+-+\n| |\n+-+','Hello, bye!')[3] ``` [Answer] # Mathematica, 74/2+1+1+1 = 40 ``` s=##<>"!"&;s["Hi, ",h="Hello"][2Range@11+3,"+-+ | | +-+",h~s~", bye"][[0]] ``` Creates a list whose elements are the four outputs, and then selects list element `0` to produce the first output; that `0` can be changed to `1`, `2`, or `3` to produce the other outputs. (The odd integers from 5 to 25 are output as a list.) Saved one byte by using the golfing trick where the head of a "list" is its element 0. Also saved a few bytes by defining a function `s` that concatenates its two arguments and adds an exclamation point, which allows me to reuse `"Hello"`. [Answer] ## [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), score: ~~19.5~~ 18.5 (31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) / 2 + 1 + 1 + 1) 1. `“Ÿ™,Þ¡!“ª"+-+\n| "ûTÝ·5+”ŒÞ,Ÿ™!”` - [try it online](https://tio.run/##MzBNTDJM/f//UcOcozsetSzSOTzv0EJFIO/QKiVtXW2uGgWlw7tDDs89tN1U@1HD3KOTDs/TASsEqpn7/z8A); 2. `“Ÿ™,Þ¡!“ª"+-+\n| "ûTÝ·5+”ŒÞ,Ÿ™!”\` - [try it online](https://tio.run/##MzBNTDJM/f//UcOcozsetSzSOTzv0EJFIO/QKiVtXW2uGgWlw7tDDs89tN1U@1HD3KOTDs/TASsEqpkb8/8/AA); 3. `“Ÿ™,Þ¡!“ª"+-+\n| "ûTÝ·5+”ŒÞ,Ÿ™!”\\` - [try it online](https://tio.run/##MzBNTDJM/f//UcOcozsetSzSOTzv0EJFIO/QKiVtXW2uGgWlw7tDDs89tN1U@1HD3KOTDs/TASsEqpkbE/P/PwA); 4. `“Ÿ™,Þ¡!“ª"+-+\n| "ûTÝ·5+”ŒÞ,Ÿ™!”\\\` - [try it online](https://tio.run/##MzBNTDJM/f//UcOcozsetSzSOTzv0EJFIO/QKiVtXW2uGgWlw7tDDs89tN1U@1HD3KOTDs/TASsEqpkbExPz/z8A). Based on [*@Adnan*'s 05AB1E (legacy) answer](https://codegolf.stackexchange.com/a/80395/52210), but further golfed. Since *Adnan* isn't really active anymore, I decided to post it as a separated answer. **Explanation:** ``` “Ÿ™,Þ¡!“ª # Fourth output: “Ÿ™,Þ¡!“ # Push dictionary string "hello, bye!" ª # Sentence capitalize it: "Hello, bye!" "+-+\n| "û # Third output: "+-+\n| " # Push string "+-+\n| " û # Palindromize it to "+-+\n| |\n+-+" TÝ·5+ # Second output: TÝ # Push list [0,1,2,3,4,5,6,7,8,9,10] · # Double each: [0,2,4,6,8,10,12,14,16,18,20] 5+ # Increase each by 5: [5,7,9,11,13,15,17,19,21,23,25] ”ŒÞ,Ÿ™!” # First output: ”ŒÞ,Ÿ™!” # Push dictionary string "Hi, Hello!" \ # (zero to three times) Discard the top of the stack # (implicitly output the top of the stack as result) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“Ÿ™,Þ¡!“` is `"hello, bye!"` and `”ŒÞ,Ÿ™!”` is `"Hi, Hello!"`. `ª` (sentence capitalize) is the reason for using the legacy version of 05AB1E, since this builtin is `.ª` in the new version of 05AB1E. ]
[Question] [ # Aim If you are given a sequence such as `(A, G, M, _, _, C, D, _, G)` your aim is to push all non empty elements to one side to get `(A, G, M, C, D, G, _, _, _)`. You must preserve the order of the non-empty elements. # Rules 1. You are free to choose the sequence type. (strings, numbers, containers etc). You must also choose a Nil/None/Null character or element that will fit your sequence type. eg; spaces or underscores inside a string. 2. User should be able to input the push direction (left or right) and the sequence. Input values and format are up to you to choose. eg; Your code handles sequences that are numbers with `7` as the null character. You set `R` for right, `L` for left. So user inputs `R, 1577462722727777`. The result is `7777777715462222` 3. Rearranged sequence should be displayed or written to a file. 4. Your code should not exceed 128 bytes. # Points 1. **+(10 / bytes)** golfing points 2. **+1** for Moses-Mode. Push half the elements to the left, and half to the right. If odd number of items are present, you may choose the direction of the final element. eg; `(A, G, M, _, _, _, C, D, G)` *You may use use this [calculator](http://www.calculatorsoup.com/calculators/math/roundingnumbers.php) to round your points to the hundredth decimal place.* [Answer] # R - 10 / ~~71~~ ~~70~~ ~~66~~ 39 bytes = 0.26 points Saved **27 bytes** thanks to Mickey! ``` function(d,s)s[order(xor(!is.na(s),d))] ``` This creates an unnamed function which takes a direction `d` (logical with `TRUE` corresponding to right and `FALSE` to left (legit per OP's comment)) and a vector `s` (assumed to use `NA` for empty elements) as input and returns a vector. To call it, give it a name, e.g. `f=function(d,s)...`. This does not support "Moses Mode." Ungolfed + explanation: ``` f <- function(d, s) { # Order the elements of s by non-missing exclusive or direction s[order(xor(!is.na(s), d))] } ``` Examples: ``` > test <- c(1, 5, NA, NA, 4, 6, 2, NA, 2, 2, NA, 2, NA, NA, NA, NA) > f(FALSE, test) [1] NA NA NA NA NA NA NA NA 1 5 4 6 2 2 2 2 > f(TRUE, test) [1] 1 5 4 6 2 2 2 2 NA NA NA NA NA NA NA NA ``` And an extra special example just for FryAmTheEggman: ``` > c(f(TRUE, test), "BATMAN") [1] "1" "5" "4" "6" "2" "2" "2" "2" NA NA NA NA NA NA NA NA "BATMAN" ``` [Answer] # Haskell 10/24 bytes = 0.42 points ``` import Data.List (.sort) ``` Sadly the `sort` function is in `Data.List`, so I have to import it. The sequence type is boolean values, i.e. `True` or `False`. The empty value is `False`. Pushing non empty values to the right is indicated by `id` and to the left by `reverse`. Example usage: ``` *Main> (.sort) id [True,False,False,True,False,True] [False,False,False,True,True,True] *Main> (.sort) reverse [True,False,False,True,False,True] [True,True,True,False,False,False] ``` [Answer] # Pyth, 10 / ~~15~~ 14 bytes + 1 = 1.71 points ``` [[email protected]](/cdn-cgi/l/email-protection)@dzQ ``` This takes two lines of input. The first one is a string (spaces are the special characters) and the second one is `0` (push all spaces to the right), `1` (Moses-mode) or `4` (push all spaces to the left). Try it online: [Demonstration](https://pyth.herokuapp.com/?code=s%40.pac2-zd%40dzQ&input=AGM++CD+G%0A4&debug=0) Thanks to @isaacg for saving one byte ### Explanation: ``` implicit: z = input string, Q = input number -zd remove all spaces from z c2 split into 2 equal pieces a append @dz get all spaces in z .p create all permutation of the 3 strings @ Q choose the Qth permutation s and join the strings ``` # Pyth, 10 / 7 bytes = 1.43 points ``` oqQqNdz ``` Input format: string on first line, and `0` (push spaces to the left) or `1` (push spaces to the right) on second line. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=oqQqNdz&input=AGM%20%20CD%20G%0A0&debug=0) This is worth less points, but it's a quite simple and elegant solution. ### Explanation: ``` implicit: z = input string, Q = input number o z order the chars N of z by the key: qQqNd Q == (N == " ") ``` When `Q == 0` all spaces get the key `0` and all other chars get the key `1`, otherwise it's exactly opposite. Then the string is sorted by their keys. Since sorting is stable in Pyth, it sorts all spaces either to the beginning or the end and keeps all other chars in the same order. [Answer] I honestly don't mind that the challenge has a byte limit. It is the OP's choice to impose that restriction to make things more interesting. However, just to represent how a "wordy" language would do, here's java: # Java **283 bytes = 0.04points + 1 = 1.04** ``` enum E{;public static void main(String[]r){String s="",t=r[0].substring(1),d="_";char p=r[0].charAt(0);for(;t.indexOf(d)>=0;){r=t.split(d,2);t=r[0]+r[1];s+=d;}int x=(t.length()-1)/2;if(p=='L')t+=s;else if(p=='R')t=s+t;else t=t.substring(0,x)+s+t.substring(x+1);System.out.print(t);}} ``` Input is from the command line. The first character can be L for left, R for right, anything else for moses mode. Underscore is used for the null character. If I remove the moses mode code, I get: **207 bytes = 0.05points** ``` enum E{;public static void main(String[]r){String s="",t=r[0].substring(1),d="_";char p=r[0].charAt(0);for(;t.indexOf(d)>=0;){r=t.split(d,2);t=r[0]+r[1];s+=d;}if(p=='L')t+=s;else t=s+t;System.out.print(t);}} ``` Input is from the command line. L is left, anything else is right. Underscore is null. I quite enjoyed the challenge of trying to fit Java code inside 128 bytes. Java just isn't a competitive language for codegolfs though. [Answer] # k,10/12 = 0.83 points ``` {x((>:;<:)y)x} ``` It takes an array of booleans and a 0 or 1 to say to push to the right or the left. ``` k){x((>:;<:)y)x}[1011110101101b;0] 1111111110000b k){x((>:;<:)y)x}[1011110101101b;1] 0000111111111b ``` # k, 10/29 = 0.34 points A more flexible version that should work for all input types and which allows you to choose the null character. ``` {x@,/$[~z;|:;](&~:;&:)@\:x=y} ``` . ``` k){x@,/$[~z;|:;](&~:;&:)@\:x=y}[1 0 3 6 5 6 0 6 0;6;0] 6 6 6 1 0 3 5 0 0 k){x@,/$[~z;|:;](&~:;&:)@\:x=y}[1 0 3 6 5 6 0 6 0;6;1] 1 0 3 5 0 0 6 6 6 k){x@,/$[~z;|:;](&~:;&:)@\:x=y}[1 0 3 6 5 6 0 6 0;0;1] 1 3 6 5 6 6 0 0 0 k){x@,/$[~z;|:;](&~:;&:)@\:x=y}["abc def ghi";" ";1] "abcdefghi " k){x@,/$[~z;|:;](&~:;&:)@\:x=y}["abc def ghi";" ";0] " abcdefghi" ``` [Answer] # Pyth - 10 / 1 byte + 1 = 11 Really cheaty, but it seems allowed, basically puts all the code in the options. Doing bonus now. It takes an array of ints, with `0` as falsey. The left value is: `Y.append(eval(input())) or [i for i in Y[0] if i] + [0]*Y[0].count(0)` The right value is: `Y.append(eval(input())) or [0]*Y[0].count(0) + [i for i in Y[0] if i]` The Moses value is: `Y.append(eval(input())) or Y.append(chop(2, [i for i in Y[0] if i])) or Y[1][0] + [0]*Y[0].count(0) + Y[1][1]` So here is the code: ``` Q ``` Because of security reasons it only works locally, not online. ## Old, non-cheaty one - 0.83: Not going for the bonus, takes array of ints, `0` is falsey, and `1` for right, `-1` for left. ``` Ms%H,fTGf!TG ``` Explanation coming soon. ``` M Two var lambda s Join the two parts of the array % String slice step, reverses if -1, unchanged if 1 H Second arg , Two element list fTG Filter arg 1 for truthiness f!TG Filter arg 1 for falsiness ``` [Try it here online.](http://pyth.herokuapp.com/?code=Ms%25H%2CfTGf!TGgQvw&input=%5B1%2C+5%2C+8%2C+0%2C+2%2C+0%2C+6%2C+0%2C+8%2C+7%5D%0A-1&debug=1) [Answer] # R 10 / 69 + 1 = 1.14 Not very pretty. An unnamed function where d is a either 0 (left), 1 (right) or .5 (Moses). s is a vector of integers where 0 as the null. ``` function(d,s)c(rep(0,(l=length(s[!s]))*(1-d)),s[!!s],rep(0,(l*d)+.5)) ``` Test example ``` > g=function(d,s)c(rep(0,(l=length(s[!s]))*(1-d)),s[!!s],rep(0,(l*d)+.5)) > test=c(17,0,2,42,2,4,35,0,0,45,0,2,0,7,9) > g(0,test) [1] 0 0 0 0 0 17 2 42 2 4 35 45 2 7 9 > g(1,test) [1] 17 2 42 2 4 35 45 2 7 9 0 0 0 0 0 > g(.5,test) [1] 0 0 17 2 42 2 4 35 45 2 7 9 0 0 0 > test=c(17,0,2,42,0,2,4,35,0,0,45,0,2,0,7,9) > g(0,test) [1] 0 0 0 0 0 0 17 2 42 2 4 35 45 2 7 9 > g(1,test) [1] 17 2 42 2 4 35 45 2 7 9 0 0 0 0 0 0 > g(.5,test) [1] 0 0 0 17 2 42 2 4 35 45 2 7 9 0 0 0 > ``` [Answer] ## JavaScript (ES6) - 168 bytes, 1.06 points ``` x=(d,a)=>{c='concat',l='length',o=a.filter(l=>l),z=new Array(a[l]-o[l]).fill(0);if(!d)Array.prototype.splice.apply(o,[a[l]/4,0][c](z));return d?(d>1?z[c](o):o[c](z)):o} ``` Input: * 0 (or any falsy value) for Moses mode, 1 for push left, 2 for push right * Array of integers in second parameter, 0 considered empty ### Unminified code ``` x = (mode, data) => { var concat = 'concat', length = 'length', stripped = data.filter(el => { return !!el; }), zeroes = new Array(data[length] - stripped[length]).fill(0); if (!mode) { Array.prototype.splice.apply(stripped, [data[length] / 4, 0][concat](zeroes)); } return mode ? (mode > 1 ? zeroes[concat](stripped) : stripped[concat](zeroes)) : stripped; }; ``` [Answer] ## CoffeeScript, 172 bytes = 1.06 points ``` x=(m,d)->c='concat';l='length';s=d.filter((el)->el);z=new Array(d[l]-s[l]).fill 0;(Array.prototype.splice.apply(s,[d[l]/4,0][c] z);return s)if!m--;return z[c] s if!m;s[c] z ``` First parameter is mode: 0 (or false) for Moses mode, 1 for push right (prepend), 2 for push left (append) Second parameter is an array of integers where 0 is considered the empty token (though all falsy values are considered empty, but will be replaced with 0). ### Version without Moses mode: 91 bytes = 0.11 points ``` x=(d,a)->o=a.filter((l)->''!=l);o[if d then'push'else'unshift'] ''while a.length-o.length;o ``` First parameter is a Boolean indicating whether to push right (`true` or any truthy value) or push left (`false` or any falsy value). Second parameter is the array. Empty tokens include empty strings. [Answer] ## PHP - 176 bytes, 1.06 points ``` function x($m,$d){$c=count;$y=array_merge;$s=array_filter($d);$z=array_fill(0,$c($d)-$c($s),0);if(!$m)array_splice($s,$c($s)/4+1,0,$z);return!$m?$s:(--$m?$y($z,$s):$y($s,$z));} ``` Where `$m` is: * 0: Moses mode * 1: Append (push left) * 2: Prepend (push right) And `$d` is the an array of numeric where 0 or 0.0 is considered empty. There are notices for undefined constants but they still work. [Answer] # [rs](https://github.com/kirbyfan64/rs), 41 bytes ``` +(.)(\d+)_(\d+)/\1_\2\3 l(_+)(.+)/\2\1 r/ ``` Takes input as a sequence of numbers, with `l` for left, `r` for right, and the underscore as the null character, e.g. `r_3_12`. [Live demo here](http://kirbyfan64.github.io/rs/index.html?script=%2B(.)(%5Cd%2B)_(%5Cd%2B)%2F%5C1_%5C2%5C3%0Al(_%2B)(.%2B)%2F%5C2%5C1%0Ar%2F&input=r_3_12%0Al1_49_). [Answer] # k2, 28 bytes ``` {,/ :[y;|:](x@&~x=0;x@&x=0)} ``` I already have another answer, and there's another K answer (for k3), but I believe this one uses a vastly different approach, IMO. 0 is used as the null value. Two unfortunate issues: 1. k2 has no binary vectors. 2. #1 makes this one *really* long. Usage: ``` {,/ :[y;|:](x@&~x=0;x@&x=0)}[1 1 0 1 2 3 0 1;1] / outputs 0 0 1 1 1 2 3 1 {,/ :[y;|:](x@&~x=0;x@&x=0)}[1 1 0 1 2 3 0 1;0] / outputs 1 1 1 2 3 1 0 0 ``` Now, if I am allowed to use just 1 and 0 as my input, I can get much shorter, but then it ends up being almost the same thing as the other K answer. So...yeah. This sucks. :( [Answer] > > Some have mentioned above that wordy languages can't participate because of the restriction in byte count. I doubt it. Here's a python solution, and I think python is a wordy language, somewhat golfed. > > > # Python 2.7 ### 68 bytes, 0.15 points ### 62 bytes, 0.16 points (thanks to @Sp3000) ``` d,s=input();e=filter(None,s),[0]*s.count(0) print e[d]+e[d+1] ``` ### input/ouput ``` 0 for right, -1 for left, list of numbers as sequence. 0 is the null character >>>0, [1, 0, 2, 3, 6, 0, 0, 0, 5] [1, 2, 3, 6, 5, 0, 0, 0, 0] >>>-1, [1, 0, 2, 3, 6, 0, 0, 0, 5] [0, 0, 0, 0, 1, 2, 3, 6, 5] ``` [Answer] # Perl - 103 bytes, 1.09 points ``` $_=<>;s/\n//;$b='_'x s/_//g;$x=length($_)/2;print(($b.$_,$_.$b,(substr($_,0,$x).$b.substr$_,$x))[<>+0]) ``` The sequence is a string. The null element is an underscore character. It reads the string as a line from the standard input, then reads the direction as another line: `0` for right, `1` for left, `2` for Moses mode. ## Version without Moses Mode - 49 bytes, 0.20 points ``` $_=<>;s/\n//;$b='_'x s/_//g;print<>+0?$_.$b:$b.$_ ``` Same as the above except shorter and without Moses mode implemented. ]
[Question] [ **This question already has answers here**: [We're no strangers to code golf, you know the rules, and so do I](/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) (73 answers) Closed 7 years ago. Your program must print out the [Gettysburg Address](https://en.wikipedia.org/wiki/Gettysburg_Address#Text_of_Gettysburg_Address). I copied this text from Wikipedia: > > Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. > Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. > But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth. > > > There are two different tests: 1. You may use system decompression software 2. No using system decompression software Additionally, none of the words in the Address can appear in plain text in your code (with a non-alpha character before and after). Shortest code wins. Good luck! [Answer] # Mathematica 40 **Note**: Not to be taken as a serious answer. ;) Just for fun: ``` ExampleData@{"Text","GettysburgAddress"} ``` > > Four score and seven years ago, our fathers brought forth upon this > continent a new nation: conceived in liberty, and dedicated to the > proposition that all men are created equal. Now we are engaged in a > great civil war...testing whether that nation, or any nation so > conceived and so dedicated. . . can long endure. We are met on a > great battlefield of that war. We have come to dedicate a portion of > that field as a final resting place for those who here gave their > lives that this nation might live. It is altogether fitting and > proper that we should do this. But, in a larger sense, we cannot > dedicate...we cannot consecrate... we cannot hallow this ground. The > brave men, living and dead, who struggled here have consecrated it, > far above our poor power to add or detract. The world will little > note, nor long remember, what we say here, but it can never forget > what they did here. It is for us the living, rather, to be dedicated > here to the unfinished work which they who fought here have thus far > so nobly advanced. It is rather for us to be here dedicated to the > great task remaining before us...that from these honored dead we take > increased devotion to that cause for which they gave the last full > measure of devotion... that we here highly resolve that these dead > shall not have died in vain...that this nation, under God, shall have > a new birth of freedom...and that government of the people, by the > people, for the people, shall not perish from this earth. > > > [Answer] ## Tcl, 759, no compression ``` puts [encoding convertt unicode 潆牵猠潣敲愠摮猠癥湥礠慥獲愠潧漠牵映瑡敨獲戠潲杵瑨映牯桴漠桴獩挠湯楴敮瑮愠渠睥渠瑡潩Ɱ挠湯散癩摥椠楬敢瑲ⱹ愠摮搠摥捩瑡摥琠桴⁥牰灯獯瑩潩桴瑡愠汬洠湥愠敲挠敲瑡摥攠畱污‮潎⁷敷愠敲攠杮条摥椠⁡牧慥⁴楣楶慷Ⱳ琠獥楴杮眠敨桴牥琠慨⁴慮楴湯‬牯愠祮渠瑡潩潳挠湯散癩摥愠摮猠敤楤慣整Ɽ挠湡氠湯⁧湥畤敲‮敗愠敲洠瑥漠⁡牧慥⁴慢瑴敬楦汥⁤景琠慨⁴慷⹲圠⁥慨敶挠浯⁥潴搠摥捩瑡⁥⁡潰瑲潩景琠慨⁴楦汥Ɽ愠⁳⁡楦慮敲瑳湩⁧汰捡⁥潦⁲桴獯⁥桷敨敲朠癡⁥桴楥⁲楬敶⁳桴瑡琠慨⁴慮楴湯洠杩瑨氠癩⹥䤠⁴獩愠瑬杯瑥敨⁲楦瑴湩⁧湡⁤牰灯牥琠慨⁴敷猠潨汵⁤潤琠楨⹳䈠瑵‬湩愠氠牡敧⁲敳獮ⱥ眠⁥慣潮⁴敤楤慣整‬敷挠湡渠瑯挠湯敳牣瑡ⱥ眠⁥慣潮⁴慨汬睯琠楨⁳牧畯摮‮桔⁥牢癡⁥敭Ɱ氠癩湩⁧湡⁤敤摡‬桷瑳畲杧敬⁤敨敲‬慨敶挠湯敳牣瑡摥椠ⱴ映牡愠潢敶漠牵瀠潯⁲潰敷⁲潴愠摤漠⁲敤牴捡⹴吠敨眠牯摬眠汩楬瑴敬渠瑯ⱥ渠牯氠湯⁧敲敭扭牥眠慨⁴敷猠祡栠牥ⱥ戠瑵椠⁴慣敮敶⁲潦杲瑥眠慨⁴桴祥搠摩栠牥⹥䤠⁴獩映牯甠⁳桴⁥楬楶杮‬慲桴牥‬潴戠⁥敤楤慣整⁤敨敲琠桴⁥湵楦楮桳摥眠牯桷捩⁨桴祥眠潨映畯桧⁴敨敲栠癡⁥桴獵映牡猠潮汢⁹摡慶据摥‮瑉椠⁳慲桴牥映牯甠⁳潴戠⁥敨敲搠摥捩瑡摥琠桴⁥牧慥⁴慴歳爠浥楡楮杮戠晥牯⁥獵琭慨⁴牦浯琠敨敳栠湯牯摥搠慥⁤敷琠歡⁥湩牣慥敳⁤敤潶楴湯琠桴瑡挠畡敳映牯眠楨档琠敨⁹慧敶琠敨氠獡⁴畦汬洠慥畳敲漠⁦敤潶楴湯琭慨⁴敷栠牥⁥楨桧祬爠獥汯敶琠慨⁴桴獥⁥敤摡猠慨汬渠瑯栠癡⁥楤摥椠慶湩琭慨⁴桴獩渠瑡潩Ɱ甠摮牥䜠摯‬桳污慨敶愠渠睥戠物桴漠⁦牦敥潤⵭湡⁤桴瑡朠癯牥浮湥⁴景琠敨瀠潥汰ⱥ戠⁹桴⁥数灯敬‬潦⁲桴⁥数灯敬‬桳污潮⁴数楲桳映潲桴⁥慥瑲⹨] ``` [Answer] # Python 2.7, no decompression, 962 characters `"eJxlVEGO2zAM/AofYOQRPbTopacCPdMWbQsri6kk28jvOxTjbNpegliiyJnhkF91L1QnLUKcA1U5JNNDuFTiRcluZ26r4Hssui9ro1lLW0kztTVWmjS3mCU3YspyUuYWNQ92Pkk8JFDMlOIopT2GXiNIiBM33DRFDqF70bvWaO/wzciUEm3AwUA1Femx8nvndKMfetIp/UbywovnZ1osjKZ4xEQnl4GaVOBa6FzF4HviC5wWIHk8P6nqG9qugn6CBBMGAUUqyWEvcqNfXn+TZipctUduLckcJQXS2esBSQ9f+QAT3cQoX6nx8g4pDcEV319DJYiP/5kTlSeNe+JJTHoEahXQUgItocVSg2EsUPmQ6one2NIWrWt2eaPvjdAzTk0Xl2WOrec32taHSyloXFfdwSVob/SNvuxtcLETlwWBVXKVwUJNoqztRe2vQ2hbZSr/Hq/oMprZTbTAWjnc6CfcMBZjhPYPhvnCFoQhjLGurezLktAq4z9c2l414AfAnBkdHhU35uC7qv2cRk6JQzADBGmFp+ZFTy2gekYYL0Xro0FE8ozA3vsim2wwMSA81eHHE8C4Q9TmvDA+xboEdT0SIj8oRAd76W9t3Gv3vlMcqPQhGwzfKG8j0nv8nJM9wxOxrjgG3g8UiNPqFUyY2cezv1jdFShiSsDPWcf0APWDYfRwAfGqLzy9dn//34y6xxvXD5OCgQOijDLb4tjr8LRv0c2i4c9VIZ1430yuxh8C89g01358qM+7+tOJ9+r+fmN1eRuGq8i+97XAFUNoE3PlGF6OdeqwO6hicDT1596FKo6lmu+eBsR1iL5BDlAarmAoc20K2BICfVOYz1/2V77qxtgX4QzeIkE3X289xwLrlbzZWuyzjSUnek/mlsdfnz7Rn9+f8DCK6PVLU8JObuvtD0gQCHY=".decode('base64').decode('zlib')` **For fun, Python 2.7, no decompression, 1470 characters** ``` "Sbhe fpber naq frira lrnef ntb bhe snguref oebhtug sbegu ba guvf pbagvarag n arj angvba, pbaprvirq va yvoregl, naq qrqvpngrq gb gur cebcbfvgvba gung nyy zra ner perngrq rdhny. Abj jr ner ratntrq va n terng pvivy jne, grfgvat jurgure gung angvba, be nal angvba fb pbaprvirq naq fb qrqvpngrq, pna ybat raqher. Jr ner zrg ba n terng onggyrsvryq bs gung jne. Jr unir pbzr gb qrqvpngr n cbegvba bs gung svryq, nf n svany erfgvat cynpr sbe gubfr jub urer tnir gurve yvirf gung gung angvba zvtug yvir. Vg vf nygbtrgure svggvat naq cebcre gung jr fubhyq qb guvf. Ohg, va n ynetre frafr, jr pna abg qrqvpngr, jr pna abg pbafrpengr, jr pna abg unyybj guvf tebhaq. Gur oenir zra, yvivat naq qrnq, jub fgehttyrq urer, unir pbafrpengrq vg, sne nobir bhe cbbe cbjre gb nqq be qrgenpg. Gur jbeyq jvyy yvggyr abgr, abe ybat erzrzore jung jr fnl urer, ohg vg pna arire sbetrg jung gurl qvq urer. Vg vf sbe hf gur yvivat, engure, gb or qrqvpngrq urer gb gur hasvavfurq jbex juvpu gurl jub sbhtug urer unir guhf sne fb aboyl nqinaprq. Vg vf engure sbe hf gb or urer qrqvpngrq gb gur terng gnfx erznvavat orsber hf—gung sebz gurfr ubaberq qrnq jr gnxr vapernfrq qribgvba gb gung pnhfr sbe juvpu gurl tnir gur ynfg shyy zrnfher bs qribgvba—gung jr urer uvtuyl erfbyir gung gurfr qrnq funyy abg unir qvrq va inva—gung guvf angvba, haqre Tbq, funyy unir n arj ovegu bs serrqbz—naq gung tbireazrag bs gur crbcyr, ol gur crbcyr, sbe gur crbcyr, funyy abg crevfu sebz gur rnegu.".encode('rot13') ``` [Answer] ## Perl, 932 bytes (no system decompression) This entry is not a UTF-8-encoded file. Perl 5 uses 8-bit characters as its default character set for scripts. Since the website does use UTF-8, I'm posting a base64-encoded version of my submission: ``` c3ViIGJ7JCRfP2IoQCQkXyk6cHJpbnQgZm9yQF99c3ViIGF7JHtjaHIoKX09W3BvcCxwb3BdZm9y IDE0OS4uMjU1OyZifWEiRpjQY/P71K123iB5Zepz3GfAmOthxHO7ctivvfog9fbBynTy3vlhlneq 98qg16LMaWL8dHn31JvounLCb3O/5tth/yCuIKZj7PHvZXF1/eNOsiDgpt6cZ6LcIJpj12lsIHfq 93S2peFlxNtuzvfa8Hmq0MDKoNfv1HPA0WW3zcz12d5kdezjV/ump/n13CCaYvF0bGVmaWWfx9t3 6uNX+8VjuPvoINH7YSBw87Ugx9tmaWVst8/c6/L9IOxzpXBsYWP7vfZvc/vhwMic6fplaXLM17bb 1W7OIG1pr5dlncH96GdlxOu/pdRwcsL82+BzaNifZG/25+NC/vfy3MzqZ/zQ3nOe0Z7KrWNy8Z68 svbBZ3LYbmTjVGj7Yr7prveXxtSkt+Fv0HRydWdnbO/d5cXKrWNy8e+/92bq3GJv6ZggcG/acLL8 s9xk+NrudL5jdONUaPt38593af/Mv3Rs+25vdOVu2mz12eynbWL8IOH04HNhyd3lYv4gafnNlnb8 6/NnZfnh9PqV3/jdZZ3n69rD4pfyZ/e+xPfou/ubyOjidW5m8udo73fzayDhaWNo9pXhb+vYr8jF +sPr6tBv0mJsedxkdvCgZJ3BvsTr2sOzu/vIm+jimnTPayDsbWHyxmJlvfvDmWZyuPa2+2j18++k +OB0YWv78mPsz+/udm+1s9tjYcP7ZtrhaWNo9pWc6fr7bM/5ZnX/IKfPdXL7xyDudm+1meDIaGm5 bMnsc29s6dX6tvuk+KvLxd+iIHZh8pn656r3dW5k/CBHb7erIMVhlne7aXL6IMfr7GVkuC3U1Wdv dvxurvnHo2J5o72jq8tw/Odo63K44mXq+i5sbHR1bGFyZSBlaHQgdCBkICz6IG5v+WFyb25pdGFu YfhlZWRuIGVyZiByYft2b3RzafVp92VhaCAu+/Zod/t3aWRuZfxoYSD09iDzIGd1b3ZpY9/0+vjw 8dZv7dPucyBzYebx8GNsIPnS9WMgefvdZm/Z8unk/PpzdXBvIOcgb3RpYXLzZv/kYiBw4mhnbW/3 ZHNl5nTCZeggd2/lbLS6+bnebWVzzeC8c87trOX07GVt++rGdGHusbDy70njZWP4bMup+aFhZ+/R qGfVLXLY12xl7cllIj1+Ly4vZ3M= ``` This is what the script looks like with the non-ASCII characters replaced with question marks, and some line breaks added for readability: ``` sub b{$$_?b(@$$_):print for@_}sub a{${chr()}=[pop,pop]for 149..255;&b} a"F??c????v? ye?s?g???a?s?r???? ????t???a?w???????ib?ty?????r?os???a? ? ?c???equ??N? ???? g?? ?c?il w??t???e??n????y????????s??e??????du??W?????? ?b?tlefie???w??W??c??? ??a p?? ?? fiel?????? ?s?plac???os???????eir?????n? mi??e????ge?????pr????sh??do???B??????g???s????? cr??????gr?nd?Th?b??????????o?truggl??????cr????f??bo?? po?p????d???t?ct?Th?w??wi???tl?no t?n?l????mb? ???sa???b? i???v???ge????????e????????g???????????unf??h?w?k ?ich???o??????? ???o?bly?dv??d???????????????t?k ?ma??be????fr????h??????tak??c????vo???ca??f??ich??????l ??fu? ??ur?? ?vo????hi?l??sol???????????? va??????und? Go?? ?a?w?ir? ???ed?-??gov?n????by ?????p??h?r??e??.lltulare eht t d ,? no?aronitana?eedn erf ra?votsi?i?eah .??hw?widne?ha ?? ? guovic???????o???s sa???cl ???c y??fo??????supo ? otiar?f??b p?hgmo?dse?t?e? wo?l??? ??mes???s??????em???ta?????I?ec?l????ag???g?-r??le??e"=~/./gs ``` As @Howard mentioned, this doesn't add much to previous kolmogorov-complexity golf challenges. My encryption scheme, sometimes referred to as "re-pair compression" is one I've used [before](https://codegolf.stackexchange.com/a/5801/4201) so I won't go into details again here. In short, it's not a very efficient compression scheme, but it has the advantage of requiring very little code for the decompressor. The compressed string itself occupies 638 characters. (The period near the start of the third-to-last line is where the compressed string ends in the source code quoted above.) The remaining 214 characters of the string is the compression dictionary, leaving 80 characters that make up the Perl script proper. ]
[Question] [ To dynamically include a JavaScript file in a web page, you'd normally insert a `<script>` tag pointing to your script. For example: ``` var js_file= document.createElement("script"); js_file.src='http://example.com/js.js'; document.body.appendChild(js_file); ``` Write JavaScript code will load an external JavaScript file in the current page and: * Shortest valid answer wins * The file is hosted on `https://pastebin.com/raw/rV6dDDj9` (content is `console.log('Good job!');`) * The code must be vanilla JavaScript (no jQuery, etc.) * Answer validity test is done in the web browser console. Criteria: + URL requested and JS file downloaded. + Console prints `Good job!` [Answer] ## 49 bytes ``` document.write`<script src=//v.ht/KvtI></script>` ``` no one clearly said: you should keep current page content [Answer] ## ~~77~~ ~~75~~ 71 bytes ``` with(document)body.appendChild(createElement`script`).src=`//v.ht/Xa33` ``` Edit: Saved 2 bytes thanks to @jrich. Saved 4 bytes thanks to @Bálint. [Answer] # 75 bytes ``` document.body.appendChild(document.createElement`script`).src="//v.ht/Xa33" ``` @Neil's answer was quite similar to this, but he found an ingenious shortcut involving `with(...)`. I will not copy it here, because he came up with it. Thanks to @Bálint for the short URL. [Answer] ## 72 bytes `(D=document).body.appendChild(D.createElement`script`).src="//v.ht/Xa33"` for using more than once(3 call): 92 then always 36 `(D=document)[B="body"][A="appendChild"](D[C="createElement"](s="script")).src="//v.ht/Xa33"; D[B][A](D[C](s)).src="//v.ht/Xa33"; D[B][A](D[C](s)).src="//v.ht/Xa33"` 93 then always 35 `D=document,B=D.body,B.a=B.appendChild,D.c=D.createElement; B.a(D.c`script`).src="//v.ht/Xa33"; B.a(D.c`script`).src="//v.ht/Xa33"; B.a(D.c`script`).src="//v.ht/Xa33";` 99 then always 30 `D=document,B=D.body,B.a=B.appendChild,D.c=D.createElement,s="script"; B.a(D.c(s)).src="//v.ht/Xa33"; B.a(D.c(s)).src="//v.ht/Xa33"; B.a(D.c(s)).src="//v.ht/Xa33";` 99 then always 26 `D=document,A=e=>D.body.appendChild(e),C=e=>D.createElement(e),s="script"; A(C(s)).src="//v.ht/Xa33"; A(C(s)).src="//v.ht/Xa33"; A(C(s)).src="//v.ht/Xa33";` 87 then always 15 `S=e=>document.body.appendChild(document.createElement("script")).src=e; S`//v.ht/Xa33`; S`//v.ht/Xa33`; S`//v.ht/Xa33`;` 88 then always 22 `S=e=>document.body.appendChild(document.createElement("script")); S().src="//v.ht/Xa33"; S().src="//v.ht/Xa33"; S().src="//v.ht/Xa33";` [Answer] ## 89 bytes ``` n=[];for(i in d=document)n.push(i);d.body[n[173]](d[n[41]]`script`).src=`//goo.gl/rPQ0Jk` ``` This is **incredibly** browser-dependent. Actually even worse than that, it pretty much only works on codegolf.stackexchange.com, in the browser console, in FireFox. Ah well. Please don't get too mad when it (likely) doesn't work on your particular browser configuration, since if it is even slightly different from mine it could fail. (yeah, probably invalid because of that. Not going to win anyway.) ]
[Question] [ Mary has given John two sticks of lengths `a` and `b` respectively, where `a` and `b` are positive integers. John is very curious. He would like to know how many triangles with integer perimeter can be formed, by having one additional side. Please help him find it out. (This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.) # Specs * Given two integers `a` and `b`, find the number of triangles with integer perimeter that can be formed, by having one additional side. # Details * Congruent triangles are congruent. * Flat triangles are flat out uncounted. * Zero-sided triangles are counted zero times. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins. # Testcases ``` a b output 1 2 1 3 3 5 9 7 13 ``` [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly/), 3 bytes ``` «Ḥ’ ``` [Try it online!](http://jelly.tryitonline.net/#code=wqvhuKTigJk&input=&args=Nw+OQ) ### Explanation ``` « min(a,b) Ḥ *2 ’ -1 ``` (Not quite rigorous) proof of correctness: * Let **x = min(a,b)** and **y = max(a,b)**, and let **z** be a potential third side. * We can't have **z ≤ y-x**, because for **z < y-x** the triangle can't be closed and for **z = y-x** it would be degenerate. [See triangle inequality.](https://en.wikipedia.org/wiki/Triangle_inequality#Mathematical_expression_of_the_constraint_on_the_sides_of_a_triangle) * We can't have **z ≥ y+x**, for the same reasons. * Every integer **z** in between is valid and gives a different triangle. That means we've got **(y+x) - (y-x) - 1 = 2x - 1** different triangles. [Answer] ## CJam, 7 bytes ``` l~e<2*( ``` [Test it here.](http://cjam.aditsu.net/#code=l~e%3C2*(&input=9%207) ### Explanation ``` l~ e# Read and evaluate input. e< e# min(a,b). 2* e# Double. ( e# Decrement. ``` For a proof of correctness, [see my Jelly answer](https://codegolf.stackexchange.com/a/79015/8478) which uses the same algorithm. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes Using [@MartinBüttner's algorithm](https://codegolf.stackexchange.com/a/79015/34388). Code: ``` ·<ß ``` Explanation: ``` · # Double the input. < # Decrement by 1. ß # Take the smallest value. ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrc8w58&input=WzksIDdd). [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 20 bytes Thanks to Sp3000 for some help while golfing this. ``` <""-}:?:? "` { ++(!@ ``` [Try it online!](http://labyrinth.tryitonline.net/#code=PCIiLX06Pzo_CiJgCnsKKysoIUA&input=NyA5) ### Explanation It turns out that the `2*min(a,b)-1` approach isn't the shortest in Labyrinth. Instead it's easier to compute `(a+b)-|a-b|-1`. Labyrinth primer: * Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros. I will usually represent these like `Main [... a b | c d ...] Aux`, where `Main` grows to the right, `Aux` grows to the left and `...` represents the implicit zeros at the bottom. * The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends. * The source code can be modified at runtime using `<>^v` which cyclically shift a row or column of the grid. The code starts on the `<` which immediately modifies the source code. This is a common golfing trick in Labyrinth whenever a program starts with a long-ish bit of linear code. Afterwards, the source looks like this, with the IP still on the `<`: ``` ""-}:?:?< "` { ++(!@ ``` Since the IP is now in a dead end, it has to start moving left. The linear code does the following: ``` Op Explanation Stacks ? Read integer a from STDIN. Main [... a | ...] Aux : Duplicate. Main [... a a | ...] Aux ? Read integer b from STDIN. Main [... a a b | ...] Aux : Duplicate. Main [... a a b b | ...] Aux } Move b over to aux. Main [... a a b | b ...] Aux - Subtract b from a on main. Main [... a (a-b) | b ...] Aux ``` The code now enters the only nonlinear part of the code which compues `-abs(x)`, (where I'm now using `<` and `v` to indicate entry and exit points): ``` ""< "` v ``` The `"` is a no-op (i.e. it does nothing), whereas the ``` multiplies the top of the main stack by `-1`. Let's go through the three possible cases of control flow: * If `a == b`, i.e. `a-b` is zero, the IP keeps moving west on the first `"`. Then it hits a corner on the the second `"` and has to turn south. Again, it keeps moving south on the third `"` and leaves this 2x2 block. All in all, nothing happens to zeros at all. * If `a > b`, i.e. `a-b` is positive, the IP turns south on the first `"`. The ``` then switches the top of the main stack to `b-a` and the IP has to take a turn west. On the next `"` the top of the stack is now negative, and the IP turns south. Therefore, if the top of the stack is positive, its sign will be negated by this block. * If `a < b`, i.e. `a-b` is negative, then the IP also turns towards the ``` , which now makes it positive. That means the IP turns *north* on the next no-op. It hits the corner and turns east, and turns south once more so that it reaches the ``` a second time. At this point, the control flow is no different from a positive input, so after applying ``` twice, we're back at `a-b` which is negative and leaves the loop. Despite doing a lot more stuff, negative inputs are also unaffected by this part of the code. Now that we've computed `-abs(a-b)`, the remainder of the code is all linear again: ``` Op Explanation Stacks [... a -|a-b| | b ...] { Move b back to main. [... a -|a-b| b | ...] + Add. [... a (-|a-b|+b) | ...] + Add. [... (a+b-|a-b|) | ...] ( Decrement. [... (a+b-|a-b|-1) | ...] ! Print as integer. [... | ...] @ Terminate program. ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 18 ~~19~~ bytes Not overly short, but a tad more interesting to do due to a lack of a minimum function. Saved a byte with a big thanks to Martin Büttner ``` -@IOIU>wu+..U;?;2* ``` This wraps onto a cube with edge length 2 and ends up looking like this ``` - @ I O I U > w u + . . U ; ? ; 2 * . . . . . . ``` Explanation that hopefully can be followed. [Try it here](https://ethproductions.github.io/cubix) Getting parameters from STDIN ``` - # This section gets input, u-turns onto top face, I # heading up, gets another input and performs a subtraction. I U # Carries on around the bottom of the cube upto the next part. ``` Determine least and leaving it at TOS ``` > w # Hits the ? going up. if TOS is negative turn left, pop stack U ; ? ; # and U-turn onto bottom face heading back up to ?. . # If 0 redirect through > and w to ; popping stack, heading right. . # If positive redirect right to ; which pops TOS ``` Output the answer and end ``` @ # Push 2 onto the stack, multiply, U-turn onto input which O # gives us -1 for the stack, add it then u-turn to the left I u + # onto the top face, output the TOS as number and end U 2 * ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 14 bytes ``` M!`(1+) \1 1 ``` Input and output in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqCiUoR2AKTSFgKDErKSBcMQogMQoKJSlgMSsKJC4m&input=MSAyCjMgMwo5IDc) (Modified to run multiple decimal test cases at once.) ### Explanation Still the same approach as my CJam and Jelly answers ([the latter](https://codegolf.stackexchange.com/a/79015/8478) contains a proof of correctness), but this time using string processing of unary representations. ``` M!`(1+) \1 ``` This finds `min(a,b)` by matching the first string of `1`s that can be found in both of them. This being a match stage and using the `!` the result is actually `min(a,b) min(a,b)` since the entire match is written back. ``` 1 ``` This simply matches the separating a space and a single `1` and removes them. This leaves a string of `2*min(a,b) - 1` characters, which is the desired result. [Answer] # k (8 bytes) Using the `Jelly`/`CJam` algorithm ``` -1+2*min ``` e.g. ``` k)-1+2*(&). 10 10 19 ``` [Answer] # Java ~~55~~ 42 bytes ``` int c(int a,int b){return (a<b?a:b)*2-1);} ``` [Answer] # APL, 6 bytes ``` 1-⍨2×⌊ ``` This is a dyadic function train that accepts integers on the right and left and returns an integer. It uses the 2 min(*a*, *b*) - 1 approach. [Try it here](http://tryapl.org/?a=f%u21901-%u23682%D7%u230A%20%u22C4%201%20f%202%20%u22C4%203%20f%203%20%u22C4%209%20f%207&run) (includes all test cases) [Answer] # Javascript full program ~~88~~ 42 bytes ``` a=prompt();b=prompt();alert((a<b?a:b)*2-1) ``` I hate prompts, even java is better in that aspect. # Javascript function ~~73~~ ~~31~~ 21 bytes ``` (a,b)=>(a<b?a:b)*2-1 ``` Testable version: ``` c=(a,b)=>(a<b?a:b)*2-1 var d = prompt("enter first number"); var e = prompt("enter second number"); alert(c(d, e)); ``` Thanks to @Neil for saving 8 bytes. Thanks goes to @MartinBüttner for the algorithm and for saving 1 byte. [Answer] ## Actually, 3 bytes ``` mτD ``` [Try it online](http://actually.tryitonline.net/#code=bc-ERA&input=MSwy) or [verify all test cases at once](http://actually.tryitonline.net/#code=YGltz4REPWBN&input=W1tbMSwyXSwxXSxbWzMsM10sNV0sW1s5LDddLDEzXV0) This uses the same `2*min(a,b)-1` approach that basically every other solutions uses. Each operation (minimum, double, decrement) is its own single-byte command. [Answer] # J, 7 bytes ``` 1-~2*<. ``` This is a tacit verb. ``` 1-~2*<. 1-~ reflexive minus (i.e. R - 1) 2* double <. lesser of ``` [Answer] # Jolf, 4 bytes ``` m±♀j ``` Replace ♀ with a literal `\x12` byte, or [try it here](http://conorobrien-foxx.github.io/Jolf/#code=bcKxDGo&input=MwoKNg)! ## Explanation ``` m±♀j ♀j min of j and implicit input m± 2*(^)-1 ``` [Answer] # PHP 36 bytes ``` function($a,$b){echo min($a,$b)*2-1} ``` Thanks goes to @MartinBüttner for the algorithm [Answer] **C# 6.0 - 34 bytes** ``` int a(int b,int c)=>(b<c?b:c)*2-1; ``` ]
[Question] [ In this challenge you will take a non-empty (finite) list of (possibly infinite) lists of positive integers, and your task is to output the longest one. An infinite list is longer than a finite list of any length, and any two infinite lists are equally long. You're guaranteed that there won't be any ties for longest between two distinct lists. That is, if two lists are tied for longest, whether they are finite or infinite, they will be equal so it won't matter which one you output. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply for outputting an infinite list. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The goal is to minimize the size of your source code as measured in bytes. A useful note from xnor: > > I think it's important for solvers to realize that you have to be outputting list entries as you go in some situations. There's no hope to find which list is longest then fully output it. > > > ## Test cases ``` [1,1,1,1,1,1,1,1] [2,2,2] [] => [1,1,1,1,1,1,1,1] ``` ``` [1,1,1,1,1,1,1,1] [2,2,2,9,9,9,9,9,9] [] => [2,2,2,9,9,9,9,9,9] ``` ``` [1,2,3] [1,2,3] [2,4] => [1,2,3] ``` ``` [1,2,3,4,5,6,7,8,9,10,11,12,...] [1,2,3,4,5,6,7,8,12] [9,2] => [1,2,3,4,5,6,7,8,9,10,11,12,...] ``` ``` [2,6,4,5,6,7,8,9,10,11,12,13,...] [2,6,4,5,6,7,8,9,10,11,12,13,...] => [2,6,4,5,6,7,8,9,10,11,12,13,...] ``` ``` [2,6,4,5,6,7,8,9,10,11,12,13,...] [2,6,4,5] [9,8,12,3] => [2,6,4,5,6,7,8,9,10,11,12,13,...] ``` ``` [1,2,3,4,5,6,7,8,9,10,11,12,...] [1,2,3,4,5,6,7,8,9,10,11,12,...] [1,2,3,4,5,6,7,8,12] [9,2] => [1,2,3,4,5,6,7,8,9,10,11,12,...] ``` --- The following cases are examples of undefined behavior, you may do whatever you wish including looping forever. ``` [1,2,3] [1,2,3] [2,6,7] ``` ``` [2,4,6,8,10,12,14,16,...] [1,3,5,7,9,11,13,15,...] ``` [Answer] # [Python](https://www.python.org), ~~74~~ 74 bytes ``` f=lambda i,n,m=0:1<len(r:={x(n)for x in i if x(m)})and f(i,n,m+1)or sum(r) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9BDoIwEEXX9hSznNGawIKEELmAVzAuamixiR1JLQZivIIXcMNG7-RtBIKJuv3z5_3_78-qDfsjd92jDmaZvtYmPyi3KxRYydLlURavDprRZ_mlQSZz9NCAZbBgDTTo6EqKCzA4-hcx9YZT7dDTRLyxCpDDROWMF7HQttz_iMirlOapMPas__SE5onQrgrt9yESQxMemnjFpcY4okzMKm85oMHNAJJ9shw_5Ri4lUxTq8_eNw) Previous version had a bug Potentially infinite lists are represented as functions that take an index and return the value at that index. If the index is out of bounds the function returns a zero. [Answer] # [Haskell](https://www.haskell.org), ~~67~~ 58 bytes ``` foldl1(#) (a:b)#(x:y)|a==x=a:b#y c#z|(1<$c)>(1<$z)=c|0<1=z ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY3rdLyc1JyDDWUNbk0Eq2SNJU1KqwqNWsSbW0rbIF85UquZOWqGg1DG5VkTTsQVaVpm1xjYGNoWwUx4RaTXnJicWqxgpWVQnR0tGdeSWp6alFsbCwXRNhWIZpLAQggJJhlqIMCY3UQUkY6QIgsEAtmxuqQol_HEgEJm2WkY4ysCEPASMcEq0Y9PQxtOiY6pjpmOuY6FjqGKL6wBHoKixlGOmaxCtraCtEmqIahiJOmD-QEVJtBbgH6iAgvkOcjKMmVm5iZB4zt3MQC33gFjYKizLwSBT2FksTsVAVjAyArTVMBnCIgyWbBAggNAA) *-9 thanks to AnttiP mixing pattern failure and guard failure* Test harness truncates to run all the cases in one go, but it [can be run infinitely](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY3rdLyc1JyDDWUNbk0Eq2SNJU1KqwqNWsSbW0rbIF85UquZOWqGg1DG5VkTTsQVaVpm1xjYGNoWwUx4RaTXnJicWqxgpWVQnR0tGdeSWp6alFsbCwXRNhWIZpLAQggJJhlqIMCY3UQUkY6QIgsEAtmxuqQol_HEgEJm2WkY4ysCEPASMcEq0Y9PQxtOiY6pjpmOuY6FjqGKL6wBHoKixlGOmaxCtraCtEmqIahiJOmD-QEVJtBbgH6iAgvkOcjKMmVm5iZB4zt3MQC33gFjYKizLwSBT2FksTsVAVjAyArTVMBnCIgyWbBAggNAA). Since the algorithm may be non-obvious and not everyone can read Haskell: ## Explanation ``` foldl1 (#) ``` The function submission operating on a list of lists just reduces the list by a function of two lists, the infix operator `#`. (Since the input is guaranteed non-empty, `foldl1` won't error.) ``` (a:b) # (x:y) | a == x = a : (b # y) ``` The critical part for handling duplicate infinite lists: if the first element of both lists is the same, then put that element in the output list and recur on the remainders of both. ``` c # z | (1 <$ c) > (1 <$ z) = c | otherwise = z ``` And here's the part that actually takes the longest list, if the previous clause failed. Since one of the lists can still be infinite, an actual length comparison is out of the question, but replacing every element of both lists with 1, a lexicographic comparison will terminate as soon as it reaches the point where one list ends and not the other. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~124~~ 123 bytes Input is an array of `Enumerator`s. Zips answers together until enough of them reach the ends of their sequences that the ones that remain are all equivalent, prints that, and keeps going. ``` ->a{g=->{a.map{_1.next rescue p}};t=a;(t=g[] t=t.zip(g[]).map{_2&&[*_1,_2]}while(t&t-[p])[1] r,=t-[p];p *r)while(t-[p])[0]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVBLTsMwEBVbn2IkpDYJjhWnHxql6Y4bsLOsKLROidSmxrVVSpqTsKkQHApOg4nTBQuwpTcznnnyvPf6rszD8fxWZh9Gl-HsswkXRbPOwkVTkG0hm5ySWjxrUGK_NAJk26Y6K1JPZ2vGkc40eamkZ3PfjceDAQtyivOYt4fHaiM8PdAhk9xnlCOFs65IJQTK7_uuG_HWrfB1NVmJEqq6BHuugcV4isd4YvEWz3CCaYQpxTTGdIQJIRwB3NVmK1Shd8pue2hOx9NxPo9TsDhNYUz2WsjGFjltWyTqFUJKPJlKCRjqait2Rg_RvUtI_-BFJIomPqx2qCTLYrMBBp7VEMw6pfhnL3t5X3QROJJG7_8geD3jhiU8mPr_Eq167OCX_OTyXWKdsA6MLmyrybl3Prv4DQ) ##### Explanation ``` ->a{ # Lambda definition g=->{a.map{_1.next rescue p}} # Lambda to take the next element of each Enumerator # If it throws StopIteration, output nil instead t=a # Set t to a as dummy value for while loop ( # Start of instructions to loop over t=g[] # Overwrite t with the next elements # Start of a one-line while loop t= # Set t to t.zip(g[]) # t zipped with the next elements # (will look like this: [[1,2,3],4]) .map{ # Map over the zipped result _2 # If next element is nil, return just that && # Otherwise, [*_1,_2] # Combine the elements together } while(t&t-[p])[1] # Loop while at least 2 unique non-nil elements of t # Now we know which elements can be safely printed r,=t-[p] # Set r to first non-nil element of t p *r # Print all such elements one at a time )while(t-[p])[0] # Loop while at least one element of t is not nil } ``` ### [Ruby](https://www.ruby-lang.org/), 20 bytes, technically against the spirit of the challenge Input is an array of specific kinds of `Enumerator::Lazy` objects constructed from `Array`s or `Range`s, but not created manually with `Enumerator.new`. Returns an `Enumerator::Lazy` that can be iterated through later to print results. Finite arrays can be written simply as `[...].lazy`. (The function also accepts the arrays directly, but for the sake of the exercise everything is passed in uniformly so no class-checking is done.) Infinite arrays take the form of `(0..).lazy.map{...}`. For example, even numbers can be represented as `(0..).lazy.map{|i|i*2}`, the infinite array `[2,6,4,5,6,7,8,9,10,11,12,13,...]` in the examples can be written as `(0..).lazy.map{|i|i==1?6:i+2}`, and something more complicated like the Fibonacci sequence can use some custom function, e.g. `(0..).lazy.map{|i|SomeFunction(i)}` With this method, infinite arrays will have a `size` of infinity, and finite arrays will have a `size` equal to their length. (This is why I'm not allowing enumerators constructed with `Enumerator.new`, because they have a `size` of `nil`.) ``` ->a{a.max_by &:size} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWW3TtEqsT9XITK-KTKhXUrIozq1JrIVK3GPsKFNL0khNzcjSiuRQUog11UGCsXk5iVaUOSMZIBwiR-BCmQqymXkl-fCIXScboWCIgkUZqGOrpaSKUGgINMdYx0THVMdMx17HQMUR2miXMoWCjErNTNQxNIWYqaCtEq-vp6anHopluBDMdGEwF1fGGtrbG9mZW8Ya1OgrKIEebIdllqWNooGMI9JaRjqGxDtC0WPwmQLwNNoGgsyDRsmABhAYA) [Answer] # [Python](https://www.python.org), 146 bytes *Uses generators for IO, sadly much longer than the other Python solution* ``` def f(L): while(Q:=[[[],l]for l in L]): while(Q:=[(k+[q],l)for k,l in Q if(q:=next(l,0))])*(len({str(k)for k,l in Q})>1):0 yield from Q[0][0] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVHLTsMwELznK3zcLYuUlIdKpPQLesktkuUDoja14tqp66pUiJ_gyqUX-Cc-hRt2AlHpGWkP3p3RzKz37aM7hJWzx-P7LqjL2efrUiqmYIFlxvYrbSTUZcU5F2SEcp4Zpi1biASf4NBe8E2kYKK01JNqphVsysrKpwCGckSBEzDSwvM2eGj_cF9wXmCZR9GDlmbJlHdrVvNcxPpJ9tXPdJA-OGe2TK8758Mky5pKAX9wOxugQBofoFly0EmfFzSlK3E2PO-ndE23NKMbuhMxbDYi_t4-SijytHXnddTvl2oQs6HFIcQ_WjajlcbhA35P9A0) [Answer] # [R](https://www.r-project.org), 92 bytes ``` f=\(L,n,m=1,g=\(i)sapply(L,\(f)f(i)))`if`(sum(table(x<-g(n)[!!g(m)])|1)>1,f(L,n,m+1),max(x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lZDNasJAFIVxO08Rd_faG3BEMBSnT-Cie1Ni2swNA8lEmklJwTdxEwt9qPZpOiEqqN24mB8O53znzuwP790Xq-_GcRj9xKxiWJGlUknK_d1gnW63xacXY2BkLyBuDG-gbkpw6WuhoV2GOVhcj8c5lPiCO4lPknjgPEikMm2hRRw6fkfPldWJq5J5klWNB2SKG_vmTGU93fiKpZqjmcwCXdQ6mIqjfXFrW6A5m7JLzGQWSqE_tL1SBUNhagfXM9CphTypX0gRCnF8vXyUU2Jaqf-zwTkc9Ol-Q7w_2497f-70sV03nH8) Based on [AnttiP's answer](https://codegolf.stackexchange.com/a/265752/55372). Takes input as list of functions and index (1-based) of the output sequence. Functions take index and return sequence value or 0 if it's out of bounds. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 74 bytes ``` k=>f=(x,i=0)=>new Set(y=x.flatMap(c=>1/c(i)?c(k):[])).size>1?f(x,i+1):y[0] ``` [Try it online!](https://tio.run/##lYyxCsIwFEV3v8LxPYy1EVwqL926OTmGDCGm8mxpii3a@vOxWQTd5Cz3XrjnZh92cHfux20XLj5WFBtSNcEkmHIk1fnn@uxHmGnK6taOJ9uDIyV3DhhLBw0W2iBmA7@8kmWdjhuJxaxzE48rF7ohtD5rwxUqkAiaSWkpvjCajUj7Xix8WgqL@ldy@EfCSRDf "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org), ~~88~~ 76 bytes *Edit: -10 bytes by stealing some ideas from [pajonk's R answer](https://codegolf.stackexchange.com/a/265772/95126).* ``` \(l,g=\(n)sapply(c(l,l),\(f)f(n)))\(i){while(sd(x<-g(i)[g(T)>0]))T=T+1;x[1]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rVFNSsQwGMVtTxEQJJ-20BYE0YkncNnddCh1ktQPYjo0qZ1BPIYrN3XhocZreAHjtMO0OoKii_y9vO97Ly9Pz1W7fiy1yGyZWaGZrPXcYqkpAkqKExaFgEQoI0jobXmN0Hb1lRoPqZxnur69FpUZEY_jIPLEndDf3HqeKnUhjGUvtZXB2foqpcovWEo1mHyxUCs6d4ACP6USpEMBUld639ygEtRwupwEhQOmBU3gMpwBJCw5iS6W02j20PV8PXjrRTInzvo9VeimXRT-6LUA5JDYpiQSNVpBPsjG6x1F5_GpP2gJ3q_7-4PA9mqRXHM3COoedeV_0x_-wuiw0XfEoT452jhC7sziPFc7H_-QxMjJ5yD2G-EopaicmR8b6f6-bbv1HQ) Input as a list of functions that each return the `i`-th element of a (possibly finite, possibly infinite) list. Output is the function corresponding to the longest list. This could be [2 bytes shorter](https://ato.pxeger.com/run?1=nZHRSsMwFIbxtk8RECTRFNqCILr4AF73bh2lrif1QExHk9oN8TH0xpt64UPNpzGuHWvnBPUihPz583_nnLy-Ve36udSQ2jK1oIWs9dxiqSkylBQnIgwYElAGSOBtfQ1ou_pujYbWPE91fX8LlRkZTyM_9OAB9A-3nqdKXYCx4r220r9Y3yRUceSFSKhmJlss1IrOnaQYT6hk0qmMPTZ3qICanC4nfuGSpgWN2XUwYywW8Vl4tZyGs6cu8ePopY8JL6Nz3uO4EgqNpbtR8FG3jJFjYpuSSNRogXyZjfePID6YzMFQkuncLYK6V93zX4KGcx0dNiBnHILIyQaNuasK55naAf_S2wi539phYo5SQuWoe8Tue9q22z8B) if it's re-arranged to take an additional argument, `i`, and directly output the `i`-th element of the longest list indexed by the input functions (the I/O-format used by [pajonk's R answer](https://codegolf.stackexchange.com/a/265772/95126)). --- Original, **86-byte** approach is [here](https://ato.pxeger.com/run?1=rZHPSsQwEMbx2qcICCXjttAWBJGtxz6Cl-1SajPRgZgubWpZxMfw5KUefKj1NXwBs9vKtrqCoof8nS_z_TLz9Fx1m8dSY2bKzKCOZaMLQ6XmBCQ5zeMwAGKoamSB86FrUZv1V2k0lgqR6eb2Cqt6IjyJ_NDBO9TfRB1HlfoaaxO_NEb6Z5vLlCtIbfC-vSGFvBY8n_t1vlqpNS-48hR4KZdgCWYJALjuVrHIL4IlQBInM2unuFqUlcCK-zkswSZ76LO_Hr0NdpnFiIc9V2SnfVG8yb8B2DEzbckkaTLItuLaGYDC8-jUG6UE59f5vVHpDnqxXAs7GOnh1j7_m_-4H5PDzt8Kx_7M3RGRsLBU5GrP8Q-VmJB8LsRhEEFSYmVhfgzS977r-vUd). ]
[Question] [ 1. Given a word, get the indexes of each letter in the alphabet. For example: `uncopyrightable` becomes: `[21, 14, 3, 15, 16, 25, 18, 9, 7, 8, 20, 1, 2, 12, 5]` 2. Convert these indexes to the given numeral system. For example, if the radix is `36`, then the array above would become: `['l', 'e', '3', 'f', 'g', 'p', 'i', '9', '7', '8', 'k', '1', '2', 'c', '5']` 3. Joining those gives **`le3fgpi978k12c5`**. Of course you don't have to use arrays. More examples: * `dermatoglyphics`, `36` → `45id1kf7cpg893j` * `undiscoverability`, `8` → `25164112331726522121114112431` * `superacknowledgement`, `16` → `13151051213bef17c5475d5e14` --- * Your input will be a word (you decide if it'll be uppercase, lowercase or mixed) and a *valid* radix (2-36). * You can receive input through any of the standard IO methods. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! ([*very similar question here*](https://codegolf.stackexchange.com/q/239935)) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç96-IBlJ ``` -5 bytes thanks to *@ovs*. With string and integer inputs; and string output. Could be 1 byte less if we can output in uppercase by removing the `l`. [Try it online](https://tio.run/##yy9OTMpM/f//cLulma6nU47X//@leSmZxcn5ZalFQKmczJJKLgsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/D7ZZmuhFOOV7/df5HRyuV5iXnF1QWZaZnlCQm5aQq6RibxeooRCulpBblJpbkp@dUFmRkJhfDxUvzUjKLk/PLUouAhudkllQq6ViAJYpLC4Biydl5@eU5qSnpqbmpeSVKOoZmsbEA). An alternative for `Ç96-` is `Ask>`, if we take the input as a character-list: [Try it online](https://tio.run/##yy9OTMpM/f/fsTjbztMpx@v//2ilUiUdpTwgTgHiTCAuBuJkIM4H4jIgTgXiIiBOBOIkqJocKF0CxJVKsVwWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaPB/x@JsuwinHK//Ov@jo5VK85LzCyqLMtMzShKTclKVdIzNYnUUopVSUotyE0vy03MqCzIyk4vh4qV5KZnFyfllqUVAw3MySyqVdCzAEsWlBUCx5Oy8/PKc1JT01NzUvBIlHUOz2FgA). **Explanation:** ``` # Step 1: Convert the (implicit) input to their 1-based alphabetical index: Ç # Convert the (implicit) input-string to a list of codepoint integers 96- # Subtract 96 from each # OR A # Push the lowercase alphabet s # Swap so the (implicit) input-list is at the top of the stack k # Get the (0-based) index of each character in the alphabet > # And increase each by 1 to make it a 1-based index # Step 2: Convert it to the base of the second input, and output: IB # Convert it to the base of the second input l # Lowercase all letters, because `B` results in uppercase A-Z J # And join the list together to a string # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ⭆θ⍘⊕⌕βιIη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDglFqdCBDQ885KLUnNT80pSUzTcMvNSNJJ0FDI1NXUUnBOLSzQyNIHA@v//0ryUzOLk/LLUosSkzJzMkkoui/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input ⭆ Map over characters and join ⌕ 0-indexed index of ι Current character β In lowercase alphabet ⊕ Incremented i.e. 1-indexed ⍘ Convert to string base η Second input I Cast to integer ``` When given an integer base, the string base conversion uses the appropriate prefix of `0-9a-zA-z`. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes ``` ØaiⱮb‘ịØB ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLDmGFp4rGuYuKAmOG7i8OYQiIsIiIsIiIsWyJ1bmNvcHlyaWdodGFibGUiLCIzNiJdXQ==) -1 byte thanks to caird coinheringaahing [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` ""<>LetterNumber@#~IntegerString~#2& ``` [Try it online!](https://tio.run/##Tcm9CsIwEADg3aeQFJyyqFAcVLoKIoKjdEjS43qYn3K9KF366rFjtw@@YKSHYIScKXgpSp2vdxABfuRggZtqvkUBBH4JU8S5OuzKc5FsG3yrHF0aJibsxVgPSh/rdrPujkaXvsDGkieZlD6tf8zDUu4T089DhxAgitL7ui3lDw "Wolfram Language (Mathematica) – Try It Online") 87-36 bytes from @att [Answer] # [JavaScript (Node.js)](https://nodejs.org), 53 bytes Expects `(string)(radix)`. ``` s=>r=>Buffer(s).map(c=>s+=(c%32).toString(r),s='')&&s ``` [Try it online!](https://tio.run/##Xc5LbsMgFIXheVcRRWoCauv08rDTAR50C10B4VUSDBbgVFm9S6qOcodH@j/ds7zKorKf61tM2qxWrEWMWYyfi7Umo4K7Sc5IibG8CKSeKcFdTV81@@hQxq9F7Pd4tyurSrGkYLqQHLJoq02eZE0u3OZvr8oWI9pjvPm7w2HDuNdwsYOa3fGDnp8e6iVqX1S6mixPPvh6a/3xP2814dAzAEIpDKTnhAABgPvCKDxaZZkboy4x/QSjnZlMrI2D@zvNAgoc3nkT6MlYGBRnA9fcAFt/AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 20 bytes ``` mȯc+48?+7I>9ṁȯB⁰%32c ``` [Try it online!](https://tio.run/##yygtzv7/P/fE@mRtEwt7bXNPO8uHOxtPrHd61LhB1dgo@f///8Zm/1NSi3ITS/LTcyoLMjKTiwE "Husk – Try It Online") No easy `0-9A-Z` built into [Husk](https://github.com/barbuz/Husk), so 12 bytes used to roll our own. Main part: get the digit values in the given base ``` ṁȯ # map and flatten across input string c # get the character code %32 # modulo 32 (so A=1, B=2, ...) B⁰ # convert to digits in base given by input number ``` Helper function: convert digit values to 0,1,2,...9,A,B,C,...,Y,Z ``` mȯ # map over all digit values ? >9 # if it's bigger than 9 +7 # add 7 I # otherwise leave unchanged; +48 # then add 48 c # and convert to corresponding ASCII character ``` [Answer] # Java, 73 bytes ``` s->r->s.chars().mapToObj(c->r.toString(c%32,r)).reduce("",String::concat) ``` [Try it online!](https://tio.run/##hZBNS8QwEEDP218RCkIibUAXRHa1R8GDeFhv4iGbpN1080UyqRTZ316jLb3uXIaZN28GpmcDq3txnpTxLgDqc00TKE3bZDkoZ@ntvvDpqBVHXLMY0RtTFv0UKMfSj8Agp8EpgUym@ABB2e7zC7HQRZKHNy/LtqcZVWv9akF2MlRzv2lQ@zzFugl1Eyk/sRAxoYb5D/d@7DHPgIKbZzG/2d5XgRAapEhc4rJctux23FnOgEz7YnMYI0hDXQLqMwRtcUuZ93rEpZDBMHCdHv1J8ViSBWwfCLmiJitU5G6QgR2VVjCu8uNVNyafNX627ltL0UkjLaz63f/tv@9eisv0Cw) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` #`nUc)sV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=I2BuVWMpc1Y&input=InVuY29weXJpZ2h0YWJsZSIKMzY) [Answer] # [R](https://www.r-project.org/), 89 bytes ``` \(x,y)Reduce(paste0,sapply(el(strsplit(x,"")),\(z)cwhmisc::int2B(grep(z,letters),y))[1,]) ``` With `R < 4.1`, `\` needs to be replaced with `function` resulting in a total of 104 bytes. -5 bytes thanks to @pajonk. [Try it online!](https://tio.run/##PcyxDgIhDIDhVzFMbdJBHRl9BFfjQLB3kiA2tMTjXh6Zbv@/v46xtBItfQts1PHOrxYZJKjxmTSI5A6cQa2q5GQzcg6RDrRj/L0/SaP3qdj1BmtlgZ1Omc24Ks4pPi70xDH@ "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` C96-kr⁰Ẏ$vτ∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C96-kr%E2%81%B0%E1%BA%8E%24v%CF%84%E2%88%91&inputs=undiscoverability%0A8&header=&footer=) A bit messy but it works. ``` C # Charcodes 96- # -96 kr⁰Ẏ # 0-9a-zA-Z sliced to input length $vτ # Convert each to that base ∑ # Sum the result ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~57~~ 56 bytes ``` f(s,r)char*s;{for(;*s;*s+=*s<10?49:56,++s)*s-=65,*s%=r;} ``` [Try it online!](https://tio.run/##bVHrjppAFP6/TzElMUHAdJGLWtY2CixLZZV4aWOqaeg47JoiEoamtsZXX/YMF0O2hUDmfPNdzszBnSeM8zzkqZS28XOQCtQ4h8eUN2AhUHEo0Dv59pM6@KDpkijStkA7Q12TBNoapsYl38cZOgT7mG@j8w2Cp/BAGaEZ/bZFQ3TmVlNz5q/nrvOwHI09m5MQZ9nzx9Fy5nhr/8E1FwxaTS13Yc6@2PPR2PXc5ZqBi5UPtTmZzr56tuXYj/Z0yV2MIogls5jvaZmj6BJiX19Csl5xymbIKSE4I7uqH89W7h3fHfT6E7lraixH1VxLntz3TN/pD5TPDNJ0VVaUnq515a6swstARXOgVsY2UDW1p1mardb94GNMsyoRPxP8k1SNcZuT3d2cBiZ8RVqjVmo1XDni2ZH28Y6cQHZrVMs7RPd/yTHk62O031eAcEUMJIoFu55CYxLgVU6jIGyN6z5Li2CXZmlEYj5rG2@kP36FIewfgig6Yj5CIpIbHJDh5A/PSBJqiplvWqXCcN7GhpUk/SePgOg6q/91mwSUAucdiz4klQ9p@CQp0EKe23AtuoGrbu1Q5yMqKwS/GLAMoiVUaus5MeNt5XO5ueQvOIyCJ5p3fr8C "C (gcc) – Try It Online") *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs an uppercase string. Maps the string such that `A` -> `1`, `B` -> `2`, \$\dots\$, `J` -> `A`, `K` -> `B`, \$\dots\$ modulus radix \$r\$. ]
[Question] [ Find the shortest function/algorithm to translate these numbers to the ones after the dash: ``` 0 - 0 1 - 10 2 - 20 3 - 30 4 - 40 5 - 50 6 - 60 7 - 70 8 - 80 9 - 90 10 - 100 11 - 115 12 - 130 13 - 150 14 - 175 15 - 200 16 - 230 17 - 260 18 - 300 19 - 350 20 - 400 ``` Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4. Some examples (input will be between []): ``` [10] -> 100 [17] -> 260 [21] -> 4*115 -> 460 [32] -> 4*[22] -> 4*(4*130)) -> 2080 ``` ``` var QUESTION_ID=80271,OVERRIDE_USER=53878;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Python 2, 57 bytes ``` lambda n:5*[2*n,4**(n/10-1)*ord('‚ô•‚ô•‚ô•‚ô•#(.4<F'[n%10])][n>9] ``` Replace the four hearts with the ASCII characters 20 (`^T`), 23 (`^W`), 26 (`^Z`), and 30 (`^^`). [Answer] ## Python 3, 45 bytes ``` lambda n:[16*n,b'(.4<F'[n%5]<<n//5][n>9]//8*5 ``` Sticking to printable ASCII and int output. Uses that the values double every 5 steps, which can be computed with a bit shift. ``` 10 - 100 11 - 115 12 - 130 13 - 150 14 - 175 15 - 200 16 - 230 17 - 260 18 - 300 19 - 350 ``` So, for `n>9`, the output is `[20,23,26,30,35][n%5]<<n/5-2`. These values are doubled and packed in a printable ASCII bytearray. The `-2` in the bit shift is pushed to the outside to avoid a negative shift error when `n<=9` -- this is an ugly hack that can probably be handled better. [Answer] ## JavaScript (ES6), ~~64~~ 51 bytes ``` f=n=>n>15?f(n-5)*2:n<11?n*10:f(n-1)+5*"22344"[n-11] ``` Much simpler now that I'm also using @xnor's observation. [Answer] # Java, ~~93~~ 89 bytes ``` int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;} ``` A translation of the [answer in Python](https://codegolf.stackexchange.com/a/80274/48934) combined with the [answer in C++](https://codegolf.stackexchange.com/a/80277/48934), also inspired by [this answer in Python](https://codegolf.stackexchange.com/a/80298/48934). ## Full program: ``` public class Q80271 { int f(int n){String x="!$(-28>FP";return n<11?n*10:n<20?(x.charAt(n-11)-10)*5:f(n-10)*4;} public static void main(String args[]){ int[] testcases = new int[]{ 0,1,2,3,4,5,6,7,8,9, 10,11,12,13,14,15,16,17,18,19, 20,21,32 }; for(int i=0;i<testcases.length;i++){ System.out.println(new Q80271().f(testcases[i])); } } } ``` ## Output: ``` 0 10 20 30 40 50 60 70 80 90 100 115 130 150 175 200 230 260 300 350 400 460 2080 ``` [Answer] # Pyth, ~~47~~ 46 bytes 1 byte deletion inspired by [Python's deletion of the final item in the lookup table](https://codegolf.stackexchange.com/a/80274/48934). ``` J9L?gb20*4y-bT+?>bT*[[email protected]](/cdn-cgi/l/email-protection)+NYj6045983J1-bhT0*Tby ``` [Test suite.](http://pyth.herokuapp.com/?code=J9L%3Fgb20*4y-bT%2B%3F%3EbT*5%40.u%2BNYj6045983J1-bhT0*Tby&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A32&debug=0) ### Principle The lookup table I built is `[1, 2, 3, 3, 4, 4, 6, 8]`. If we start from `1`, and then add cumulatively that table: ``` 1 = 1 1+1 = 2 1+1+2 = 4 1+1+2+3 = 7 1+1+2+3+3 = 10 1+1+2+3+3+4 = 14 1+1+2+3+3+4+4 = 18 1+1+2+3+3+4+4+6 = 24 1+1+2+3+3+4+4+6+8 = 32 ``` ## Previous 53-byte solution: ``` L?tb+ytbeSmlf!%ydTSydStb1L?>b20*4'-bT+?>bT*5y-bT0*Tb' ``` This needs to be golf... very further. Maybe it would cost less to build a lookup table directly. [Test suite.](http://pyth.herokuapp.com/?code=L%3Ftb%2BytbeSmlf!%25ydTSydStb1L%3F%3Eb20*4%27-bT%2B%3F%3EbT*5y-bT0*Tb%27&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A32&debug=0) ### Principle If we subtract ten times the first number from the second number: ``` 115-110 = 5 = 5*1 130-120 = 10 = 5*2 150-130 = 20 = 5*4 175-140 = 35 = 5*7 200-150 = 50 = 5*10 230-160 = 70 = 5*14 260-170 = 90 = 5*18 300-180 = 120 = 5*24 350-190 = 160 = 5*32 400-200 = 200 = 5*40 ``` It corresponds with [A120679](http://oeis.org/A120679): `1,2,4,7,10,14,18,24,32,40,...` [Answer] ## PHP, 101 bytes ``` function f($i){$a=array(23,26,30,35,40,46,52,60,70);return $i<11?$i*10:$i<20?$a[$i-11]*5:f($i-10)*4;} ``` Huzzah for nested conditional operator! [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~32~~ ~~31~~ ~~30~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ·ªã‚Äú.4<F(‚ÄùO√¶¬´·∏§:¬•:‚Å¥√ó¬µ√ó>?‚ŵ ``` Uses the astute observation from [@xnor's answer](https://codegolf.stackexchange.com/a/80324), which saved 8 bytes. [Try it online!](http://jelly.tryitonline.net/#code=4buL4oCcLjQ8RijigJ1Pw6bCq-G4pDrCpTrigbTDl8K1w5c-P-KBtQ&input=&args=MzI) or [verify all test cases](http://jelly.tryitonline.net/#code=4buL4oCcLjQ8RijigJ1Pw6bCq-G4pDrCpTrigbTDl8K1w5c-P-KBtQowcjIxOzMywrXFvMOH4oKsRw&input=). ### How it works ``` ·ªã‚Äú.4<F(‚ÄùO√¶¬´·∏§:¬•:‚Å¥√ó¬µ√ó>?‚ŵ Main link. Argument: n (integer) >?‚ŵ If n is greater than 10: ¬µ ‚ŵ Execute the chain to ¬µ's left dyadically, with arguments n (left) and 10 (right). ‚Äú.4<F(‚Äù Yield the string of code points [46, 52, 60, 70, 40]. ·ªã Retrieve the character at index n. Indexing is modular and 1-based, so 1, 6, 11, etc. map to the first character, 0, 5, 10, etc. to the last. O Ordinal; yield the code point of the character. ¬• Combine the two links to the left into a dyadic chain. ·∏§ Yield 2n. : Divide 2n by 10, flooring the result. This yields n : 5 (integer division). √¶¬´ Shift the code point n : 5 bits to the left. :‚Å¥ Divide the result by 16. √ó Multiply the result by 10. Else: √ó ‚ŵ Multiply n by 10. ``` [Answer] # Python, 81 bytes ``` f=lambda n:n>19and 4*f(n-10)or n>10and[23,26,30,35,40,46,52,60,70][n-11]*5or 10*n ``` [Answer] # C++11, ~~104~~ ~~95~~ 91 bytes ``` int f(int n){int x={23,26,30,35,40,46,52,60,70};return n<11?n*10:n<20?x[n-11]*5:f(n-10)*4;} ``` Simple lookup table and ternary operator fun. [edit]Thanks! [edit2]I'm feeling extra stoopid today. Thanks again! [Answer] # Java, 62 bytes ``` i->' '<i?l(i-10)*4:10*i+")*+-037;AIQ".charAt(i>9?i-10:0)%41*5 ``` [Answer] # Jelly, 42 bytes ``` 7568b3+\+\ _‚ŵ·ªã¬¢√ó5+√ó‚ŵ$ √ᬵ_‚ŵ√ü4√ó¬µ20>$?√ó‚ŵ$>‚ŵ$? ``` [Try it online!](http://jelly.tryitonline.net/#code=NzU2OGIzK1wrXApf4oG14buLwqLDlzUrw5figbUkCsOHwrVf4oG1w580w5fCtTIwPiQ_w5figbUkPuKBtSQ_&input=&args=MzI) [Test suite.](http://jelly.tryitonline.net/#code=NzU2OGIzK1wrXApf4oG14buLwqLDlzUrw5figbUkCsOHwrVf4oG1w580w5fCtTIwPiQ_w5figbUkPuKBtSQ_CsOH4oKs&input=&args=MCwxLDIsMyw0LDUsNiw3LDgsOSwxMCwxMSwxMiwxMywxNCwxNSwxNiwxNywxOCwxOSwyMCwyMSwzMg) Uses the same principle as my [answer in Pyth](https://codegolf.stackexchange.com/a/80275/48934), just that the array is further reduced to `[1, 1, 0, 1, 0, 2, 2]`, which can generate `[1, 2, 3, 3, 4, 4, 6, 8]`, which can generate `[1, 2, 4, 7, 10, 14, 18, 24, 32]`. [Answer] # Javascript ES6, ~~104 103 100 97~~ 93 bytes ``` h=a=>{return a<11?a*10:a<20?a*10+c[a-11][1/2,1,2,7/2,5,7,9,12,16]*10:4*h(a-10);},u=p=>h(p[0]) ``` usage: call `u` with the input **enclosed in brackets like the OP said.** Will golf later. # 84 bytes if input is not enclosed in brackets and `h()` is called directly thanks to kenny lau -6 bytes [Answer] ## Haskell, ~~71~~ 66 bytes ``` h n|n<11=n*10|n<20=sum$5<$['.'.."DGKPU[ais"!!(n-11)]|1<2=4*h(n-10) ``` Usage example: `h 32` -> `2080`. The Haskell version of the algorithm found in many other answers. The results in the middle part for the numbers `11..19` are encoded as strings of consecutive ASCII characters: ``` 11: from . to D (23 chars) 12: from . to G (26 chars) 13: from . to K (30 chars) ... ``` Every character in the string is mapped to a 5 and summed up. Edit: @Lynn helped saving 4 bytes. Thanks! [Answer] # Julia 0.4, ~~49~~ 42 bytes ``` n->n>9?5Int("(.4<F"[n%5+1])*2^(n√∑5)/8:10n ``` Uses the astute observation from [@xnor's answer](https://codegolf.stackexchange.com/a/80324), which saved 7 bytes. [Try it online!](http://julia.tryitonline.net/#code=ZiA9IG4tPm4-OT81SW50KCIoLjQ8RiJbbiU1KzFdKSoyXihuw7c1KS84OjEwbgoKZm9yIG4gaW4gWzA6MjE7MzJdCiAgICBwcmludGxuKG4sICIgLT4gIiwgZihuKSkKZW5k&input=) --- # Julia 0.3, 38 bytes ``` n->2.5max("(.4<F"[n%5+1]<<(n√∑5-2),4n) ``` This requires a call to `Int` in Julia 0.4, which makes it longer than the other approach. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/237546/edit). Closed 2 years ago. [Improve this question](/posts/237546/edit) I was pondering today about how many characters it would take in each language to throw an exception, and noticed there wasn't any existing collection of answers, so: ### The task Throw an exception in the least amount of characters. If your language does not have exceptions, then a panic is valid. A panic constitutes as anything that there is no reasonable recovery strategy for. Examples include (but are not limited to): * Explicit `panic` instructions * Memory accesses that will always fail * Integer division by zero * Taking the `head` of an empty list in a `data`-based language Things that do not count as panics: * Compile-/parse-time errors (such as syntax errors and invalid types in a statically-typed language) * Unbound/undefined identifier errors * Quoting/splicing errors that are not the result of runtime data (ex `#'a` in Lisp is truly an unbound identifier error) ### Examples: #### Scala (.sc): 3 Characters ``` ??? ``` #### Scala 3 (.scala): 16 Characters ``` @main def a= ??? ``` #### Python: 3 Characters ``` 1/0 ``` #### Zig: 28 Characters ``` pub fn main()u8{@panic("");} ``` [Answer] # Motorola 6800 machine code, ~~2~~ 1 byte ``` FD HCF ; halt and catch fire ``` From [Some Guy](https://x86.fr/investigating-the-halt-and-catch-fire-instruction-on-motorola-6800/): > > It doesn’t really destroy the CPU, but makes it switch into a kind of debugging mode. Allegedly, HCF instruction on the 6800 should toggle the address lines in order very quickly. Legend added: up to the point that some support component might catch fire! > > > Fire would count as a panic, right? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` s ``` [Try it online!](https://tio.run/##y0rNyan8/7/4/38A "Jelly – Try It Online") I just tried random 1-letter commands until it worked. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` ḭ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B8%AD&inputs=&header=&footer=) Because I forgot to make integer division account for division by 0. ## Better Explanation Okay so normal division (`/`) accounts for division by 0 - it just always returns 0 (which has helpful uses for code golf). This is done in the overloads internally: ``` ​def​ ​divide​(​lhs​, ​rhs​): ​    ​types​ ​=​ ​vy_type​(​lhs​), ​vy_type​(​rhs​) ​    ​def​ ​handle_numbers​(​lhs​, ​rhs​): ​        ​if​ ​rhs​ ​==​ ​0​: ​            ​return​ ​0 ​        ​normal​, ​int_div​ ​=​ ​lhs​ ​/​ ​rhs​, ​lhs​ ​//​ ​rhs ​        ​return​ [​normal​, ​int_div​][​normal​ ​==​ ​int_div​] ​    ​return​ { ​        (​Number​, ​Number​): ​lambda​: ​handle_numbers​(​lhs​, ​rhs​), ``` That's taken directly from the vyxal source code btw. Now the problem is that I never actually special cased division by 0 in the overloads for integer division: ``` ​def​ ​integer_divide​(​lhs​, ​rhs​): ​    ​types​ ​=​ ​vy_type​(​lhs​), ​vy_type​(​rhs​) ​    ​return​ { ​        (​Number​, ​Number​): ​lambda​: ​lhs​ ​//​ ​rhs​, ``` As you can see, it just straight up tries to do python integer division without accounting for the special case normal division handles. Also, just for clarification, if there aren't any inputs provided to a vyxal program, `0` is implicitly used. ## Alternate solutions ``` ° ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%B0&inputs=&header=&footer=) How you gonna push the function reference of an undefined function? ``` ← ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%86%90&inputs=&header=&footer=) Same thing with variables [Answer] # [C (clang)](http://clang.llvm.org/), 9 bytes ``` f(){f();} ``` [Try it online!](https://tio.run/##S9ZNzknMS///P01DsxqIrWv/5yZm5gE5XAogLlftfwA "C (clang) – Try It Online") No exceptions in C, I hope a scary segfault with exit code is fine. [Answer] This isn't the shortest by any means, but here it is: ## C++ (g++), 14 bytes ``` main(){throw;} ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 3 bytes ``` 0`` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/3yAh4f9/AA "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), 3 bytes ``` 0() ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/3yAh4f9/AA "JavaScript (V8) – Try It Online") Not sure if you can get it below 3. [Answer] # [Bash](https://www.gnu.org/software/bash/), 4 bytes ``` . $0 ``` [Try it online!](https://tio.run/##S0oszvj/X09BxeD/fwA "Bash – Try It Online") Calls itself (well includes itself more accurately) until it segfaults. # [Aubergine](https://esolangs.org/wiki/Aubergine), 3 bytes ``` === ``` [Try it online!](https://tio.run/##SyxNSi1Kz8xL/f/f1tb2/38A "Aubergine – Try It Online") As far as I know, all Aubergine programs have to be divisible by 3, since all instructions are 3 characters. There are lots of 3 character programs that will fail. Here's one that I think is aesthetically pleasing. :) # [Ly](https://github.com/LyricLy/Ly), 1 byte ``` I ``` [Try it online!](https://tio.run/##y6n8/9/z/38A "Ly – Try It Online") Tries to pop from an empty stack. There are other one character programs in Ly that will fail when there's nothing on the stack. [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), 3 bytes ``` ^_@ ``` [Try it online!](https://tio.run/##S03OSylITkzMKcop@P8/Lt7h/38A "!@#$%^&*()_+ – Try It Online") Converts -1 to ascii but errors. [Answer] # [Malbolge Unshackled](https://github.com/TryItOnline/malbolge-unshackled), 0 bytes [Try it online!](https://tio.run/##y03MScrPSU/VLc0rzkhMzs5JTfkPBAA "Malbolge Unshackled – Try It Online") I have no idea, don't ask me why it works. ]
[Question] [ # Introduction You started to write a "Hello, World!" program, but after you wrote the part to print the hello, you forgot what your program should actually print. So now, you somehow managed it to write a program which can check if the entered word is what you search. # The task Your task is to write a program or function, which first prints `Hello... eh, whom should I greet?`, then asks for input, and if the input equals `world` ignoring capitalization, the program should print `Ah, yes. World.`, else it should print `No. That isn't what I meant.`. **But** you are not allowed to use any of the bytes equivalent to the ASCII values of: `worldWORLD` - that is, for those using code-pages not aligned with ASCII, bytes: `0x...:` `77, 6f, 72, 6c, 64, 57, 4f, 52, 4c, 44`. # Compact rules * No substring of the byte-string `worldWORLD` may appear in your program or in the file name of the program on any way * `print "Hello... eh, whom should I greet?"; if input.lower == "world" print "Ah, yes. World."; else print "No. That isn't what I meant.";` * Leading or trailing spaces are ignored. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the program with the lowest amount of chars wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 70 [bytes](https://github.com/DennisMitchell/jelly) ``` “¡Kịy<⁷ẊṘṘsṁñAỵḋẇ,ẇʂI»Ṅø“¢ƈṫ(Ɲ¬÷Ø“¡ṣƓ»µɠŒteḊȧKȯ“TḲj/Ẇi¤cecṡĿt⁺ƘNƁ⁻»;”. ``` Jelly's code-page is equal to ASCII in the range `' '`, `0x20`, through to `'~'`, `0x7e`, inclusive so the lack of any of `worldWORLD` in the code above suffices (note: `ẇȯṘĿḊ` are not `woRLD` or equivalent bytes.) **[Try it online!](https://tio.run/nexus/jelly#@/@oYc6hhd4Pd3dX2jxq3P5wV9fDnTOAqPjhzsbDGx0f7t76cEf3w13tOkB8qsnz0O6HO1sO7wBpWnSs4@HO1RrH5h5ac3j74RkgoaUPd7Q83DHv0O5DQF1dbkD8qHHPyQVHJ5UcWnJi@Yn1QDUhD3dsytJ/uKst89CS5NTkhzsXHtlf8qhx17EZfscaHzXuPrTb@lHDXL3//8v9i3xSAA "Jelly – TIO Nexus")** This took a little fiddling to avoid the forbidden bytes: all the naive string compressions contained illegal characters; finding the first index of a sublist within another is performed with the `w` atom; finding the length of a list (for chopping and measuring to replace `w`) uses `L` - something I considered was summing the indices with `JS` (triangle(9)=45), I ended up using a list of strings and a separate trailing period to kill three birds with one stone [sic], allowing a dequeue-flatten-dequeue chain, `ḊFḊ`, to pick out the word `World`, this can be further shortened by post-joining the list with the space using `Ḳ`, allowing for a simple dequeue, `Ḋ` to be used instead saving another byte. Adding the trailing period to whichever response is output as a single action also allowed compression without illegal bytes. For some reason, the word `yes` is not in Jelly's dictionary, yet even though compressing `Ah, yes.` is the same length as the raw string, having the compression as a list of strings `['Ah, yes.',' World']` (`“¢ƈṫ(Ɲ¬÷Ø“¥ḄḞ»`) is shorter by two bytes than concatenating (`“Ah, yes.”;“¥ḄḞ»`), the *third bird*. For the first message I compressed `Hell` as a word and prepended the string '...' with an 'o' to avoid the forbidden bytes. Commented code: ``` W: “¡Kịy<⁷ẊṘṘsṁñAỵḋẇ,ẇʂI» - compressed string "Hello... eh, whom should I greet?" R: “¢ƈṫ(Ɲ¬÷Ø“¡ṣƓ» - compressed list of strings ["Ah, yes.","World"] D: “TḲj/Ẇi¤cecṡĿt⁺ƘNƁ⁻» - compressed string "No. That isn't what I meant" WṄøRµɠŒteḊȧKȯD;”. - Main link: no arguments W - "Hello... eh, whom should I greet?" Ṅ - print and yield ø - niladic chain separation, no input to the following R - ["Ah, yes.","World"] µ - monadic chain separation, call that L ɠ - read a line from STDIN Œt - title-case it (e.g. "wOrLd" -> "World") Ḋ - dequeue L: ["World"] e - exists in? (0 or 1) ȧ - and L (0 or ["Ah, yes.","World"]) K - join with spaces (0 or "Ah, yes. World") D - "No. That isn't what I meant" ȯ - or ("No. That isn't what I meant" or "Ah, yes. World") ”. - literal '.' ; - concatenate ("No. That isn't what I meant." or "Ah, yes. World.") ``` [Answer] # Java 8, ~~376~~ 361 bytes ``` v->{System.\u006Fut.p\u0072int\u006Cn("He\u006C\u006C\u006F... eh, \u0077h\u006Fm sh\u006Fu\u006C\u0064 I g\u0072eet?");System.\u006Fut.p\u0072int\u006Cn(ne\u0077 java.uti\u006C.Scanne\u0072(System.in).next().equa\u006CsIgn\u006F\u0072eCase("\u0077\u006F\u0072\u006C\u0064")?"Ah, yes. \u0057\u006F\u0072\u006C\u0064.":"N\u006F. That isn't \u0077hat I meant.");} ``` -15 bytes switching from Java 7 to 8. [Try it online.](https://tio.run/##hVFNSwMxEL33Vwy5mAU7lKIWLFqkUtyDPVjRg3qI27HNujutTbJYSn/7mt1E2It4mcwXb/Ley1Wl@vnys84KZQzcK82HHoBmS7sPlRHMmxKg2uglZPKpeapk7HvHng/GKqszmAPDVV31rw@LvbFU4qsbDC5mzuK2yUZDj9e2pizFHYW0E2eICLQ@hXZ7tA7NEkzMXGf3DFJYBVQiOxHJ@P@bTAEYck8XndVhgItMcZwNZYTRnCDTt5UJ0pdTYdOkKw748fJUGZIioHYH3Y@KZCJuPKk9GWyZnf@5iuJSzKMU8LhWFrThE/urh69TKEmxRc/3WDf6b9174aWPDrT@lN49ubA7zauXN5UE5xgzya4oomnH@nnzUNz@AA) **Explanation:** In Java you can use unicode escapes in the form of `\u####`. Fortunately, `u` wasn't one of the disallowed characters, so I've used these unicode escapes for the characters that are disallowed. The method above, without unicode escapes: ``` v->{ // Method with empty unused parameter & no return System.out.println("Hello... eh, whom should I greet?"); // Print the greetings line System.out.println(new java.util.Scanner(System.in).next() // Get the user input from STDIN .equalsIgnoreCase("world")? // If it's equal to (case-insensitive) "world": "Ah, yes. World." // Print the World-response line : // Else: "No. That isn't what I meant.");} // Print the No-response line ``` Taking the input as parameter and returning a String instead of using STDIN/STDOUT (which I think is allowed reading the challenge again, so not sure why I hadn't done that four years ago when I posted my answer), it would be **239 bytes** instead: ``` s->"He\u006C\u006C\u006F... eh, \u0077h\u006Fm sh\u006Fu\u006C\u0064 I g\u0072eet?\n"+(s.equa\u006CsIgn\u006F\u0072eCase("\u0077\u006F\u0072\u006C\u0064")?"Ah, yes. \u0057\u006F\u0072\u006C\u0064.":"N\u006F. That isn't \u0077hat I meant.") ``` [Try it online.](https://tio.run/##dZBBS8NAEIXv/RXDXtxFuxRRC4oWqYg5mIMKHqyHMR2TrcmmdiaFIv3tcdOskIuXYd7M29nHt8ItjlfLrzYrkRke0fmfEYDzQptPzAjSTgI8y8b5HDIdGzZXYb4fhcKC4jJIwcN1y@Mb9UCLZjK5mA/qvbUWqDiBTk2nRT@sgGPXDLxnkEB@8J0SyWzh1bFmS98N9iZOct@/iqY5MmnVXx4uhjeVmanb8P@O2B5CnP9rtepSpTE1vBQo4NgfyV/0oBOoCL1YZdqOwrr5KAOAyGFbuyVUgWNE9faOJjLcsVBl60bsOmyk9NrbTKvX@qm8UyYS3be/) [Answer] # [SOGL](https://github.com/dzaima/SOGL), 67 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` P5√~!9!j┌⁰‚V{7Χ←½χķ²‘q"A6‘,u=?"ΤΞ¦▲ξ⌠²ō⅞Σ↔─╚‘p}"⁽∙šžøp⅔…ļ4∑Ν…ZH]└»‘ ``` Explanation: ``` ...‘ push "Hello... eh, whom should I greet?" q output, without disabling implicit output "A6‘ push "world" ,u=? } if equal to lowercased input "....‘ push "Ah, yes. World." p output, disabling implicit output "...‘ push "No. That isn't what I meant." implicitly output that if that hasn't been disabled by the if. ``` [Answer] # JavaScript (ES6), ~~215~~ 247 bytes If I've understood correctly, the challenge is to not use any of the following chracters: `0, 2, 4, 5, 6, 7, c, d, f, l, o, r, w, x, D, L, O, R, W`. ``` (t=this,T=""+t,A=T[8],a=T[13],b=T[1],e=(""+!!1)[1],g=(""+!1)[3-1],h=T[11])=>t[`p${e+b}mpt`](`He${g+g+b}... eh, ${a}h${b}m sh${b}u${g+h} I g${e}eet?`)[`t${b}L${b+a}e${e}Case`]()==a+(z=b+e+g+h)?`Ah, yes. ${A+z}.`:`N${b}. That isn't ${a}hat I meant.` ``` --- ## Try It ``` y= (t=this,T=""+t,A=T[8],a=T[13],b=T[1],e=(""+!!1)[1],g=(""+!1)[3-1],h=T[11])=>t[`p${e+b}mpt`](`He${g+g+b}... eh, ${a}h${b}m sh${b}u${g+h} I g${e}eet?`)[`t${b}L${b+a}e${e}Case`]()==a+(z=b+e+g+h)?`Ah, yes. ${A+z}.`:`N${b}. That isn't ${a}hat I meant.` alert(y()) ``` ## Explanation ``` t=this // assigns the window object to variable t T=""+t // converts t to a string ("[object Window]") and assigns it to variable T A=T[8] // assigns the 9th character of T ("W") to variable A a=T[13] // assigns the 14th character of T ("w") to variable a b=T[1] // assigns the 2nd character of T ("o") to variable b e=(""+!!1)[1] // converts true to a string and assigns the 2nd character ("r") to variable e g=(""+!1)[3-1] // converts false to a string and assigns the 3rd character ("l") to variable g // (1 is a truthy value in JS, so !1=false and !!1=true) h=T[11] // assigns the 12th character of T ("d") to variable h // The rest then uses template literals and the above variables to construct the following: window["prompt"]("Hello... eh, whom should I greet?")["toLowerCase"]()=="w"+(z="orld")? "Ah, yes. W"+z: "No. That isn't what I meant." ``` [Answer] # JavaScript, ~~484~~ 347 bytes This is horrible and could most likely be golfed more. Just seeing if I could answer in JavaScript with the restrictions. ``` z=({}+[]+{})[-~[]] y=(!![]+[])[+!+[]] x=([][[]]+[])[!+[]+!+[]] v=this c=n=>v[`St${y}ing`][`f${y}${z}mCha${y}C${z}${x}e`](n*9) u=c(12) t=c(13.3) v[s=`a${u}e${y}t`](`He${u+u+z}... eh, ${t}h${z}m sh${z}u${u+x} I g${y}eet?`) v[s](v[`p${y+z}mpt`]()[`t${z+c(8.5)+z+t}e${y+c(7.5)}ase`]()==t+(s=z+y+u+x)?`Ah, yes. ${c(9.7)+s}.`:`N${z}. That isn't ${t}hat I meant.`) ``` ### Try it online! ``` z=({}+[]+{})[-~[]] y=(!![]+[])[+!+[]] x=([][[]]+[])[!+[]+!+[]] v=this c=n=>v[`St${y}ing`][`f${y}${z}mCha${y}C${z}${x}e`](n*9) u=c(12) t=c(13.3) v[s=`a${u}e${y}t`](`He${u+u+z}... eh, ${t}h${z}m sh${z}u${u+x} I g${y}eet?`) v[s](v[`p${y+z}mpt`]()[`t${z+c(8.5)+z+t}e${y+c(7.5)}ase`]()==t+(s=z+y+u+x)?`Ah, yes. ${c(9.7)+s}.`:`N${z}. That isn't ${t}hat I meant.`) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 71 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•ǝ·Þ•“Ÿ™...Ûß,£Ô‚© I ÿ?“ćuì,u‘‚ï‘Qi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª, ``` 05AB1E uses a custom code-page, but the lower- and uppercase characters are on the same hexadecimal positions on the code-page, so as long as I don't use `worldWORLD` it's fine. [Try it online](https://tio.run/##yy9OTMpM/f9f71HDouNzD20/PA/IeNQw5@iORy2L9PT0Ds8@PF/n0OLDUx41zDq0UsFT4fB@e6D0kfbSw2t0Sh81zACKH14PpAMzgcKHdh1u03nUsOzwHD2wOJCcc3g1kHjUtObQDj0geXQBkDjdlqdeAqQPNyh4HtoIVA9SV6t3aJXO///l/kU@KQA). **Explanation:** ``` .•ǝ·Þ• # Push compressed string "greet" (which unfortunately isn't part of # the dictionary, AND contains an 'r'..) “Ÿ™...Ûß,£Ô‚© I ÿ?“ # Push dictionary string "hello... eh, whom should I ÿ?", # where the `ÿ` is filled with the "greet" we pushed earlier ć # Extract head; pop and push remainder and first character separately u # Uppercase this first character ì # Prepend it back to the remainder-string , # And output it to STDOUT with trailing newline u # Convert the (implicit) input-string to uppercase ‘‚ï‘ # Push dictionary string "WORLD" Qi # If they are equal: “ºÆ,…Ü.‚ï.“ # Push dictionary string "ah, yes. world." ë # Else: “€¸.€Š€ˆn't€À I±….“ '# Push dictionary string "no. that isn't what I meant." }.ª # After the if-else: sentence capitalize the string , # And also output it to STDOUT ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•ǝ·Þ•` is `"greet"`; `“Ÿ™...Ûß,£Ô‚© I ÿ?“` is `"hello... eh, whom should I ÿ?"`; `‘‚ï‘` is `"WORLD"`; `“ºÆ,…Ü.‚ï.“` is `"ah, yes. world."`; and `“€¸.€Š€ˆn't€À I±….“` is `"no. that isn't what I meant."`. If all characters would be allowed, there are only two minor differences: * The `greet` would have been placed literally inside the dictionary sentence * The input would have been changed to lowercase with `l` instead, so `'‚ï` could be used for `"world"` So it would be **68 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` “Ÿ™...Ûß,£Ô‚© I greet?“ćuì,l'‚ïQi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª, ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcOcozsetSzS09M7PPvwfJ1Diw9PedQw69BKBU@F9KLU1BJ7oIoj7aWH1@jkqAMlDq8PzASKHNp1uE3nUcOyw3P0wIJAcs7h1UDiUdOaQzv0gOTRBUDidFueegmQPtyg4HloI1A9SF2t3qFVOv//l/sX@aQAAA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 75 bytes ``` `ƈṡ... eh, ↓Ṅ ƛ¤ I £Ẋet?`,⇩`ƛ†`=[`Ah, ∨ȯ. ƛ€.`,|«ƛτ«ǐ`. λ÷ ⋏°'t λ⟨ I ḋ↓.`J, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgxojhuaEuLi4gZWgsIOKGk+G5hCDGm8KkIEkgwqPhuopldD9gLOKHqWDGm+KAoGA9W2BBaCwg4oioyK8uIMab4oKsLmAsfMKrxpvPhMKrx5BgLiDOu8O3IOKLj8KwJ3Qgzrvin6ggSSDhuIvihpMuYEosIiwiIiwiV29SbEQiXQ==) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 171 bytes No compression here! Requires `⎕IO←0` which is default on many systems. All characters are in [the character set](https://codegolf.meta.stackexchange.com/a/9429/43319). ``` c←{⎕AV[¯25+⎕AV⍳⍵]} c'Á.558GGGm.1´m∆186m¥18£5¯mÂm0⊢..$⍒' c'Ë8GmÒ1z$m2¥7v$m∆1z$mÂm6.z7$G' 'Z1mB.¥GmÕ8⊢5¯G'⊃⍨(c'∆8⊢5¯')≡819⌶⍞ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wQDrkcd7Wn/k4HMaqCYY1j0ofVGptpg5qPezY96t8bWciWrH27UMzW1cHd3z9UzPLQl91FHm6GFWe6hpYYWhxabHlqfe7gp1@BR1yI9PZVHvZPUQRq6LdxzD08yrFLJNTq01LxMBawHyAOqNNOrMldxV1dQjzLMddI7tBSocKoFUDfQIHf1R13Nj3pXaCSrA9VDBdU1H3UutDC0fNSz7VHvvP9AB/9P40rKSczgSuMKzw/KcQEA "APL (Dyalog Unicode) – TIO Nexus") Works by first defining a custom decoding function `c` which decodes from a simple shifted encoding which was carefully chosen to be able to represent all the required strings while avoiding the ten forbidden characters. `c←{`…`}` a function:  `⎕AV[`…`]` the **A**tomic **V**ector indexed by   `¯25+` the downshifted-by-25   `⎕AV⍳` indices into the **A**tomic **V**ector for   `⍵` the argument `c'Á.558GGGm.1´m∆186m¥18£5¯mÂm0⊢..$⍒'` implicitly print the decoded *Hello... eh, whom should I greet?* `⍞` get character input `819⌶` lowercase it `(`…`)≡` compare it to  `c'∆8⊢5¯'`  the decoded *world* `'Ë8GmÒ1z$m2¥7v$m∆1z$mÂm6.z7$G' 'Z1mB.¥GmÕ8⊢5¯G'⊃⍨` use that Boolean to pick from the encoded *No. That isn't what I meant.* (if false) and *Ah yes. World.* (if true) `c` decode that [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 1445 bytes ``` ->-[------->+<]>-.-[->+++++<]>++.+++++++..+++.[->+++++<]>+++...++[--->++<]>.+[->+++<]>++.+++.----[->+++<]>.------------.--[->++++<]>-.+[->+++<]>.+++++++.--.[->+++++<]>-.---[->++++<]>-.-----------.+++++++.++++++.---------.--------.-[--->+<]>-.++++[->++<]>+.-[->++++<]>.++[->+++<]>+.+++++++++++.-------------..[--->+<]>---.-[->+++++<]>.[-]+[-<+]->>>,[>>+<+<-]<------[>+++<--]>[->-<]+>[<->[-]]<[<<+>>-]-[>+<---]>++[->-<]+>[<->[-]]<[<<<+>>>-]+[-<+]->>>,[>>+<+<-]<-[>--<-------]>+[->-<]+>[<->[-]]<[<<+>>-]-[>+<---]>------[->-<]+>[<->[-]]<[<<<+>>>-]+[-<+]->>>,[>>+<+<-]<-[>++<+++++++++]>[->-<]+>[<->[-]]<[<<+>>-]-[>+<---]>---[->-<]+>[<->[-]]<[<<<+>>>-]+[-<+]->>>,[>>+<+<-]<-[>--<-------]>--[->-<]+>[<->[-]]<[<<+>>-]-[>+<-------]>+++[->-<]+>[<->[-]]<[<<<+>>>-]+[-<+]->>>,[>>+<+<-]<-[>++<-----]>--[->-<]+>[<->[-]]<[<<+>>-]----[>---<----]>+[->-<]+>[<->[-]]<[<<<+>>>-]+[-<+]->>,[<+>-]<-----[>+>+<<-]>[<+>-]+>[>-[--->+<]>-------.-[--->+<]>.[->+++++<]>+++.++[--->++<]>.>-[--->+<]>-.[---->+++++<]>-.-------.--[--->+<]>-.[---->+<]>+++.-[--->++<]>-.++++++++++.-----.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>-.+[->+++<]>.-------.--[--->+<]>-.[---->+<]>+++.++++[->++<]>+.-[->++++<]>.+[----->+<]>.--------.----.+++++++++++++.++++++.[++>---<]>.+[-<+]->>->[-]]<[>>----[---->+<]>++.[--->+<]>---.----[->+++<]>.------------.--[->++++<]>+.--[->+++<]>.[--->+<]>----.+[++>---<]>.++[--->++<]>.---[->+++<]>.-[--->+<]>---.+++.------.--------.[->+++<]>++.+[-<+]->>-] ``` [Try it online!](https://tio.run/##nVRbbgMxCDwQgRNYXAT5ow9Vqhq1UqQox9@CX2A3G23jr13MzBjM@PXy8vn9cX372jZkFKyLIWVG0n8GW/oHQFAX2QdNWxrToBSkRQjq9sCRsY4YYVjUN6qmI4ee5gQ1A0yIyNUhA@ki/UO8PsuRdmSgQEoQCuikM2MhIyfDuV26k5UjQUZmPglrFiTMqSKlkCNmVgymDCwJ9TvnJCkBM2bLsWxr4b0ky@I9EdEDNSkjOCDSzvV/Ia1jtOdQOc/JxHruE0wyrfCnWgeN4bFQuUVsx9rp8Sp0Eo30IVAhFU02AyWqUMY4UMu8rpabDBeRZSoXwwynrUmNDJ0LaZ13EoBSarHzcMYfjj0jH9B/YEXxJ4kmP0djuuf9rDT63m@EuQ65Ky8OPvZKean1WsKVqWbQjzc0U0@y/rB4gdMDOurI23b7uZzffwE "brainfuck – Try It Online") Requires an 8-bit wrapping implementation where EOF=0. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~76~~ 73 bytes ``` u”Ÿ™... ”“Ûß,£Ô‚© I g“«’‚™ˆÆ?’«,‘‚ï‘Qi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª, ``` [Try it online!](https://tio.run/##yy9OTMpM/f@/9FHD3KM7HrUs0tPTUwCyHzXMOTz78HydQ4sPT3nUMOvQSgVPhXSg4KHVjxpmAgWAKk@3HW6zB/IOrdZ51DADKHZ4PZAOzASp2nW4DSi47PAcPbC4Hsg4oM45j5rWHNqhBySPLgASp9vy1EuA9OEGBc9DG4HqQepq9Q6t0vn/HwA "05AB1E – Try It Online") *-3 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs).* ``` # (implicit) push STDIN to stack u # convert top of stack to uppercase ”Ÿ™... ”“Ûß,£Ô‚© I g“«’‚™ˆÆ?’« # push "Hello... eh, whom do I greet?" , # output top of stack to STDOUT ‘‚ï‘ # push "WORLD" Qi # if top two stack values are equal... “ºÆ,…Ü.‚ï.“ # push "ah, yes. world." ë # else... “€¸.€Š€ˆn't€À I±….“ # push "no. that isn't what I meant." } # exit if statement .ª # push top of stack in sentence case , # output top of stack to STDOUT ``` [Answer] # [Python 3](https://docs.python.org/3/), 186 bytes ``` t=a,b,c,e,f=5*'%c'%(87,111,114,108,100) exec(f'exit(["N{b}. That isn\'t \u0077hat I meant.","Ah, yes. {t}."][input("He{e+e+b}... eh, \u0077h{b}m sh{b}u{e+f} I g{c}eet?").tit{e}e()==t])') ``` [Try it online!](https://tio.run/##TZBRa8IwEMff8ymOgEtTQ2nZhuIoY7CHCeJgDPagMmJ6XQOaShqnEvLZu1R82MNx3PG/393/DhfXtOa@V22FUIKllPaulGIrlEBRl48pGyk2SqYTURRFjAdR5NMYOSd4RpXUDM/aJSu69NuQwWcjHejOrJmD9THPJ5OhMYc9SuMyKuhLI@CCXQbehYxuVtocji6hb@hxjOOIyDLAqLkNR@geuiEdo6AOEfXjVUB0z5RnTjuPARNelm7DGe/j@YRo49B2qJxuTfTk08FcuPMpO7V2V329fyxeWYDWgl@2BgM52DiSsLn5lTtdgWqklWpgzJiA9D@O37SckMF2ea1IHVHfoA3kopjB9S3DSv4EN3V/ereLiux3srr8AQ "Python 3 – Try It Online") Outputs to `STDERR`. [Answer] # [Retina](https://github.com/m-ender/retina), ~~211~~ 194 bytes ``` T`a-z`A-Z T`A-Z`A-C\E-KMNPQS-VX-Z(%[]{ ^(?!%SVNE$).* Qs. Yiay jxq'y =iay J pfaqy. %SVNE Ai, *fx. %svne. ^ Ifnns... fi, =isp xiszne J hvffy?¶ T`A-C\E-KMNPQS-VX-Z(%[]{a-ce-kmn\pqs-vx-z}=+*&`A-Za-z ``` Explanation: ``` T`a-z`A-Z - Stage one (uppercasing input) T` Configuration - Transliterate; a-z Lowercase letters of the alphabet ` ...into... A-Z Uppercase letters of the alphabet T`A-Z`A-C\E-KMNPQS-VX-Z(%[]{ - Stage two (encoding input) T` Configuration - Transliterate: A-Z Uppercase letters of the alphabet ` ...into... A-C\E-KMNPQS-VX-Z All uppercase characters, excluding "WORLD" (%[]{ And these characters to make up for the missing 5 characters ^(?!%SVNE$).* Qs. Yiay jxq'y =iay J pfaqy. - Stage three (check whether input is not "world") Implicit Configuration - Replace: ^(?!%SVNE$).* Anything except "%SVNE" (the encoded version of "WORLD") with Qs. Yiay jxq'y =iay J pfaqy. This line (encoded version of "No. That isn't what I meant."). %SVNE Ai, *fx. %svne. - Stage four (check whether input is "world") Implicit Configuration - Replace: %SVNE %SVNE with Ai, *fx. %svne. This line (the encoded version of "Ah, yes. World.") ^ Ifnns... fi, =isp xiszne J hvffy?¶ - Stage five (append message to start) Implicit Configuration - Replace: ^ The start with Ifnns... fi, =isp xiszne J hvffy?¶ This line (the encoded version of ("Hello... eh, whom should I greet?"). The ¶ represents a newline T`A-C\E-KMNPQS-VX-Z(%[]{a-ce-kmn\pqs-vx-z}=+*&`A-Za-z - Stage six (decode) T` Configuration - Transliterate: A-C\E-KMNPQS-VX-Z All uppercase characters, excluding "WORLD" (%[]{ And these characters to make up for the missing 5 characters A-C\E-KMNPQS-VX-Z All lowercase characters, excluding "world" }=+*& And these characters to make up for the missing 5 characters ` ...with... A-Za-z All the uppercase characters followed by the lowercase characters. ``` [Try it online!](https://tio.run/nexus/retina#@x@SkKhbleCoG8UVAiKB2DnGVdfb1y8gMFg3LEI3SkM1OraaK07DXlE1OMzPVUVTT4srsFhPITIzsVIhq6JQvVLBFsT0UihISyys1OMCK@NyzNRR0Eqr0FNQLS7LS9XjiuPyTMvLK9bT01NIA0rZZhYXKFRkFlflpQJ1ZpSlpVXaH9oGdgM2@xN1k1N1s3PzYgoKi3XLKnSram21tdRADga6/v//8vyiHBcA) I used [this](https://tio.run/nexus/retina#@x@S4KgblahbBaScY1x1vX39AgKDdcMidKM0VKNjqxN1k1N1s3PzYgoKi3XLKnSram21tdT@/3fM0FGoTC3WUwjPL8pJ0QMA) program to encode the strings, and [this](https://tio.run/nexus/retina#@x@S4KjrHOOq6@3rFxAYrBsWoRuloRodW52om5yqm52bF1NQWKxbVqFbVWurraUGVByVqFv1/79jpo6CVlqFnoJqcVleqh4A) one to decode them. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~208~~ ~~205~~ 202 bytes ``` a[];main(){puts("He\x6c\x6c\x6f... eh, \x77h\x6fm sh\x6fu\x6c\x64 I g\162eet?");gets(a);puts((*a|' ')^1819438967|(a[1]|32)^100?"N\x6f. That isn't \x77hat I meant.":"Ah, yes. \x57\x6f\x72\x6c\x64.");} ``` [Try it online!](https://tio.run/##NU5NC4JAEP0rw15coxa/cjUPEnTIS126qcGybCqkRK5kZL/dRquBYZg3b957clVIOY4izaNaVA01X7dOt5TsVdb78tcXxhiocglZz3k5ATW08@x@DA8SKDLbd5TSMTGjQqGIMKNZjC7EYACWYZ7twA49Nwh9PlCR2vngOghaVkwOsxGcSqGhahtDf91wS6BWotGMbMgWQzxVy/C25tMDcpx/BobG73F8HO/X3Qc "C (gcc) – Try It Online") Apparently you don't even have to specify an array length. Ungolfed: ``` int a[]; // Array of ints. Hint: ints are 4 characters wide. main(){ puts("Hello... eh, whom should I greet?"); gets(a); // Read input line. puts( (*a | ' ') // Tolower() the first four characters ^ 1819438967 // Compare to "worl", non-zero if not the same | (a[1] | 32) // Tolower() the fifth character ^ 100 // Compare to "d\0\0\0", non-zero if not the same ? // If non-zero bits present, it wasn't "world". "No. That isn't what I meant." : // Otherwise, we have a match. "Ah, yes. World."); } ``` Thanks to @ceilingcat for shaving off 3 bytes. [Answer] ## Python 3.7, ~~239~~ ~~267~~ ~~260~~ 258 bytes ``` a,b,c,e,f,g='\u0057','\u0077','\u006f','\u0072','\u006c','\u0064' exec(f'p=p{e}int;p("He{f}{f}{c}... eh, {b}h{c}m sh{c}u{f}{g} I g{e}eet?");p("Ah, yes. {a}{c}{e}{f}{g}."if input().{f}{c}{b}e{e}()=="{b}{c}{e}{f}{g}"e{f}se"N{c}. That isn\'t {b}hat I meant.")') ``` [Try it online!](https://tio.run/##dY8/C8IwEMV3P8WRJQnIUfzXqYgIYhcnxy5FTpOhsZgr2E8faxMhi8tx93j3471@ZPN06xD6l3WsxJmaoSh2x2yeEBHILOF7laWJYgc@bUPm3UANj9m3IuK90At6003JRD9MlJE8zqhtGf@jPYegsHewrh9YacyTxAQUP5SuKhGVfyCR2ngSl9QFrqZlsN41kn@NJqGGjlrHKLTUIXwA "Python 3 – Try It Online") I had to write `exec` because I had to write `p\u0072int` instead of `print`, `e\u006Cse` instead of `else` and `\u006C\u006F\u0077e\u0072` instead of `lower`. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 7 years ago. [Improve this question](/posts/16788/edit) A [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'") is not the same as a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), in a Code-Bowling, you should solve the challenge in as many characters as possible. The goal of this Code-Bowling is to create a quine in as many characters as possible, but you still should try to remove redundant characters. For example, don't post a HQ9+ solution with 10,000,000 times the `+` character, because the code still works if you remove them. Also, don't use variables with a name of 100 characters long, because you could easily rename them to a name of one character. Because this is a popularity-contest, the highest-voted answer wins. With 'redundant characters', I mean characters that can be removed, but the code will still work after removing them. [Answer] # Brainfuck: 153,191 bytes This is probably my largest BF binary. It prints it's own source including the intro text which is the Norwegian fairy tail The three billy goats Gruff (De tre bukkene Bruse). You cannot remove the story without removing the generating code so this Quine is designed to tell a story! `bf` (A well known interpreter on Debian based linux distros) has too few cells by default so start it with: ``` bf -c35724 billy-quine.bf ``` Since StackExchange has a 30K limit I had to put it [somewhere else](https://gist.github.com/westerp/8363993/raw/2edaf2becd8aeff47025683bb0f81eaba5f85c51/billy-quine.bf). Beginning of the file follows: ``` [ Once upon a time there were three billy goats, names Gruff. They were on their way to eat on the hillside, but they had to cross a bridge. Under the bridge lived a troll, with eyes as big as saucers, and a nose as long as a poker. The first goat over the bridge was the youngest Billy Goat Gruff. "Trip, trap, trip, trap!" he walked across the bridge. "Who's that tripping over my bridge?" roared the troll. "I am the smallest Billy Goat Gruff, and I'm going up to the hillside to make myself fat," said the billy goat, with a tiny voice. "I'm coming to gobble you up," said the troll. "Oh, no! please don't eat me. I'm too little!" said the billy goat. "Wait for the second Billy Goat Gruff. He's much bigger." "Well, be off with you," said the troll. A little while later, the second Billy Goat Gruff crossed the bridge. "Trip, trap, trip, trap, trip, trap" went the bridge. "Who's that tripping over my bridge?" roared the troll. "I am the second Billy Goat Gruff, and I'm going up to the hillside to make myself fat," said the billy goat, with a medium voice. "I'm coming to gobble you up," said the troll. "Oh, no! Don't eat me. Wait for the last Billy Goat Gruff. He's much bigger." "Very well! Be off with you," said the troll. Next, the big Billy Goat Gruff crossed the bridge. "Trip, trap, trip, trap, trip, trap!" went the bridge. This billy goat was heavy and the bridge creaked and groaned under him. "Who's that tramping over my bridge?" roared the troll. "I am the big Billy Goat Gruff ," said the billy goat, with a big ugly voice. "I 'm coming to gobble you up," roared the troll. "No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and I could crush you into bits and bones." "No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and I could crush you into bits and bones." And when the troll saw how big the billy goat was, the troll let him pass. After that, the three billy goats went to the hillside. They got so fat they could hardly walk home. And if the fat hasn't fallen off, they're still fat; and so, Snip, snap, snout. This tale's told out. ] ->>>>++++>++>++>>++++>++>+++>++>++++>++>++>+++++>+++>++>++++++>++>++++>+>+>+++>+>+>++++>+>+++>+>+>++++>++>++++>++>+++>++>++++>++>++>+++>>++++>+>+>+++>+>+>++++>+>+++>+>+>+++++>+++>+++++>+++>++>++>>++++>++>++>+++>+++++>+>+>>+>+>+>+>>>>+>+>>+>+>+++++>+++++>+>+>+>+>+++++>+++++>+>+>++++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>>+>+>>+>+>>+>+>>>+>+>>>+>+>+>+++++>+>+>+>>+>+>+++++>+++>>>++>++++>++>++>++>++>++>>+>+>>+>+>+>+++++>+++>++>++++>>+>+>+>++++>++>>+>+++++>+++>++>++++>++>>+>+++++>+++>++++++>+>+>>++>++>++>++++>+>+>+>>++>++++++>++>++>+++++>+++>+++++>+++>>+>++++++>++++++>++++++>++++++>+++++>+>+++++>+++++>+>++++>++>++>>>>>>>>+>>>>>>+>+++++>+++>>>>>>>>>>+>++++>>++>+++++>+++>>++>++>++>++>++++++>+>++++>++>>>>>>>>>>+>+++++>+++>>>>>>+>++++>++++>++>++>+++++>+++++>+++>>>+>+++++>++++>>++>+++++>+++>+++>>++++>+++++>+++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>++++++>>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>++>+++++>+++>>>>>>+>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>>>++++++>>++>++++>+>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>+>++++++>>>>++>++++>+>>>>>>>++>+++++>+++>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++++++>>>>>>>>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>>>>++++++>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++.... ``` [Answer] # Java 2286+ This can be expanded easily by including lowercase class names and then moving on to unicode characters. I do believe that there are no redundant characters. However, you could **replace** characters to simplify this (If this is allowed, then no solution here will win because you could simply replace every character and get the shortest quine for the language). This is a true quine, with no sort of reading code. Redundant characters removed version: ``` class Z{String s(){char q=34;String t="class Z{String s(){char q=34;String t=;t=t.substring(0,38)+q+t+q+t.substring(38);return t;}}class Y{String s(){return new Z().s();}}class X{String s(){return new Y().s();}}class W{String s(){return new X().s();}}class V{String s(){return new W().s();}}class U{String s(){return new V().s();}}class T{String s(){return new U().s();}}class S{String s(){return new T().s();}}class R{String s(){return new S().s();}}class P{String s(){return new R().s();}}class O{String s(){return new P().s();}}class N{String s(){return new O().s();}}class M{String s(){return new N().s();}}class L{String s(){return new M().s();}}class K{String s(){return new L().s();}}class J{String s(){return new K().s();}}class I{String s(){return new J().s();}}class H{String s(){return new I().s();}}class G{String s(){return new H().s();}}class F{String s(){return new G().s();}}class E{String s(){return new F().s();}}class D{String s(){return new E().s();}}class C{String s(){return new D().s();}}class B{String s(){return new C().s();}}class A{public String toString(){return new B().s();}}public class Q{public static void main(String...a){System.out.print(new A());}}";t=t.substring(0,38)+q+t+q+t.substring(38);return t;}}class Y{String s(){return new Z().s();}}class X{String s(){return new Y().s();}}class W{String s(){return new X().s();}}class V{String s(){return new W().s();}}class U{String s(){return new V().s();}}class T{String s(){return new U().s();}}class S{String s(){return new T().s();}}class R{String s(){return new S().s();}}class P{String s(){return new R().s();}}class O{String s(){return new P().s();}}class N{String s(){return new O().s();}}class M{String s(){return new N().s();}}class L{String s(){return new M().s();}}class K{String s(){return new L().s();}}class J{String s(){return new K().s();}}class I{String s(){return new J().s();}}class H{String s(){return new I().s();}}class G{String s(){return new H().s();}}class F{String s(){return new G().s();}}class E{String s(){return new F().s();}}class D{String s(){return new E().s();}}class C{String s(){return new D().s();}}class B{String s(){return new C().s();}}class A{public String toString(){return new B().s();}}public class Q{public static void main(String...a){System.out.print(new A());}} ``` Readable version: ``` class Z{ String s(){ char q=34; String t="class Z{String s(){char q=34;String " + "t=;t=t.substring(0,38)+q+t+q+t.substring(38);" + "return t;}}class Y{String s(){return new Z().s();" + "}}class X{String s(){return new Y().s();}}" + "class W{String s(){return new X().s();}}" + "class V{String s(){return new W().s();}}" + "class U{String s(){return new V().s();}}" + "class T{String s(){return new U().s();}}" + "class S{String s(){return new T().s();}}" + "class R{String s(){return new S().s();}}" + "class P{String s(){return new R().s();}}" + "class O{String s(){return new P().s();}}" + "class N{String s(){return new O().s();}}" + "class M{String s(){return new N().s();}}" + "class L{String s(){return new M().s();}}" + "class K{String s(){return new L().s();}}" + "class J{String s(){return new K().s();}}" + "class I{String s(){return new J().s();}}" + "class H{String s(){return new I().s();}}" + "class G{String s(){return new H().s();}}" + "class F{String s(){return new G().s();}}" + "class E{String s(){return new F().s();}}" + "class D{String s(){return new E().s();}}" + "class C{String s(){return new D().s();}}" + "class B{String s(){return new C().s();}}" + "class A{public String toString(){return new B().s();}}" + "public class Q{public static void main(String...a){System.out.print(new A());}}"; t=t.substring(0,38)+q+t+q+t.substring(38); return t; } } class Y{ String s(){ return new Z().s(); } } class X{ String s(){ return new Y().s(); } } class W{ String s(){ return new X().s(); } } class V{ String s(){ return new W().s(); } }class U{ String s(){ return new V().s(); } } class T{ String s(){ return new U().s(); } } class S{ String s(){ return new T().s(); } } class R{ String s(){ return new S().s(); } } class P{ String s(){ return new R().s(); } } class O{ String s(){ return new P().s(); } } class N{ String s(){ return new O().s(); } } class M{ String s(){ return new N().s(); } } class L{ String s(){ return new M().s(); } } class K{ String s(){ return new L().s(); } } class J{ String s(){ return new K().s(); } } class I{ String s(){ return new J().s(); } } class H{ String s(){ return new I().s(); } } class G{ String s(){ return new H().s(); } } class F{ String s(){ return new G().s(); } } class E{ String s(){ return new F().s(); } } class D{ String s(){ return new E().s(); } } class C{ String s(){ return new D().s(); } } class B{ String s(){ return new C().s(); } } class A{ public String toString(){ return new B().s(); } } public class Q{ public static void main(String...a){ System.out.print(new A()); } } ``` [Answer] ## Python 2, jiggabytes. Here's a small variant. I'd use some dataset like [all the phone conversations in the world over the last 6 months](http://www.theguardian.com/world/2013/jun/06/nsa-phone-records-verizon-court-order), but [some jackass can't figure out power to the building](http://www.salon.com/2013/10/08/is_nsa_spying_more_than_its_machines_cant_handle/). Oh, and they haven't responded to my FOIA\* request. ``` s='Another one got caught today, it\'s all over the papers. "Teenager Arrested in Computer Crime Scandal", "Hacker Arrested after Bank Tampering"...\n\nDamn kids. They\'re all alike.\n\nBut did you, in your three-piece psychology and 1950\'s technobrain, ever take a look behind the eyes of the hacker? Did you ever wonder what made him tick, what forces shaped him, what may have molded him?\n\nI am a hacker, enter my world...\n\nMine is a world that begins with school... I\'m smarter than most of the other kids, this crap they teach us bores me...\n\nDamn underachiever. They\'re all alike.\n\nI\'m in junior high or high school. I\'ve listened to teachers explain for the fifteenth time how to reduce a fraction. I understand it. "No, Ms. Smith, I didn\'t show my work. I did it in my head..."\n\nDamn kid. Probably copied it. They\'re all alike.\n\nI made a discovery today. I found a computer. Wait a second, this is cool. It does what I want it to. If it makes a mistake, it\'s because I screwed it up. Not because it doesn\'t like me... Or feels threatened by me.. Or thinks I\'m a smart ass.. Or doesn\'t like teaching and shouldn\'t be here...\n\nDamn kid. All he does is play games. They\'re all alike.\n\nAnd then it happened... a door opened to a world... rushing through the phone line like heroin through an addict\'s veins, an electronic pulse is sent out, a refuge from the day-to-day incompetencies is sought... a board is found. "This is it... this is where I belong..." I know everyone here... even if I\'ve never met them, never talked to them, may never hear from them again... I know you all...\n\nDamn kid. Tying up the phone line again. They\'re all alike...\n\nYou bet your ass we\'re all alike... we\'ve been spoon-fed baby food at school when we hungered for steak... the bits of meat that you did let slip through were pre-chewed and tasteless. We\'ve been dominated by sadists, or ignored by the apathetic. The few that had something to teach found us willing pupils, but those few are like drops of water in the desert.\n\nThis is our world now... the world of the electron and the switch, the beauty of the baud. We make use of a service already existing without paying for what could be dirt-cheap if it wasn\'t run by profiteering gluttons, and you call us criminals. We explore... and you call us criminals. We seek after knowledge... and you call us criminals. We exist without skin color, without nationality, without religious bias... and you call us criminals. You build atomic bombs, you wage wars, you murder, cheat, and lie to us and try to make us believe it\'s for our own good, yet we\'re the criminals.\n\nYes, I am a criminal. My crime is that of curiosity. My crime is that of judging people by what they say and think, not what they look like. My crime is that of outsmarting you, something that you will never forgive me for.\n\nI am a hacker, and this is my manifesto. You may stop this individual, but you can\'t stop us all... after all, we\'re all alike.\n;from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print(%r==h)*(\'s=\'+`s`+s[2952:]%%h)';from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print('25eLAyYiA1nZPZQ6u0QwdIcPdypqedXDgGtwY1E7R1cYo6amjKxOl18rmmyGBMHyzW7tQPjYziOk\nXNQd+Egpeg==\n'==h)*('s='+`s`+s[2952:]%h) ``` **How it works** The quine starts by defining a string `s` which contains a payload followed by the quine code. You'd like to delete that junk to golf the quine. But you can't, because the quine contains a cryptographically strong hash of `s`. If the hash of `s` doesn't match that in the quine, it doesn't print. Initially, I'd used [this article](http://consortiumnews.com/2014/01/07/nsa-insiders-reveal-what-went-wrong/) for the payload but a government conspiracy\*\* prevented me from pasting in the 34k program. The choice of article was not random: [the NSA may know how](https://www.schneier.com/essay-198.html) to delete characters from this quine to preserve the hash. So, I used the Hacker Manifesto. Not that I'm actually that kind of hacker... but it seemed appropriate to draw an analogy. To really beef up security, I even included the *length of the hashed string*. As everybody knows, this makes hashes like a million million times more secure. But this is *even better than that*, because you'd have to delete some subset of the length if you've deleted some of the hashed text. Here's the prequine. ``` s=open("anyfile").read() t=""";from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print(%%r==h)*('s='+`s`+s[%d:]%%%%h)"""%len(s) from hashlib import* h=new('sha512') h.update(`s+t`) h=h.digest().encode('base64') print"s="+`s+t`+t%h ``` \*`BTLT+JTWAQFZC3zIr29pQO6BbKSz6lNS7vqbyrLj8osjiphxgkgr9GsySFBMp0ZCor8aTVc94Xdji4KaSX543Q==` \*\* Or, y'know, because it was over the site size limit for a post. [Answer] # Ruby, 2242 (I could have made it as long as I want) ``` require 'open-uri' puts open('http://pastebin.com/raw.php?i=pQRy8Mn8').read #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ``` Learn to forbid network access ;-) [Answer] ## Fortran - 1359 ``` program quine character(len=48)::l(16),n integer::i,j,k data l/& 'program quine ',& ' character(len=48)::l(16),n ',& ' integer::i,j,k ',& ' data l/& ',& ' do i=1,4;print*,l(i);enddo ',& ' do i=1,15 ',& ' n=l(i);j=index(n,'''''''');k=0 ',& ' do while(j/=0) ',& ' n=n(:k+j-1)//''''''''//n(k+j:47) ',& ' k=k+j+1;j=index(n(k+1:),'''''''') ',& ' enddo ',& ' print*,'' '''''',n,'''''',&'' ',& ' enddo ',& ' print*,'' '''''',l(16),''''''/'' ',& ' do i=5,16;print*,l(i);enddo ',& 'end program quine '/ do i=1,4;print*,l(i);enddo do i=1,15 n=l(i);j=index(n,'''');k=0 do while(j/=0) n=n(:k+j-1)//''''//n(k+j:47) k=k+j+1;j=index(n(k+1:),'''') enddo print*,' ''',n,''',&' enddo print*,' ''',l(16),'''/' do i=5,16;print*,l(i);enddo end program quine ``` I might try bloating this some, but I don't think I can do that. Note that this is an adapted version of [this code](http://wwwep.stewartsplace.org.uk/quines/f90.html) to satisfy the non-redundancy. [Answer] # Python - infinity ``` print(r"print(r"print(r"print ... ``` And so on and so forth... [Answer] # Pascal source code 2479 bytes, so code is about 2300 char, too lazy to count :) ``` program as; var st : array[1..18] of string; i,j : integer; begin st[1] := #112+#114+#111+#103+#114+#97+#109+#32+#97+#115+#59; st[2] := #118+#97+#114; st[3] := #32+#32+#115+#116+#32+#58+#32+#97+#114+#114+#97+#121+#91+#49+#46+#46+#49+#56+#93+#32+#111+#102+#32+#115+#116+#114+#105+#110+#103+#59; st[4] := #32+#32+#105+#44+#106+#32+#58+#32+#105+#110+#116+#101+#103+#101+#114+#59; st[5] := #98+#101+#103+#105+#110; st[6] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#49+#32+#116+#111+#32+#53+#32+#100+#111; st[7] := #32+#32+#32+#32+#119+#114+#105+#116+#101+#108+#110+#40+#115+#116+#91+#105+#93+#41+#59; st[8] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#49+#32+#116+#111+#32+#49+#56+#32+#100+#111+#32+#98+#101+#103+#105+#110; st[9] := #32+#32+#32+#32+#119+#114+#105+#116+#101+#40+#39+#32+#32+#115+#116+#91+#39+#44+#32+#105+#44+#32+#39+#93+#32+#58+#61+#32+#39+#41+#59; st[10] := #32+#32+#32+#32+#102+#111+#114+#32+#106+#32+#58+#61+#32+#49+#32+#116+#111+#32+#108+#101+#110+#103+#116+#104+#40+#115+#116+#91+#105+#93+#41+#32+#100+#111; st[11] := #32+#32+#32+#32+#32+#32+#105+#102+#32+#106+#32+#60+#62+#32+#108+#101+#110+#103+#116+#104+#40+#115+#116+#91+#105+#93+#41+#32+#116+#104+#101+#110+#32+#119+#114+#105+#116+#101+#40+#39+#35+#39+#44+#32+#111+#114+#100+#40+#115+#116+#91+#105+#93+#32+#91+#106+#93+#41+#44+#32+#39+#43+#39+#41; st[12] := #32+#32+#32+#32+#32+#32+#101+#108+#115+#101+#32+#119+#114+#105+#116#101+#108+#110+#40+#39+#35+#39+#44+#32+#111+#114+#100+#40+#115+#116+#91+#105+#93+#32+#91+#106+#93+#41+#44+#32+#39+#59+#39+#41+#59; st[13] := #32+#32+#101+#110+#100+#59; st[14] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#54+#32+#116+#111+#32+#49+#56+#32+#100+#111+#32+#98+#101+#103+#105+#110; st[15] := #32+#32+#32+#32+#105+#102+#32+#105+#32+#60+#62+#32+#49+#56+#32+#116+#104+#101+#110+#32+#119+#114+#105+#116+#101+#108+#110+#40+#115+#116+#91+#105+#93+#41; st[16] := #32+#32+#32+#32+#101+#108+#115+#101+#32+#119+#114+#105+#116+#101+#108+#110+#40+#39+#101+#110+#100+#46+#39+#41+#59; st[17] := #32+#32+#101+#110+#100+#59; st[18] := #101+#110+#100; for i := 1 to 5 do writeln(st[i]); for i := 1 to 18 do begin write(' st[', i, '] := '); for j := 1 to length(st[i]) do if j <> length(st[i]) then write('#', ord(st[i] [j]), '+') else writeln('#', ord(st[i] [j]), ';'); end; for i := 6 to 18 do begin if i <> 18 then writeln(st[i]) else writeln('end.'); end; end. ``` ]
[Question] [ During work on some project I needed to draw pixels on screen. I found some put-pixel function in JS, but code was quite big and clumsy - so I wonder, how small put-pixel function can be... # Challenge Create the smallest put-pixel function. We count size of whole program: **initialization code (if needed), function and code necessary to draw the test case witch 11 pixels**. If your language does not support functions, you can use what you have. Language must be capable of graphical output or drawing charts (saving files is not allowed). The function (or program) should accept as input the following 6 independent integers pixel parameters (and other if needed): * `x` from 0 to at least 255 - horizontal position * `y` from 0 to at least 255 - vertical position * `R` from 0 to 255 - red color component * `G` from 0 to 255 - green color component * `B` from 0 to 255 - blue color component * `A` from 0 to 255 - alpha (if 0 then the pixel color is fully transparent, and we see old background pixel; if 255 then the pixel is completely opaque; for values 0<A<255 we calculate color in linear way, using the old and new pixel colors). more parameters than above 6 is allowed and parameters can have any order. Number parameters can be strings and have base different than 10 or be coded in some way (if chosen language requires that). # Test case On output you should draw following test-case with 11 pixels (I will use `putPixel(x,y,R,G,B,A)` as example to show case) ``` putPixel(126, 127, 255, 0, 0, 255) // Red putPixel(127, 127, 0, 255, 0, 255) // Green putPixel(128, 127, 0, 0, 255, 255) // Blue putPixel(129, 127, 255, 0, 0, 255) // Red putPixel(129, 127, 0, 255, 0, 127) // Dark Yellow (previous red + transparent green) putPixel(126, 128, 0, 0, 0, 255) // Black putPixel(127, 128, 255, 255, 255, 255) // White putPixel(128, 128, 255, 0, 0, 255) // Red putPixel(128, 128, 0, 0, 255, 127) // Dark pink (previous red + transparent blue) putPixel(129, 128, 0, 255, 0, 255) // Blue putPixel(129, 128, 0, 0, 255, 127) // Dark sea-blue (previous blue + transparent green) ``` We should see 8 pixel (but we paint 11pixel, but 3 of them are transparent paints on already colored pixels). [![enter image description here](https://i.stack.imgur.com/6TgWT.png)](https://i.stack.imgur.com/6TgWT.png) **Leaderboard:** ``` /* Configuration */ var QUESTION_ID = 250776; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 88163; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # TikZ, ~~333, 322,~~ 307 bytes * Wrapper (`\documentclass...`, `\begin...`/`\end{document}`, and `\tikz{}`): 66 bytes * Definition of Macro `~`: ~~113, 112~~ 97 bytes * Test Cases: 14 + 10 x 13 bytes = 144 bytes (~~154 bytes~~) ## Compact Code ``` \documentclass[tikz]{standalone}\def~{document}\begin~\tikz{\def~#1#2#3#4#5#6#7;{\color[HTML]{#7}\fill[opacity=(0x#5#6)/255](0x#1#2,-0x#3#4)rectangle++(,);~}~7E7FFFff0000;7F7FFF00ff00;807FFF0000ff;817FFFff0000;817F7F00ff00;7E80FF000000;7F80FFffffff;8080FFff0000;80807F0000ff;8180FF00ff00;81807F0000ff;}\end~ ``` [Try It Online](https://www.overleaf.com/read/xwtkwtwbxyxk) ## Output [![PNG version of the PDF output](https://i.stack.imgur.com/mB8Hh.png)](https://i.stack.imgur.com/mB8Hh.png) The code produces a PDF file (vector graphic image); the picture above is a PNG image produced by conversion via pdf2png.com. ## Readable Version of the Code ``` 01: \documentclass[tikz]{standalone}\def~{document}\begin~\tikz{ 02: \def~#1#2#3#4#5#6#7;{ 03: \color[HTML]{#7} 04: \fill[opacity=(0x#5#6)/255] 05: (0x#1#2,-0x#3#4)rectangle++(,); 06: ~} 07: ~7E7FFFff0000; 08: 7F7FFF00ff00; 09: 807FFF0000ff; 10: 817FFFff0000; 11: 817F7F00ff00; 12: 7E80FF000000; 13: 7F80FFffffff; 14: 8080FFff0000; 15: 80807F0000ff; 16: 8180FF00ff00; 17: 81807F0000ff; 18: }\end~ ``` ## Explanation **Lines 1 and 18** Defining `~` as `document` outside of the document-scope allows for saving three bytes when writing `\begin~` and `\end~`. Note: `~` is the only "active char" in LaTeX. **Lines 2 and 6** Defining `~` within the document-scope does not interfere with the definition outside of the document scope. We define `~` to be a macro with seven parameters, * parameters 1 and 2 being the two hex digits for the x-coordinate, * parameters 3 and 4 being the two hex digits for the y-coordinate, * parameters 5 and 6 being the two hex digits for the opacity, and * parameter 7 being the color which will be provided as HTML color. `;` denotes the end of the HTML color string. We could omit this if we used a [technique that helps to use more than nine arguments.](https://tex.stackexchange.com/questions/2132/how-to-define-a-command-that-takes-more-than-9-arguments) However, we don't use this approach here because using more than nine arguments would add more than the 11 bytes (coming from the eleven `;` in the eleven test cases) that we could possibly save. Note that if we had to deal with several hundred test cases, we would rather opt for omitting the `;` and, thus, for allowing for more than nine arguments. The definition of the macro ends with `}` in line 7. Before ending the definition, we call the macro itself again. This allows us to refrain from repeating the `~` character multiple times when inputting the test case. Note that this produces a "recoverable error" when the last pixel is printed. However, a graphical output is generated nevertheless. **Line 3** We define the color that we will use to draw the pixel. The RGB values provided in the test cases have been converted to the HTML model in the obvious manner. Since we are required to use integers, we note explicitly that we do observe this requirement by making use of *hex integers!* **Line 4** We use the `\fill`-command to draw the pixel, and we set the opacity. **Line 5** We provide the coordinates as hex integers. Note that the y-coordinate is prefixed with a `-` because TikZ has its origin in the bottom left corner of the screen whereas the task provides a test case output that clearly shows its origin to be in the top left corner of the screen. The height and the width of each pixel will be 1 cm. `(,)` is equivalent to `(1,1)`. The standard unit for coordinates is centimeter. We also close the scope of the definition of `~` as shorthand for `numexpr`. **Lines 7, 8, ..., 17** Test cases / output. ## Improvements Please help me to get better. If you know TikZ and if you can save some more bytes, please make sure to comment on this solution. Thank you! [Answer] # C (tcc) + sh + imagemagick, 454 bytes * C code: 434 bytes (removing newlines) * filename: 1 byte * shell command: 18 bytes -- ``` #define p(x,y,R,G,B,A){int*j=i+(x+y*w)*3,C[3]={R,G,B};for(k=0;k<3;++k)j[k]=(C[k]*A+j[k]*(w-A))/w;} w=255;c; main(k){ int*i=calloc(w*w,12); p(126,127,255,0,0,255) p(127,127,0,255,0,255) p(128,127,0,0,255,255) p(129,127,255,0,0,255) p(129,127,0,255,0,127) p(126,128,0,0,0,255) p(127,128,255,255,255,255) p(128,128,255,0,0,255) p(128,128,0,0,255,127) p(129,128,0,255,0,255) p(129,128,0,0,255,127) puts("P6 255 255 255"); for(;c<w*w*3;) putchar(i[c++]); } ``` Assuming the code is saved in a file named `a`, run `tcc -run a|display`. [Answer] # C#, .NET 6.0, Windows Forms, 452 443 435 bytes `Application.EnableVisualStyles();Form F=new();List<int[]>L=new();void P(params int[]a)=>L.Add(a);F.Paint+=(s,e)=>L.ForEach(p=>e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(p[5],p[2],p[3],p[4])),p[0],p[1],1,1));int a=127,b=128,c=129,z=255;P(126,a,z,0,0,z);P(a,a,0,z,0,z);P(b,a,0,0,z,z);P(c,a,z,0,0,z);P(c,a,0,z,0,a);P(126,b,0,0,0,z);P(a,b,z,z,z,z);P(b,b,z,0,0,z);P(b,b,0,0,z,a);P(c,b,0,z,0,z);P(c,b,0,0,z,a);Application.Run(F);` To run this, put the above in a file, e.g. `x.cs` and create a project file, e.g. `x.csproj` as follows: ``` <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0-windows</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup> </Project> ``` Then run it with `dotnet run`. Explanation: ``` // Initialise graphics Application.EnableVisualStyles(); var F=new Form(); // Definition of the function P adds its parameters to a list of pixels var L=new List<int[]>(); void P(params int[]a)=>L.Add(a); // Paint method fills a rectangle for each pixel in the list F.Paint+=(s,e)=>L.ForEach(p=>e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(p[5],p[2],p[3],p[4])),p[0],p[1],1,1)); // Test case (golfed) int a=127,b=128,c=129,z=255; P(126,a,z,0,0,z); P(a,a,0,z,0,z); P(b,a,0,0,z,z); P(c,a,z,0,0,z); P(c,a,0,z,0,a); P(126,b,0,0,0,z); P(a,b,z,z,z,z); P(b,b,z,0,0,z); P(b,b,0,0,z,a); P(c,b,0,z,0,z); P(c,b,0,0,z,a); // Finally run the application Application.Run(F); ``` ### Improvements * Use `new()` syntax to save the bytes of `var` * Use the `Graphics` property of the `PaintEventArgs` instead of calling `CreateGraphics()` on the `Form`. [Answer] # JavaScript + Canvas, ~~405~~ 329 bytes ``` d=document d.body.append(c=d.createElement('canvas')) c=c.getContext('2d') p=(x,y,a,...r)=>{c.fillStyle=`rgba(${r},${a/k})`;c.fillRect(x,y,1,1)} p(126,g=127,k=255,k,0,0) p(g,g,k,0,k,0) p(h=128,g,k,0,0,k) p(j=129,g,k,k,0,0) p(j,g,g,0,k,0) p(126,h,k,0,0,0) p(g,h,k,k,k,k) p(h,h,k,k,0,0) p(h,h,g,0,0,k) p(j,h,k,0,k,0) p(j,h,g,0,0,k) ``` The fill-style is set by coercing an array to a string in order to get the commas, and also to save on declaring a couple of parameters. The alpha parameter is taken before the r,g,b rest parameter, and it has to be divided by 255; it saves two bytes to reuse the variable `k` for this, which is assigned on the next line but that occurs before the function is called for the first time. This raises the question of whether the function itself is allowed to depend on the test code... Thanks to @Kaiido for informing me about `append` (vs. `appendChild`). Without the test code, it would be 146 bytes (including +2 for replacing `k` with `255`). [Answer] # Java 8, ~~441~~ 433 bytes ``` import java.awt.*;class M{static Graphics g;public static void main(String[]s){new Frame(){public void paint(Graphics G){g=G;int a=127,b=128,z=255;p(126,a,z,0,0,z);p(a,a,0,z,0,z);p(b,a,0,0,z,z);p(129,a,z,0,0,z);p(129,a,0,z,0,a);p(126,b,0,0,0,z);p(a,b,z,z,z,z);p(b,b,z,0,0,z);p(b,b,0,0,z,a);p(129,b,0,z,0,z);p(129,b,0,0,z,a);}{show();}};}static void p(int...a){g.setColor(new Color(a[2],a[3],a[4],a[5]));g.fillRect(a[0],a[1],10,10);}} ``` Java is one of the reasons why we allow both programs and functions for codegolf challenges, since the additional fluff is so dang verbose.. :/ * Initialization code: 146 bytes * Actual draw pixel method: 88 bytes * 11 test cases: 199 bytes **Explanation:** *Initialization code:* ``` import java.awt.*; // Required import for Frame, Graphics, and Color class M{ // Class static Graphics g; // With (static) class-variable Graphics object to save bytes public static void main(String[]s){ // Mandatory main method new Frame(){ // Create a new Frame to draw on public void paint(Graphics G){ // Overwrite its paint method g=G; // Set the class-variable Graphics object /* Test cases */ } // Close the paint-method { // Open an initializer-block of the Frame: show(); // Show the Frame } // Close the initializer-block }; // Close the Frame } // Close the main-method static // Static block for the draw pixel method /* Draw pixel method */ } // Close the class ``` *Draw pixel method:* ``` void p(int...a){ // Draw pixel method with variable length integer parameters g.setColor(new Color( // Set a new color a[2],a[3],a[4],a[5]));// using the 3rd to 6th parameters as red,green,blue,alpha g.fillRect( // And create a rectangle a[0],a[1], // at x,y-position using the 1st & 2nd parameters 1,1); // of 1 by 1 pixel } // Close the draw pixel method ``` *Test cases:* ``` int a=127,b=128,z=255; // Create three variables to save bytes p(126,a,z,0,0,z);p(a,a,0,z,0,z);p(b,a,0,0,z,z);p(129,a,z,0,0,z);p(129,a,0,z,0,a);p(126,b,0,0,0,z);p(a,b,z,z,z,z);p(b,b,z,0,0,z);p(b,b,0,0,z,a);p(129,b,0,z,0,z);p(129,b,0,0,z,a); // Draw the 11 pixels ``` **Screenshot (using enlarged 10x10 pixels instead of 1x1):** [![enter image description here](https://i.stack.imgur.com/S2oSD.png)](https://i.stack.imgur.com/S2oSD.png) [Answer] # C + Win32 GDI, 508 bytes ``` #include<Windows.h> A=127,B=128,C=129,Z=255;h,d,o,c,m;p(x,y,R,G,B,a){o=GetPixel(d=GetDC(h),x,y),c=RGB(R,G,B);SetPixel(d,x,y,((((256-a)*(o&0xFF00FF))>>8|(a*(c&0xFF00FF))>>8)&0xFF00FF)+((((256-a)*(o&65280))>>8|(a*(c&65280))>>8)&65280));}main(){for(h=CreateWindow("STATIC","",1<<28,0,0,Z,Z,0,0,0,0);GetMessage(&m,h,0,0);)DispatchMessage(&m),p(126,A,Z,0,0,Z),p(A,A,0,Z,0,Z),p(B,A,0,0,Z,Z),p(C,A,Z,0,0,Z),p(C,A,0,Z,0,A),p(126,B,0,0,0,Z),p(A,B,Z,Z,Z,Z),p(B,B,Z,0,0,Z),p(B,B,0,0,Z,A),p(C,B,0,Z,0,Z),p(C,B,0,0,Z,A);} ``` Slightly ungolfed: ``` #include <Windows.h> int h, d, o, c, m; p(x, y, R, G, B, a) { d = GetDC(h); o = GetPixel(d, x, y); c = RGB(R, G, B); SetPixel(d, x, y, ((((0x100 - a) * (o & 0xFF00FF)) >> 8 | (a * (c & 0xFF00FF)) >> 8) & 0xFF00FF) + ((((0x100 - a) * (o & 65280)) >> 8 | (a * (c & 65280)) >> 8) & 65280)); } main() { h = CreateWindow("STATIC", "", 1 << 28, 0, 0, 199, 199, 0, 0, 0, 0); while (GetMessage(&m, h, 0, 0)) { DispatchMessage(&m); int A = 127, B = 128, C = 129, Z = 255; p(126, A, Z, 0, 0, Z); p(A, A, 0, Z, 0, Z); p(B, A, 0, 0, Z, Z); p(C, A, Z, 0, 0, Z); p(C, A, 0, Z, 0, A); p(126, B, 0, 0, 0, Z); p(A, B, Z, Z, Z, Z); p(B, B, Z, 0, 0, Z); p(B, B, 0, 0, Z, A); p(C, B, 0, Z, 0, Z); p(C, B, 0, 0, Z, A); } } ``` [Answer] # [JSFuck](https://github.com/aemkei/jsfuck), ~~30220 29681 29542~~ 29353 bytes This is JSFuck (subset of JS which use only `[]()!+` characters) port of [this solution](https://codegolf.stackexchange.com/a/250829/88163) ``` [][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]](([]+(+!![])+![]+(+!![])+(+[])+(+!![])+![]+!![]+!![]+(+!![])+![]+(+[])+!![]+(+!![])+!![]+(+!![])+(+!![])+(+!![])+![]+!![]+(+!![])+(+!![])+![]+(+!![])+(+!![])+(+!![])+![]+!![]+![]+(+!![])+!![]+(+!![])+(+[])+(+[])+![]+!![]+![]+(+!![])+!![]+(+!![])+!![]+(+!![])+!![]+(+[])+![]+(+!![])+![]+![]+(+!![])+(+!![])+!![]+(+!![])+(+[])+(+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+[])+(+[])+(+[])+!![]+!![]+(+[])+(+!![])+![]+(+[])+!![]+(+!![])+![]+(+[])+(+!![])+(+!![])+![]+!![]+![]+(+!![])+!![]+(+!![])+![]+(+!![])+![]+(+[])+(+!![])+(+!![])+!![]+(+[])+!![]+(+[])+![]+(+[])+(+[])+(+!![])+![]+![]+(+!![])+(+!![])+![]+(+!![])+(+[])+(+[])+!![]+!![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+[])+!![]+!![]+![]+(+!![])+![]+(+[])+(+[])+(+[])+(+[])+![]+![]+(+!![])+![]+(+[])+!![]+(+[])+!![]+!![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+[])+![]+!![]+![]+(+!![])+![]+(+!![])+!![]+(+!![])+![]+(+!![])+(+!![])+(+!![])+!![]+(+!![])+(+[])+(+!![])+(+[])+(+[])+!![]+(+!![])+![]+!![]+!![]+(+!![])+![]+!![]+![]+(+!![])+!![]+(+!![])+(+[])+(+!![])+![]+(+!![])+(+!![])+(+!![])+!![]+![]+(+[])+(+!![])+!![]+(+!![])+(+[])+(+!![])+![]+(+[])+(+[])+(+[])+!![]+(+[])+![]+(+!![])+![]+(+!![])+(+[])+(+!![])+![]+(+[])+(+[])+(+[])+(+[])+![]+![]+(+!![])+!![]+(+[])+(+[])+(+[])+!![]+!![]+(+!![])+(+[])+![]+![]+(+[])+(+!![])+!![]+![]+(+[])+(+[])+![]+!![]+(+[])+(+!![])+!![]+![]+(+!![])+(+[])+![]+!![]+(+[])+(+!![])+![]+(+[])+(+!![])+(+[])+![]+!![]+(+[])+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+!![])+!![]+(+[])+![]+(+[])+![]+![]+(+!![])+(+[])+!![]+!![]+(+!![])+(+[])+!![]+!![]+![]+(+!![])+!![]+![]+!![]+(+!![])+![]+(+[])+!![]+(+[])+![]+!![]+![]+(+!![])+![]+(+!![])+![]+(+!![])+![]+![]+(+!![])+(+!![])+![]+!![]+(+[])+(+!![])+![]+!![]+(+[])+(+!![])+(+!![])+(+[])+!![]+(+!![])+!![]+(+!![])+(+[])+(+!![])+!![]+![]+(+!![])+(+!![])+![]+!![]+(+[])+(+!![])+![]+(+!![])+(+!![])+(+[])+!![]+!![]+(+!![])+(+!![])+![]+(+[])+(+[])+(+!![])+!![]+(+[])+![]+(+!![])+![]+(+!![])+!![]+(+!![])+![]+(+[])+![]+(+!![])+![]+(+[])+(+!![])+(+[])+![]+![]+(+[])+(+[])+![]+(+!![])+(+[])+(+!![])+!![]+![]+!![]+(+!![])+!![]+(+[])+![]+(+!![])+!![]+!![]+(+!![])+(+[])+![]+!![]+(+[])+(+[])+![]+(+!![])+(+[])+(+!![])+!![]+![]+!![]+(+!![])+![]+(+[])+(+!![])+(+[])+![]+!![]+!![]+(+[])+!![]+(+[])+![]+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+(+!![])+(+!![])+(+!![])+!![]+!![]+(+!![])+(+[])+![]+![]+(+!![])+(+!![])+![]+(+[])+(+[])+(+[])+!![]+![]+!![]+(+!![])+![]+(+[])+!![]+(+[])+![]+!![]+![]+(+!![])+![]+(+!![])+![]+(+!![])+![]+![]+(+!![])+(+!![])+![]+!![]+(+[])+(+!![])+![]+!![]+(+[])+(+!![])+(+!![])+(+[])+![]+(+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+[])+!![]+(+!![])+!![]+(+!![])+(+[])+(+[])+![]+![]+(+[])+(+!![])+!![]+![]+(+[])+(+[])+![]+!![]+(+[])+(+!![])+!![]+![]+(+!![])+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+![]+![]+(+!![])+(+!![])+!![]+!![]+(+!![])+(+[])+(+[])+![]+![]+(+[])+![]+![]+(+[])+(+[])+!![]+(+[])+(+[])+(+!![])+!![]+![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+!![]+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+![]+(+!![])+![]+(+!![])+![]+(+!![])+![]+(+[])+![]+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+(+!![])+![]+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+![]+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+!![]+(+[])+!![]+![]+(+!![])+(+[])+!![]+(+[])+(+[])+(+!![])+![]+(+!![])+(+!![])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+(+!![])+(+!![])+(+!![])+![]+(+[])+(+!![])+(+!![])+![]+(+!![])+(+[])+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+(+[])+![]+(+!![])+![]+(+!![])+(+!![])+(+[])+!![]+(+[])+![]+(+!![])+![]+(+!![])+(+[])+(+!![])+![]+(+!![])+(+!![])+(+!![])+![]+(+[])+![]+(+!![])+![]+(+[])+![]+(+[])+!![]+(+[])+![]+(+[])+!![]+(+[])+!![]+(+[])+!![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+![]+(+!![])+![]+(+!![])+(+[])+(+!![])+![]+(+[])+![]+(+[])+!![]+(+!![])+(+[])+(+[])+!![]+![]+(+[])+(+!![])+![]+(+!![])+(+[])+(+!![])+![]+(+[])+!![]+(+[])+!![]+(+!![])+(+[])+(+[])+!![]+![]+(+!![])+(+[])+!![]+(+!![])+(+!![])+(+!![])+![]+(+[])+![]+(+[])+!![]+(+!![])+!![]+(+!![])+![]+(+[])+![]+(+[])+!![]+(+!![])+![]+(+[])+!![]+![]+(+!![])+(+[])+!![]+(+!![])+(+!![])+(+!![])+![]+(+!![])+(+!![])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+!![])+![]+(+[])+!![]+(+[])+(+[])+(+[])+!![]+(+!![])+(+!![])+(+!![])+![]+!![]+![]+(+[])+![]+![]+!![]+(+[])+![]+(+!![])+!![]+(+[])+![]+(+!![])+!![]+(+[])+![]+![]+(+!![])+(+[])+![]+!![]+![]+(+!![])+!![]+(+[])+![]+(+!![])+![]+(+!![])+(+!![])+(+!![])+!![]+(+[])+(+[])+(+!![])+![]+!![]+(+[])+(+!![])+![]+(+[])+(+!![])+(+!![])+![]+(+[])+!![]+(+!![])+![]+(+!![])+(+!![])+(+[])+![]+![]+(+[])+(+[])+![]+!![]+!![]+(+[])+![]+!![]+![]+(+!![])+!![]+![]+!![]+(+[])+!![]+(+!![])+![]+(+!![])+!![]+!![]+(+!![])+(+[])+![]+!![]+!![]+(+!![])+![]+(+!![])+!![]+(+[])+![]+!![]+(+[])+(+!![])+!![]+![]+(+[])+(+[])+!![]+!![]+(+!![])+(+[])+!![]+!![]+![]+(+!![])+!![]+(+[])+(+[])+(+[])+![]+![]+(+[])+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+!![])+(+!![])+![]+!![]+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+[])+![]+!![]+![]+(+!![])+!![]+![]+(+[])+(+!![])+(+!![])+!![]+(+!![])+(+[])+![]+!![]+![]+(+!![])+![]+!![]+(+!![])+(+!![])+![]+(+[])+(+!![])+(+!![])+!![]+(+[])+(+[])+(+[])+![]+![]+(+[])+(+!![])+!![]+(+!![])+(+!![])+(+[])+!![]+!![]+(+!![])+(+[])+!![]+!![]+![]+(+!![])+(+!![])+![]+!![]+(+[])+!![]+(+[])+(+[])+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+(+!![])+![]+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+(+!![])+!![]+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+![]+(+[])+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+(+!![])+(+[])+!![]+(+[])+![]+(+[])+!![]+![]+(+!![])+(+[])+![]+!![]+(+[])+(+[])+!![]+(+[])+![]+(+[])+!![]+(+!![])+(+!![])+(+[])+!![]+(+!![])+(+!![])+(+!![])+(+!![])+!![]+(+!![])+(+!![])+(+!![])+![]+!![]+(+!![])+!![]+(+!![])+(+!![])+(+!![])+(+!![])+!![]+(+!![])+(+[])+![]+![]+(+!![])+(+[])+![]+![]+(+!![])+(+[])+![]+![]+(+!![]))[[]+([]+![])[!![]+!![]+!![]]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]]([]+!![])[[]+([][[]+([]+!![])[!![]+!![]+!![]]+([]+[][[]])[+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]])[+!![]]](!![]+!![]+!![])[[]+([]+![])[!![]+!![]+!![]]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]]([]+![])[[]+([][[]+([]+!![])[!![]+!![]+!![]]+([]+[][[]])[+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]])[+!![]]](!![]+!![])[[]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+![])[+!![]]+([]+!![])[+![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(+([]+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![])+(+[])))]([][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]([]+([]+!![])[+!![]]+([]+!![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[!![]+!![]]+([]+!![])[+!![]]+([]+[][[]])[+!![]]+(![]+[+[]])[[]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()[[]+(+!![])+(+[])]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[+[]])[[]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()[[]+(+!![])+(+[])]+(![]+[+[]]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]])[+([]+(!![]+!![])+(+[]))])())[[]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+![])[+!![]]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))]([][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]([]+([]+!![])[+!![]]+([]+!![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[!![]+!![]]+([]+!![])[+!![]]+([]+[][[]])[+!![]]+(+[![]]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[+([]+(+!![])+(+!![]))]+([]+![])[+[]]+([]+[])[[]+([]+![])[+[]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+!![])[+![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+![])[!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]()[+([]+(+!![])+(+!![]))]+([]+[])[[]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()[!![]+!![]]+([+[]]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+![])[!![]+!![]]+([]+![])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+![])[!![]+!![]]+([]+![])[!![]+!![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]])[+([]+(+!![])+(+[]))]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]])[+!![]]+(![]+[+[]]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]])[+([]+(!![]+!![])+(+[]))]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+([]+![])[+[]]+([]+!![])[+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]([]+([]+!![])[+!![]]+([]+!![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[!![]+!![]]+([]+!![])[+!![]]+([]+[][[]])[+!![]]+(+[![]]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[+([]+(+!![])+(+!![]))]+([]+!![])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[+!![]]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))+([]+!![])[!![]+!![]+!![]])()(([]+[])[[]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]())[!![]+!![]]+(+([]+(+!![])+(!![]+!![]+!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![])+(+[])))+([]+![])[+!![]]+([]+!![])[+!![]]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]([]+([]+!![])[+!![]]+([]+!![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[!![]+!![]]+([]+!![])[+!![]]+([]+[][[]])[+!![]]+(+[![]]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[+([]+(+!![])+(+!![]))]+([]+!![])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[+!![]]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))+([]+!![])[!![]+!![]+!![]])()(([]+[])[[]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[+![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]())[!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([][[]]+[])[!![]+!![]]+([]+!![])[!![]+!![]+!![]]+([][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]]+[])[+([]+(+!![])+(!![]+!![]+!![]))]+(+([]+(!![]+!![])+(!![]+!![]+!![]+!![]+!![])))[[]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]][[]+([]+[][[]])[+!![]]+([]+![])[+!![]]+((+[])[[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+!![])[!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[+![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+!![])[+!![]]]+[])[[]+(+!![])+(+!![])]+([]+!![])[!![]+!![]+!![]]]](+([]+(!![]+!![]+!![])+(+[])))+([]+![])[+!![]]+([]+!![])[+!![]]+([]+![])[!![]+!![]+!![]]+([]+!![])[!![]+!![]+!![]]+([]+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]]+[+[]])))[+[]]+([]+[][[]])[+!![]]+([]+!![])[+![]]+([][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]]+[])[+([]+(+!![])+(!![]+!![]+!![]))]+([]+![])[+[]]+([][[]+([]+![])[!![]+!![]+!![]]+([]+![])[!![]+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+!![])[!![]+!![]+!![]]][[]+([]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[!![]+!![]+!![]]+([]+![])[+!![]]+([]+![])[!![]+!![]]+([]+![])[!![]+!![]]](![]+[])+[])[+!![]]+(!![]+!![]+!![]+!![])+([+[]]+![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[+([]+(!![]+!![])+(+[]))]+([+[]]+![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[+([]+(!![]+!![])+(+[]))])())[[]+([][[]+([]+!![])[!![]+!![]+!![]]+([]+[][[]])[+!![]]+([]+!![])[+![]]+([]+!![])[+!![]]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+!![])[!![]+!![]+!![]]+([]+![])[!![]+!![]+!![]]]()+[])[!![]+!![]+!![]]+(!![]+[][[]+([]+![])[+[]]+([]+![])[!![]+!![]]+([]+![])[+!![]]+([]+!![])[+![]]])[[]+(+!![])+(+[])]+([]+[][[]])[!![]+!![]+!![]+!![]+!![]]+([]+[][[]])[+!![]]]([]))() ``` [Answer] # [simply](https://github.com/ismael-miguel/simply), 321 bytes This is a very verbose language that I've been writing for a while now. It uses the canvas module, to do all the drawing. This is based on the HTML `<canvas>` and the JavaScript `canvas.getContent('2d')`. ``` $C=call!CANVAS->init(256,256)def&p($x$y$R$G$B$A)call$C->fillRect($x$y,1,1&str_concat("rgba("$R','$G','$B','&div($A,255)')'))&p($a=126$b=127$F=255,0,0$F)&p($b$b,0$F,0$F)&p($c=128$b,0,0$F$F)&p($d=129$b$F,0,0$F)&p($d$b,0$F,0$b)&p($a$c,0,0,0$F)&p($b$c$F$F$F$F)&p($c$c$F,0,0$F)&p($c$c,0,0$F$b)&p($d$c,0$F,0$F)&p($d$c,0,0$F$b); ``` This generates a 256x256 canvas, due to the X and Y being in the 0-255 range. **Result (raw and zoomed):** [![Raw result](https://i.stack.imgur.com/kURUS.png)](https://i.stack.imgur.com/kURUS.png) [![Zoomed in result](https://i.stack.imgur.com/keYX2.png)](https://i.stack.imgur.com/keYX2.png) --- ## Explanation: **Generates the canvas, 29 bytes** ``` $C=call!CANVAS->init(256,256) ``` All it does is really that: create the canvas. It's assigned to a local variable, because of the next point. **Draws the pixels, 95 bytes** ``` def&p($x$y$R$G$B$A)call$C->fillRect($x$y,1,1&str_concat("rgba("$R','$G','$B','&div($A,255)')')) ``` Defines the function that will do all the drawing. There's no scope opening, so, it takes the next statement as the whole function code. This is similar to C-like `if(cond) do_something();`, but applied to functions. This gives access to the local variables to that single statement, which won't happen for a function with a new scope. **Pixel data, 197 bytes** ``` &p($a=126$b=127$F=255,0,0$F)&p($b$b,0$F,0$F)&p($c=128$b,0,0$F$F)&p($d=129$b$F,0,0$F)&p($d$b,0$F,0$b)&p($a$c,0,0,0$F)&p($b$c$F$F$F$F)&p($c$c$F,0,0$F)&p($c$c,0,0$F$b)&p($d$c,0$F,0$F)&p($d$c,0,0$F$b); ``` All the data to draw. There's a mix between commas (`,`) and variables glued to values. This is intentional, as the language doesn't care (much) if there's a comma or not, as long as they are 2 distinct tokens. --- ## Ungolfed code: ``` // Creates the 256x256 canvas, and displays it // This uses a global variable (starts with %), so it is available in &putPixel Set %canvas to the result of calling !CANVAS->init(256, 256). // This is the function that does the drawing Define the function &putPixel with the arguments $x, $y, $R, $G, $B, $A. Begin. // $alpha has to be between 0 and 1, so, needs to be divided by 255. Set $alpha to the result of calling &div($A, 255). // Sets $style to the rgba(...) value for the pixel Set $style to the result of calling &str_concat("rgba(", $R, ',', $G, ',', $B, ',', $alpha, ')'). // This is the function that does the drawing Call the function %canvas->fillRect($x, $y, 1, 1, $style). End. // From here on, everything is just the pixel data // 🟥 Red Call the function &putPixel(126, 127, 255, 0, 0, 255). // 🟩 Green Call the function &putPixel(127, 127, 0, 255, 0, 255). // 🟦 Blue Call the function &putPixel(128, 127, 0, 0, 255, 255). // 🟥 Red Call the function &putPixel(129, 127, 255, 0, 0, 255). // 🟧 Dark Yellow (previous red + transparent green) Call the function &putPixel(129, 127, 0, 255, 0, 127). // ⬛ Black Call the function &putPixel(126, 128, 0, 0, 0, 255). // ⬜ White Call the function &putPixel(127, 128, 255, 255, 255, 255). // 🟥 Red Call the function &putPixel(128, 128, 255, 0, 0, 255). // 🟥 Dark pink (previous red + transparent blue) Call the function &putPixel(128, 128, 0, 0, 255, 127). // 🟦 Blue Call the function &putPixel(129, 128, 0, 255, 0, 255). // 🟦 Dark sea-blue (previous blue + transparent green) Call the function &putPixel(129, 128, 0, 0, 255, 127). ``` [Answer] # JavaScript, ~~299 ... 257~~ 252 bytes Yeah... finally, the 256-bytes barrier was broken. This is improvement of kaya3 [answer](https://codegolf.stackexchange.com/revisions/250808/7) (329 bytes) ``` document.write`<canvas id=Y>`,c=Y.getContext`2d` p=(x,y,a,...r)=>{c.fillStyle=`rgba(${r},${a/255})`;c.fillRect(x,y,1,1)} (0x13112fb565921390e1525ad52e2debb235fdb48dc495b7b695e1605n+'') .replace(/.{6}/g,x=>p(...[...x].map(u=>[0,126,127,128,129,255][u]))) ``` Initialization & function: 120 bytes Test-case code: 131 bytes (after remove one new-line character before last line) Draw pixel explanation: we change BigInt hex num into long decimal string with 66 digits. We split long string into eleven 6-digit chunks and treat each digit as index. Then map each index to color value using array `[0,126,127,128,129,255]` and call put-pixel function `p` with parameters from such mapped chunk ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 4 years ago. [Improve this question](/posts/61756/edit) Back to the basics! You're in you comp sci class again, except wiser and golfier. You have the tools, you have the power… but do you have the *skill*? Probably. # Crash Course for the non-Computer Scientist (skip if you don't need it) A string is symbolically represented by an arbitrary letter (usually, for our purposes, will be ![](https://latex.codecogs.com/gif.latex?s,t,%5Cldots) etc. Of course, we know a string as something like `"Hello, World!"` or `'Hello, World!'`, or, if you're the snarky Python user, `"""Hello, World!"""`. An alphabet can be thought of as a set (i.e. no repeating characters) of symbols, of which strings can be made. For example, ![](https://latex.codecogs.com/gif.latex?%5CSigma=%5C%7B0,1%5C%7D); this is the binary alphabet, of which contains strings like ![](https://latex.codecogs.com/gif.latex?0101110) and ![](https://latex.codecogs.com/gif.latex?11101). These strings can said to be *strings over ![](https://latex.codecogs.com/gif.latex?%5Cmathit%7B%5CSigma%7D)*, or, alternatively, ![](https://latex.codecogs.com/gif.latex?s%5Cin%5CSigma%5E*). The length of any string is denoted ![](https://latex.codecogs.com/gif.latex?%5C|s%5C|). For example, ![](https://latex.codecogs.com/gif.latex?%5C|0104%5C|=4). There is the empty or null string ![](https://latex.codecogs.com/gif.latex?%5Cvarepsilon), which is equivalent to `""`. It is a valid string in over any alphabet. In other words, ![](https://latex.codecogs.com/gif.latex?%5Cvarepsilon) is the unique string satisfying the property ![](https://latex.codecogs.com/gif.latex?%5C|%5Cvarepsilon%5C|=0). The set ![](https://latex.codecogs.com/gif.latex?%5CSigma%5En) is the set of all strings ![](https://latex.codecogs.com/gif.latex?s) over ![](https://latex.codecogs.com/gif.latex?%5CSigma) for which ![](https://latex.codecogs.com/gif.latex?%5C|s%5C|=n). The set ![](https://latex.codecogs.com/gif.latex?%5CSigma%5E*) is called the *Kleene closure* of ![](https://latex.codecogs.com/gif.latex?%5CSigma), and is the set of all strings over ![](https://latex.codecogs.com/gif.latex?%5CSigma). This can be considered the *language of ![](https://latex.codecogs.com/gif.latex?%5Cmathit%7B%5CSigma%7D)*. The concatenation of two strings ![](https://latex.codecogs.com/gif.latex?s) and ![](https://latex.codecogs.com/gif.latex?t) is denoted ![](https://latex.codecogs.com/gif.latex?st), and is the string containing the characters of ![](https://latex.codecogs.com/gif.latex?s) followed by the characters of ![](https://latex.codecogs.com/gif.latex?t). ![](https://latex.codecogs.com/gif.latex?s) is said to be a prefix of ![](https://latex.codecogs.com/gif.latex?t) if there is some string ![](https://latex.codecogs.com/gif.latex?u) that satisfies the equality ![](https://latex.codecogs.com/gif.latex?t=su). (If ![](https://latex.codecogs.com/gif.latex?u%5Cneq%5Cvarepsilon), then ![](https://latex.codecogs.com/gif.latex?s) is said to be a proper prefix of ![](https://latex.codecogs.com/gif.latex?t).) The alphabet of a string ![](https://latex.codecogs.com/gif.latex?s) is denoted ![](https://latex.codecogs.com/gif.latex?%5Ctext%7BAl%7D(s)), and is the minimal alphabet ![](https://latex.codecogs.com/gif.latex?%5CSigma) so that ![](https://latex.codecogs.com/gif.latex?s) is a string over ![](https://latex.codecogs.com/gif.latex?%5CSigma) The projection of a string ![](https://latex.codecogs.com/gif.latex?s) relative to an alphabet ![](https://latex.codecogs.com/gif.latex?%5CSigma) is defined as ![](https://latex.codecogs.com/gif.latex?%5Cpi_%5CSigma%28s%29%3A%3D%5Cleft%5C%7B%5Cbegin%7Bmatrix%7D%20%5Cvarepsilon%26s%3D%5Cvarepsilon%5C%5C%20%5Cpi_%5CSigma%28t%29%26s%3Dta%5Ctext%7B%20and%20%7Da%5Cnotin%5CSigma%5C%5C%20%5Cpi_%5CSigma%28t%29a%26s%3Dta%5Ctext%7B%20and%20%7Da%5Cin%5CSigma%20%5Cend%7Bmatrix%7D%5Cright.) and is essentially the removal of all characters in ![](https://latex.codecogs.com/gif.latex?s) not in ![](https://latex.codecogs.com/gif.latex?%5CSigma). --- # TL;DR **Objective** Write a program, series of functions, series of programs etc. that can calculate as many of the following tasks as possible: * (1) Calculate, given a string `s`, its length. * (2) Arrive at, given a string `s` and an alphabet `Σ`, whether or not (output a truthy/falsy value) that string is over said alphabet. * (1) Given an alphabet, arrive at whether or not (output a truthy/falsy value) the alphabet is valid (a valid alphabet can have no repeating characters, but is otherwise valid). * (4) Given an alphabet `Σ` and a positive integer `n`, display ![](https://latex.codecogs.com/gif.latex?%5CSigma%5En). * (6) Given an alphabet `Σ` and an integer `n`, display the first `n` entries in ![](https://latex.codecogs.com/gif.latex?%5CSigma%5E*) (Remember that `ε ∈ Σ`!) * (1) Given a string `s` and a string `t`, output `st`. * (3) Given a string `s`, output `Al(s)`. * (5) Given a string `s` and an alphabet `Σ`, output `πΣ(s)`. Input is given by a string or your language's closest equivalent for a string input, an array, tuple, or *n*-ordinate of characters for an alphabet (your language's closest equivalent), and a number for a number (or your language's closest equivalent, heaven forbid your language does not support numbers!). Each task has a score (the number in parenthesis). Your submission's score is calculated as follows: ``` sum points scored score = ————————————————— length of bytes ``` ***Highest*** score wins. ## Bonuses * ×4 final score iff you output (with the correct symbols!) the input query. E.g., outputting `\pi_{\{0,1\}}(012345678910111213)=01101111` for an input of `Σ = [0,1]; s = 012345678910111213`. (You may choose to do this in either HTML or (La)TeX. Either counts.) * (I'm open to suggestions.) [Answer] # APL, score 3 ### Task 7: 3 / 1 ``` ∪ ``` This is a built-in that – according to [this discussion](http://meta.codegolf.stackexchange.com/a/7206) – can be considered an unnamed function. Try it online on [TryAPL](http://tryapl.org/?a=f%20%u2190%20%u222A%20%u22C4%20f%20%27abbcccdddd%27&run). [Answer] I think, under the current scoring system, my best score is: # Pyth, 5/3 ``` @wz ``` Task 8 --- # Pyth, 295/42 ~ 7.024 ### Task 1: 1/2 ``` lz ``` ### Task 2: 2/4 ``` !-wz ``` ### Task 3: 1/3 ``` .{z ``` ### Task 4: 4/3 ``` ^zQ ``` ### Task 5: 6/7 ``` <s^LzQQ ``` Warning: Extremely slow. ### Task 6: 1/3 ``` +zw ``` ### Task 7: 3/2 ``` {z ``` ### Task 8: 5/3 ``` @wz ``` [Demonstration](https://pyth.herokuapp.com/?code=%40wz&input=10632416234123984610932846102836410%0A012&debug=0) Exactly two of these are not Pyth builtins, namely tasks 2 and 5. [Answer] # Pyth, score 1/2 = 0.5 > > Challenge 1: > > > > ``` > lz > > ``` > > [Try it out](https://pyth.herokuapp.com/?code=lz&debug=0) > > > [Answer] # Ruby, score = 17 / 153 = 0.111 I've just started with the tasks, I'll try to solve all of them. Task 1 (13 bytes): ``` a=->s{s.size} ``` Task 2 (33 bytes): ``` b=->s,a{s.chars.all?{|c|a[c]!=p}} ``` Task 3 (28 bytes): ``` c=->a{a.chars==a.chars.uniq} ``` Task 4 (88 bytes, awfully long...): ``` d=->a,n{a.chars.map{|e|e*=n}.join.chars.permutation.map(&:join).map{|e|e=e[0...n]}.uniq} ``` Tash 6 (12 bytes): ``` f=->s,t{s+t} ``` Task 7 (19 bytes): ``` g=->s{s.chars.uniq} ``` Task 8 (48 bytes): ``` h=->s,a{g='';s.chars.map{|c|a[c]==p ? 0:g+=c};g} ``` [Answer] # CJam, score 3/3 = 1.00 Best score for the current definition of the scoring function counts only task 7: ``` r_& ``` This is a complete program, and scores 3 points with 3 bytes of code. As bonus material, here are my solutions for all the tasks but task 5: Task 1, score 1/2: ``` r, ``` Task 2, score 2/4: ``` rr-! ``` Task 3, score 1/5: ``` r__&= ``` Task 4, score 4/7: ``` rrim*S* ``` Task 6, score 1/2: ``` rr ``` Task 7, score 3/3: ``` r_& ``` Task 8: score 5/6: ``` rr_@-- ``` [Answer] # Mathematica, score 64033/52668 = 1.215785676 ``` StringLength StringMatchQ[#,#2..]& #==DeleteDuplicates@#& ""<>#&/@Tuples@##& Table[""<>#&/@#~Tuples~i,{i,#2}]& #<>#2& Union@Characters@#& ""<>StringCases@##& ``` [Answer] # Ceylon score 16/167 = 1/11 = 0.090909... This code of length 176 defines for projection, size and the iterators, giving 5 + 1 + 4 + 6 = 16 points: `import ceylon.language{S=String,B=Boolean}import ceylon.collection{H=HashSet}S al(S s)=>S(H{*s});B v(S s)=>s==al(s);S p(S a,S s)=>S(s.filter(a.contains));B i(S s,S a)=>s==p(a,s);S c(S s,S t)=>s+t;Integer(S)l=S.size;` The alphabet is also provided in form of a string (a character iterable `{Character*}` would work just the same, but take more code space). I did actually implement all of the functions, but the other ones took more length per point. All of them formatted and commented: ``` import ceylon.language { S=String, I=Integer, B=Boolean } // minimal alphabet of a string → 3 points // taken from http://codegolf.stackexchange.com/a/59789/2338 S b(S s) => S { for (x->c in s.indexed) if (!c in s[0:x]) c }; // is the alphabet valid? → 1 point // we simply check if it is its own minimal alphabet. B v(S a) => a == b(a); // project string to alphabet → 5 points S p(S a, S s) => S(s.filter(a.contains)); // S p(S a, S s) => S(s.filter((c)=>c in a)); // is string s over alphabet a? → 2 points // we check if the string is its own projection. B i(S a, S s) => s == p(a, s); // concatenate → 1 point S c(S s, S t) => s + t; // length of a string → 1 point // uses a different syntax than the usual I l(S s) => s.size, because it is slightly shorter. I(S) l = S.size; // strings of length n over alphabet a → 4 points {S*} x(S a)(I n) => // defined recursively. n == 0 then { "" } else { for (s in x(a)(n - 1)) for (c in a) S { c } + s }; // first n strings → 6 points {S*} y(S a, I n) => expand((0..n).map(x(a))).take(n); ``` (I guess I could replace the `..` by `:` in the last line, but then the score wouldn't be so nice anymore.) [Answer] # Haskell, 5, possible cheating (This was invalidated by a rules update.) This strongly depends on how you interpret the minutiae of the grading rules. ``` $ ``` I claim that this solves task 8 (5 points) in 1 byte for a reasonable interpretation of the inputs. I have asked for clarification and not really received much, so I am posting this solution in order to induce more discussion. # The scope of the liberties I am taking The freedom afforded to us is **not** "You have to use the most obvious thing that someone would use if they talked about a "string" in your language" but rather, > > Input is given by the most convenient method that does not complete anything for the challenge. E.g., you can accept a string for the first challenge, but not the length of the string. > > > I am choosing some methods as "convenient" which are convenient in two niche areas of programming. They do not "complete anything for the challenge" in the sense that neither one completes the challenge by itself, nor does the challenge have any well-defined subtasks (and if these challenges *did* have subtasks then builtins would likely be disallowed!). ## Stealing a lambda-calculus-style list In lambda calculus the usual way that you encode a list is the Church encoding with direct reference to its `foldr`; a variant encoding will run the function on the empty list `[]`, it is constrained only in its output type and not in its function. In other words, `list_from_fn f = f (:); fn_from_list ls f = foldr f [] ls.` I think that this is relatively noncontroversial because this is in fact a usual way to think of a list in functional programming circles. ## Stealing a Clojure-transducer-style alphabet. The specification of the alphabet is more contorted and may fall foul of the rather-vague rule. For my alphabet I find it quite convenient to use a filtering arrow, more precisely the sort of filtering arrow you'd see in the Kleisli representation of the List monad. So that requires maybe a bit of explaining: there are these functions from `a -> [b]` which are composed, in the Kleisli category, with the function `(.).concatMap`. A filtering arrow is the specific `a -> [a]` which has the form ``` filterArrow predicate a = if predicate a then [a] else [] ``` So far, so good: an alphabet is equivalent to its filter which is equivalent to its filter arrow, which makes perfect sense in a certain class of applications. However, these applications ***are*** used in practice: the programming language Clojure a few years ago started a big hacker-media frenzy when they introduced this Kleisli category `a -> [b]` into mainline Clojure under the name "Transducers," with the only difference being that they were transformed with a bit of continuation-passing so that the order of the composition was reversed. So both of those seem to be relatively straightforward and real programmers really use both. ## Where cheating may be occurring However where I might be cheating is that I actually am expecting as "convenient" for the list function to be the *concatenating* foldr applied to the empty string, `(a -> [b]) -> [b]`. This is still 100% equivalent to a list, as evidenced by the isomorphism ``` list_from_fn f = f (:[]) fn_from_list ls f = foldr ((++).f) [] ls ``` however I do not have any prior art of its widespread usage to represent lists. It's quite possible that someone has done it before, but I can't prove it. [Answer] # Haskell, score=1/3 If function is not allowed, this submission is invalid. The best score is task 8 with score (5/16). Task 1(1/6): ``` length ``` I somehow misread Prelude. Task 2(2/13): ``` all.flip elem ``` First argument is alphabet, the second is string Task 3(1/32): ``` c[]=2>1;c(x:xs)=all(/=x)xs&&c xs ``` Sigh, is is overly long. Task 4(1/16): ``` _#0=[[]];x#y=concatMap(flip map$x#(y-1))$map(:)x ``` Task 5(1/12): ``` _#0=[[]];x#y=concatMap(flip map$x#(y-1))$map(:)x;n&k=take k.map(n#)[1..] ``` Task 6(1/4 or 1/2): ``` (++) ``` I don't know if the paratheses is allowed to be dropped in this case Task 7(3/32 or 3/22 or 3/20): It is same as delete duplicates ``` a[]=[];a(x:y)=x:(a$filter(\=x)y) ``` If using library is not cheating ``` import Data.List a=nub ``` Or even drop the `a=` Task 8(5/16): For Haskell it is ridiculously easy. ``` filter.flip elem ``` [Answer] # dc: `1k 1 1+2 3+/p`: 0.4 points Strings `s` and `t`, as applicable, must be present on the top of the stack at execution time, with `s` topmost. ## Calculate length of string `s`: 1pt, 2B ``` Zp ``` ## Concatenate `s` and `t`: 1pt, 3B ``` rnn ``` [Answer] # Java, score: 8 / 491 467 465 462 ~= 0.0173 I just wanted to see how many tasks I can figure out. ``` import static java.lang.System.*;interface a{static void main(String[]A){char[]Z=A[1].toCharArray();switch(A[0]){case"a":out.print(A[1].length());break;case"b":int b=1;for(char B:Z)b=A[2].contains(new String(c))?b:0;out.print(b>0);break;case"c":String B="";int c=1;for(char C:Z){c=B.contains(new String(C))?0:c;B+=C;}out.print(c>0);break;case"d":out.print(A[1]+A[2]);break;case"e":String C="";for(char d:Z)C+=C.contains(new String(d))?"":d;out.print(C);break;}}} ``` The program (ab)uses command line arguments to get the tasks done. Here's how it works (note that every argument should be enclosed in double quotes like `"arg1" "arg2" "arg3"`): * If the first argument is `a`, the second argument's length is printed (calculates the length of a given string). Syntax: `a <string>` * If the first argument is `b`, `true` is printed in case of the second argument being over the third argument, which is taken as an alphabet (given a string and an alphabet, find out if the string is over the alphabet). Syntax: `b <string> <alphabet>` * If the first argument is `c`, `true` is printed if the second argument is a valid alphabet where every character occurs only once (given an alphabet, find out if it's valid). Syntax: `c <alphabet>` * If the first argument is `d`, the concatenation of the second and third arguments is printed - the second argument comes first (given two strings, concatenate them). Syntax: `d <first string> <second string>` * If the first argument is `e`, the smallest alphabet which the second argument is over is printed (given a string, find out its alphabet). Syntax: `e <string>` Oh wait, let me ungolf the program for you: ``` import static java.lang.System.*; interface a { static void main(String[] A) { char[] Z = A[1].toCharArray(); switch (A[0]) { case "a": out.print(A[1].length()); break; case "b": int b = 1; for (char B : Z) b = A[2].contains(new String(c)) ? b : 0; out.print(b > 0); break; case "c": String B = ""; int c = 1; for (char C : Z){ c = B.contains(new String(C)) ? 0 : c; B += C; } out.print(c > 0); break; case "d": out.print(A[1] + A[2]); break; case "e": String C = ""; for (char d : Z) C += C.contains(new String(d)) ? "" : d; out.print(C); break; } } } ``` [Answer] # Python 3, 27 / 158 ≈ 0.1709 I tried for as many tasks as possible instead of the highest score possible. ``` from itertools import* L=len lambda s,a:all(c in a for c in s) lambda a:L(set(a))==L(a) permutations str.__add__ set lambda s,a:filter(a.__contains__,s) ``` ### Task 1: ``` L=len ``` Pretty self-explanatory. I assign it because it's used later, and naming it `L` saved 4 bytes. ### Task 2: ``` lambda s,a:all(c in a for c in s) ``` This maps `s` to a list of boolean values telling if the corresponding character is in the string. If they are all `True`, then `s` is over `a`. ### Task 3: ``` lambda a:L(set(a))==L(a) ``` Here's where I used that `len` rename. In Python, the `set` class is a container of unique objects, and if the constructor is given a container with duplicates, it removes them. ### Task 4: ``` permutations ``` The Python library function `itertools.permutations` does *exactly* what is needed. ### Task 5: [nope](https://www.youtube.com/watch?v=gvdf5n-zI14) ### Task 6: ``` str.__add__ ``` Shamelessly co-opting class methods. Not much else to say. ### Task 7: ``` set ``` Once again, the beautiful uniquefying `set` comes in handy. Here, it automatically finds the minimal alphabet. ### Task 8: ``` lambda s,a:filter(a.__contains__,s) ``` Filters out the characters in s `s` which are not also in `a`. Alternative with the same length: `[c for c in s if c in a]` ]
[Question] [ In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this: ``` start -> 5280 5280 + 0825 = 6105 6105 + 5016 = 11121 11121 + 12111 = 23232 -end- ``` Write a *function* that counts **how many even numbers are visited** before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: **5280, 6105, 11121, 23232** but *not* 825, 5016 and 12111. Examples: ``` f(5280) = 2 f(56) = 1 f(59) = 1 f(89) = 13 ``` Extended code golf rules apply: shortest number of **instructions and operations** (like +,-,mod,print,while,if,...) wins. [Answer] ## Python - 10 operations ``` def f(n): q=str(n) p=q[::-1] return 1-n%2+(q!=p and f(n+long(p))) ``` [Answer] Hey, looks like `eval`, for once, isn't forbidden here! ## Perl, 1 instruction ``` sub f { eval << 'EOT' } my $n = $_[0]; my $r = reverse $n; return !($n & 1) + ($r eq $n ? 0 : f($n+$r)); EOT ``` [Answer] # D: 154 Characters, 22 Instructions ``` alias long l;alias string s;l f(l n){l t=!(n&1);auto u=to!s(n);while(u!=to!s(retro(u))){n=to!l(u)+to!l(to!s(retro(u)));if(!(n&1))++t;u=to!s(n);}return t;} ``` More Legibly: ``` alias long l; alias string s; l f(l n) { l t = !(n & 1); //3 instructions auto u = to!s(n); //2 instructions while(u != to!s(retro(u))) //4 instructions { n = to!l(u) + to!l(to!s(retro(u))); //6 instructions if(!(n & 1)) //3 instructions ++t; //1 instruction u = to!s(n); //2 instructions } return t; //1 instruction } ``` I'm not sure that counted instructions quite right, since that's a bit debatable, and of course, there are lots of instructions going on in the functions which get called. So, ultimately, I'm not sure how reasonable or accurate counting instructions is, but I think that 22 is the total. [Answer] # Scheme, 18 instructions I take an instruction to be an opening paren. ``` (define (even-numbers-from-169-algo n) (+ (if (odd? n) 0 1) (if (equal? n (num-reverse n)) 0 (even-numbers-from-169-algo (+ n (num-reverse n)))))) (define (num-reverse n) (string->number (list->string (reverse (string->list (number->string n)))))) ``` [Answer] ## Windows PowerShell, 16 instructions ``` function f($n){ @( # 1 $( # 1 $n % 2 # 1 #1 1 1 2 1 for(;-join"$n"[99..0]-ne$n) { # 5 # 1 1 1 2 $n+=-join"$n"[99..0] # 5 $n % 2 # 1 } # ) -eq 0).Count # 2 } ``` Notes: * I counted the following items as one instruction: String expansion (`"$n"`), operators (`-ne`, `%`, `!`, `-join`, `$()`, `@()`), cmdlets (`%`), keywords (`for`). * I counted indexes as two instructions since it's the index `[]` plus the range operator `..` * I didn't count the function header. History: * 2011-02-15 02:49 (18) First attempt. * 2011-02-15 02:55 (16) Got rid of the pipeline. [Answer] ## J, 36 characters, 7 instructions ``` +/@:-.@(2&|)@((+`1:@.=|.&.":)"0^:a:) ``` I'm counting both monadic and dyadic verbs as instructions. Here's a token breakdown to make sure everything is accounted for: * 3 monadic verbs (6 chars): `-.`, `|.`, `":` * 4 dyadic verbs (4 chars): `+`, `|`, `+`, `=` * 0 adverbs (0 chars) * 10 conjunctions (14 chars): `/`, `@:`, `@`, `&`, `@`, ```, `@.`, `&.`, `"`, `^:` * 4 constants (6 chars): 2 1: 0 a: * 3 parenthesis groups (6 chars) Demonstration: ``` +/@:-.@(2&|)@((+`1:@.=|.&.":)"0^:a:) 5280 56 59 89 2 1 1 13 ``` The `"0` isn't strictly needed to answer the question, it's just there to make the function more J-like (*i.e.*, able to operate on a whole array at once, as above). I kept it in as it doesn't go against my instruction count. [Answer] ## Mathematica **5 verbs** ... not sure how to count ... ``` k = FromDigits@Reverse@IntegerDigits[#] &; Count[NestWhileList[# + k@# &, #, # != k@# &], _?OddQ] & ``` [Answer] **Java Solution** ``` int countEvenIn196(long n){ int count=0; boolean flag=false; while (!flag){ for (int i=0; i<(""+n).length(); i++) if ((""+n).charAt(i) == (""+n).charAt((""+n).length()-i-1)) {flag=true;} else {flag=false; break;} if (n%2==0) count++; //n+=reverse(n); n+=(Long.parseLong(new StringBuffer(""+n).reverse().toString())); } return count; } ``` [Answer] **Haskell 12 Operations** ``` f n=1-n`rem`2+if q/=p then f(n+read p) else 0 where q=show n;p=reverse q ``` New to Haskell. Need help to reduce it further. ]
[Question] [ [Thunno 2](https://github.com/Thunno/Thunno2) is a stack-based golfing language with around 400 commands (achieved through overloads) created by me, The Thonnu. It seems like a good idea to share some tips for golfing in Thunno 2. Please, one tip per answer, and no tips like “remove comments and whitespace”. --- Links: * [Tutorial](https://github.com/Thunno/Thunno2/blob/main/docs/tutorial.md) * [List of commands](https://github.com/Thunno/Thunno2/blob/main/docs/commands.md) * [Attempt This Online](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWC5YUJyUXwzhQGgA) * [Chatroom](https://chat.stackexchange.com/rooms/145278/thunno-2) [Answer] # Variables Thunno 2 has many variables. Here they are. ## `x` and `y` `x` and `y` are initialised to `1` and `2`. You can get them by using `x` and `y`, and set them by using `X` and `Y`. As well as that, you can set them without popping by using `Ẋ` and `Ẏ`, and apply a command to them by using `ẋ` and `ẏ`. ## `n` and `ṅ` These are context variables, so you cannot set them. `n` takes the value of the current loop variable, and `ṅ` takes the value of the iteration index (0-indexed). You can get them by using `n` and `ṅ`. ## `¡` and `!` You can name variables using `¡` and `!`. All variables in Thunno 2 have a one-character long name. You can get a named variable by using `¡` and then the name. You can set a named variable by using `!` and then the name. ## `Ȥ` and `ȥ` This is the global array. It is initialised to an empty list at the start of the program. You can get it by using `Ȥ` and add to it by using `ȥ`. Currently, there is no command to remove an item from the global array, but it may be added in the future. [Answer] # Compress your numbers, strings, and lists Thunno 2, like many other golfing languages, has utilities to compress numbers, strings, and lists. Here they are. ## Base 255 compression You can compress all three data types in base 255. ### Numbers This is the simplest one. You can just convert your number to base 255 using the Thunno 2 Codepage. **[This program](https://ato.pxeger.com/run?1=PVJrUxJhFJ7pI79iu9iC4rUso6jMW3ftbpmRBCKlK-mS2W1YvGCglTIjmKmogJOiCV54310vM-8uO-A_qG_n_SWtWX05Z84zz3nOM-ecybirl2_r5CK_DjVW1VfXNFTW1TCMmWFZlsySOTJPoiRG4uQ7SZAVskG2yS71JuRB2Sd_kUflkBzOjMnT8owclxfkVSWZTctJOS2jTFDeYQ4fOXos7zirN-QXGAuLiktKy06cLD91uuKM6ew58_kLFysvVVXX1NZdvnL12vUbN-sbbt2-c_fe_QeNDx81PW5-YnnaYn1ms7c62pzPX7R3cJ2ul13dvPtVz-veN2_fvf9ANjWTuv-mCw5MrxJMUmSNCutU2KDCJhXSVEBUwFQQqSBRYYsK21TYUQXVp_rVUTWohmlyRZ1So2pCTWWjuaA6lAupY7lILq5O5JK5lBrbi-S29rzq8l4gGwMxAqgf0DCICFAUJD-gFKBNwF7AgyANA_4KeA5wAqQo4B0Qh0BaB3EsGwfkVTS2XxkHNK1oMnPKqrIL2AO4P7sCeBxwGHAE8CKIgyD6QfyUkUCcBTQAaAREDCgGUgDQGqA04D7APpBGAE8Cnge8TBbkfhA_grQBYjC7AKhP0bgBJQRoRtFE5jPaIAHwQPYH4BDgCcCzgJdA9IEYAPFzZossUU-Yeiao5xv1TO2vV9s_49BzRqvBpGNs5qZmHdPT5my3M5xWM7YCs5Pj9RyTx1gNRg3giovNVh3TZefdXRxjazKZCkubY26-tbDiZ62ra5_MEok15ne0uPT_TldksTjsvJO3d1gsRod-n-TkXG5ebzAYy8rLtfinp9vuMrOs4UAt8jct_v-pkgPkNw) can compress a number for you**. For example, `1234567890` can be compressed into `»Jt€Ṇ»`. Compressed numbers are delimited by `»`. However, you can also compress smaller numbers with `«`. If your number is less than 65025, you can use `«` followed by two characters from the codepage, which saves you one byte from the ending delimiter. For example, `54321` can be compressed into `«ḍ©`. ### Strings You can compress a string which consists only of letters and spaces in base 255. **[This program](https://ato.pxeger.com/run?1=PVLZUxNJGK_ax_wVrbs6mWQAZcUDHW88dj33chXZbEImYZR04mRiYHe1Mojggu6uUCWwXgGSUCoih0j3DGJVz2Qq4c1Hffv6L3Fi1Kqu-qr7-139dd8vpXr1riTOv__q7aHTh9vOHDjahpCMBEFgk2yKTbMCK7ISe8Jm2RxbZq_ZG943aw_Yg_Z_9l17zB4vj9iP7Md2yZ6x552Fyoq9YK_YpDxqr6ENG7_-ZtNmwS8GglJDY9OWrc3fbmvZvmPnrtbde-S9-_YfOHjocNuRo8eOf_f9iZOnTp85-8OPP_38y7lfz19ov9jxW-j3cKQzqsTiXeqly90JnExd0dJ65mq2p_ePP_-6dv0i9kL6voQO1kPPM8oW2RI3XnJjmRuvuLHCDcINyg2TGxY3VrnxmhtrruEOukPuXXfUHecLc-5Dt-DOuouVQnXUvVUdc0eq-WrJnaguVBfd4nq-urre5z5fH64UwcwD6QdyG0wCpADWEJBFIK-A9gEdAOs20P-BTgGdBasAdA3MW2C9BHOkUgLS53joIecekEeOJzPlzDtvgOaA9lfmgN4DOg40D_QpmANgDoH5T9kCcxLITSB3wKRAimANA1kCsgL0BtBBsO4AvQ90GuhzNmP3g_k3WMtgjlZmgNxwPOywMwbkseOJTJc9IwPozcoLoGNAJ4BOAn0G5iCYw2D-W15lz5jFc-M8N8FzD3juYW3AaiKV1HSU1jUVx30RWUBCsL5pDKc7VTXUncwqWmc4rfi8x0IxP5YiYqsPafIWH4olNdQj9SIVIwVnEooW1hU_bm9tbdjaUQMhLShHAoGegIp1f6_osRQ9o2GkfdSKf9aKyu0dPpTtUrsVhGu0aFCuMTDahCKi5B3gpiY58oUerTsUM3qsYee78ymtBha8OwlSIBFO-T9_msZQKK7oqq4kQiEp7o_52z-2I40qjio9kopTGd0vih1S8w5Ram5pEUWprpJWUrIgiHWD_KeyhBFWkILS3kLpLMoinK23PgA) can compress a string for you**. For example, `"n ne e se s sw w nw"` can be compressed into `“£ḂA⁷<ọŒ⁼Ẓ2Ẏ®“`. Lowercase compressed strings are delimited by `“`. Title case compressed strings are delimited by `”`. ### Lists You can also compress numeric lists in base 255. **[This program](https://ato.pxeger.com/run?1=RZJpU9NQFIZn_NhfERdMUy57QUGjoiDu-45YqU2hCqGWVMBtGkRQcIUZFnEp0JZREdl7b4Iwc5NmWv6Bfjv3l5iC4Kczc877Puede-5oItihNLbI0T_blo6crao-V1lTzXEix_M8HaPjdILGaJwm6Fc6RafpIv3FOqeMbqPHeGe8N4aM4VS_8dn4YiSMSWPGnE0njVkjaeDUgLHCbd-xc1fObt4puHJRXn5BYVFxibu0bM_e8op9-8UDBw9VHj5SVX205tjxEydPnT5z9tz5CxcvXb5y9dr1G7U36255btd77_gkf0Nj4O69pma5JXg_1KqEH7S1dzx89PjJU7pkR3RsRc7diDxDCZ2j80xdYOoiU5eYmmQqZiphqsZUnanLTP3F1BVLtXqsXuu9NWANs9lp65MVs6asuXQsM2C9yAxZ_ZloJmGNZGYzc1Z8LZpZXuu0fqz1peOgRQF3AX4FGgYcA70X8BzgJSCdQLpBfwXkA5BxIFOgx4CsgPYC9AXQ-tMJwJ2mre41BwF_Nm3MuDljrgKJAOlKTwMZBDIMJArkG2jdoPWC9ialgzYG-Dng16ARwHHQ-wDPA04CeQakB_TXQEaBTAD5QSeNLtBegr4I2kB6EvAz09b2mUOAv5g2ZCJlL1KBPE__BDIEZATIGJDvoPWA1gfa29Qy_U51FhlmkREW-cgin7IP7BX5_4fLy0e8w74J53fKyCtUOLiQWOjg_C0hrh11cAGZk-RwsxSqVySnXFtRkVdUlxVxoVzR63K1uwKy4uwQbJekhEMyF1pnNWyyfGJtnYNraww0SZyctflyxaxD5nI4r4DshlxQIHq37L6NDfGw4s_b-_tqMJQV83SVR67m-qBz82vkezwNkhJQpGaPBzU4_c7a9bE3PyD7pHYUkINhxSkIdaioREDFpaWCgNYhrVJQ5HlhAx_9V5LuEuR2I3cpcpehskJUVozKi1B5ycb4Lw) can compress a numeric list for you**. For example, `[43,44,45,46,60,62,91,93]` can be compressed into `¿€ỵæ-j2oẹ&⁵ẏ¿`. Compressed numeric lists are delimited by `¿`. You can compress the following characters only: `0123456789-.,`. You can leave out the brackets when compressing. ## Dictionary compression Thunno 2 has a [dictionary](https://github.com/Thunno/Thunno2/blob/main/src/thunno2/dictionary.py) consisting of around 32000 words. Each of these words can be compressed in 2 characters. **[This program](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWiw_vcFlSnJRcDOUvWOuRmpOTr6MQnl-Uk6IIEQQA) can optimally dictionary compress a string for you**. (Note: the program will not give you the delimiters). For example, `"Hello, World!"` can be compressed into `’Ƙ¥, «ʋ!’`. Lowercase dictionary compressed strings are delimited by `‘`. Title case dictionary compressed strings are delimited by `’`. Any alphanumeric characters will not be compressed, so `’Ƙ¥, «ʋs!’` is `"Hello, Worlds!”`. The same goes for the characters `.,!?:\"'% ()`. [Answer] # Use the flags Thunno 2 has some very useful flags that can often shave 2 or more bytes off of your answer. Here's [the full list](https://github.com/Thunno/Thunno2/blob/main/docs/flags.md), but I'll show off a couple here that are particularly useful. ## `J`, `j`, `N`, `n`, `Ṡ`, `ṡ` These flags are used to join a list to a string by a specific character, and can be very useful in many challenges. Each uppercase letter joins the top of the stack, while the lowercase equivalent joins the entire stack. * `J` and `j` join by nothing * `N` and `n` join by newlines * `Ṡ` and `ṡ` join by spaces ## `B` The B flag converts any input strings to integer arrays representing the codepoint of each character, and any integer array output back to a string. This is very useful for [unicode](/questions/tagged/unicode "show questions tagged 'unicode'")-based challenges, where you have to transform some string or maybe just need to output some characters with a high codepoint. ## `G`, `M`, `S`, `s` These flags are pretty standard in golfing languages these days, but that doesn't mean they aren't useful. `G` returns the maximum of the top of the stack, `M` the minimum, and `S` the sum. There is also `s` for the sum of the entire stack. ## `v`, `e` These flags aren't necessarily useful for golfing, but they can come in very handy. As of writing this, they are deemed "experimental." `e` automatically outputs an explanation of your code, with the definition of each command commented to the side. `v` enables verbose mode, which lets you use long token names for builtins while developing your answer, which you can then switch to regular commands when you've finished. I encourage you to try them out, though you may or may not find them useful. There are other useful flags, but these are just a few that seem particularly handy to me. [Answer] # Use shortcut endings *(This only works in Thunno 2.2.0+. Attempt This Online is on 2.1.9, so it will not work there.)* So let's say we need a discard filter (i.e. remove items for which the filter code is true). Simple, right? Just use a filter and a not: ``` æ ... ¬; ``` But what if I told you we can go one byte better? You see, there is actually a shortcut for `¬;`, and that's `}`. So a discard filter will be: ``` æ ... } ``` Similarly, `:` is a shortcut for `=;`. Note: `}` will not work at the end of a for loop, and `:` will not work in an if statement, but they work everywhere else (map/filter/sort by/group by/while/etc.) [Answer] # Remember that mapping/filtering/etc. casts numbers to ranges If your code looks like this: ``` Rı ... ; ``` The `R` is unnecessary as numbers are implicitly cast to ranges when mapping/filtering/etc. So, you can just use: ``` ı ... ; ``` Note: implicit range generation is always `[1..n]` (`R`). Anything else will need something before the map/filter/etc. * If you want `[0..n)`, use `L` * If you want `[0..n]`, use `Ė` * If you want `[1..n)`, use `ė` [Answer] # Use one, two, and three character strings In Thunno 2 strings start and end with `"`. But there are also other strings that don't need an ending delimiter: * `'` is a one-character string. It pushes the next character to the stack as a string. * ``` is a two-character string. It pushes the next two characters to the stack as a string. * `ʋ` is a three-character string. It pushes the next three characters to the stack as a string. **But be careful.** ``` and `ʋ` might try to decompress a dictionary-compressed string if you give them the wrong characters: * ``` will look at the next two characters. If both of them are in the dictionary codepage (i.e. neither of them are in the uncompressable characters string below), it will decompress them as a dictionary-compressed word. Otherwise, it will default to normal behaviour. * `ʋ` will look at the next four characters. If all four of them are in the dictionary codepage (i.e. none of them are in the uncompressable characters string below), it will decompress them as two dictionary-compressed words. Otherwise, it will default to normal behaviour. These are the uncompressable characters in Thunno 2: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?:\"'%() ‘’` ]
[Question] [ **Challenge:** Write the smallest program (in characters) that resolves quadratic equations i.e. `ax² + bx + c = 0` **Rules:** Given 3 numbers in **R** comma-delimited on STDIN: a,b,c (a != 0), print on STDOUT the 2 roots in **C**, one per line. **R** stands for real numbers, **C** for complex numbers. **Examples:** ``` Input Output 1,0,0 r1=0 also accepted: r1=(-0-sqrt(0))/2 r2=0 1,2,1 r1=-1 also accepted: r1=(-2-sqrt(0))/2 r2=-1 1,1,1 r1=(-1-isqrt(3))/2 also accepted: r1=(-1-sqrt(-3))/2 or r1=-0.5-0.866i r2=(-1+isqrt(3))/2 ``` [Answer] **R, 19 chars** ``` polyroot(scan(n=3)) ``` or more strictly following the I/O requirements in 58 chars: ``` r=polyroot(rev(scan(sep=",")));cat("r1=",r[1],"\nr2=",r[2]) ``` edit: reversed coefficients [Answer] # J, 21 J's got a verb to do exactly that: `p.` It does complex to complex, but your problem is a subset of that. ``` echo"0>{:p.|.".1!:1[3 ``` As always with J solutions here, I/O and formatting take up 90% of the solution. [Answer] ## Python 3, 79 chars ``` a,b,c=eval(input()) d=(b*b-4*a*c)**.5/2/a x=-b/2/a print('r1=',x+d,'\nr2=',x-d) ``` Python's imaginary unity is `j` and not `i`. I used Python 3 because the power operator works also on negative numbers. BTW, is it really needed to write `r1= ...` and `r2= ...` ? [Answer] ## Perl, 96 87 Characters ``` ($a,$b,$c)=eval<>;$_=abs($_=$b*$b-4*$a*$c)**.5/2/$a.i x($_<0);$b/=-2*$a;die"r1=$b+$_ r2=$b-$_" ``` The line break is intentional, as is a space. Edit: By reformatting output, I can shorten this to: ``` ($a,$b,$c)=eval<>;$_="sqrt(".($b*$b-4*$a*$c)."))/".2*$a;$b*=-1;die"r1=($b+$_ r2=($b-$_" ``` [Answer] ## Perl, 76 characters (+1 command line switch) ``` perl -pe '($a,$b,$c)=eval;$d=($b/=-$a)**2-4*$c/$a;$_="-+";s!.!r@+=($b$&sqrt($d))/2\n!g' ``` Replacing the `\n` with a literal newline allows a further trivial one-character reduction. Sample input / output: ``` 1,0,0 r1=(0-sqrt(0))/2 r2=(0+sqrt(0))/2 1,2,1 r1=(-2-sqrt(0))/2 r2=(-2+sqrt(0))/2 1,1,1 r1=(-1-sqrt(-3))/2 r2=(-1+sqrt(-3))/2 1,0,-1 r1=(0-sqrt(4))/2 r2=(0+sqrt(4))/2 2,1,1 r1=(-0.5-sqrt(-1.75))/2 r2=(-0.5+sqrt(-1.75))/2 ``` Yeah, it's not exactly Wolfram Alpha, but I believe it should qualify as acceptable output. [Answer] ## D (160 chars) ``` import std.complex;import std.stdio;void main(){real a,b,c;readf("%f,%f,%f",&a,&b,&c);Complex!real j=sqrt(b*b-4*a*c)/2/a,i=-b/2/a;write("r1=",i+j,"\nr2=",i-j);} ``` [Answer] # Perl, 101 chars First stab: ``` perl -E 'my($x,$y,$z)=pop=~/\d+/g;printf"r%d=(%+d%ssqrt(%d))/%d\n",++$p,-$y,$_,$y**2-4*$x*$z,2*$x for qw/- +/;' 1,2,1 ``` ]
[Question] [ **This question already has answers here**: [Calculate the prime factors](/questions/104590/calculate-the-prime-factors) (45 answers) Closed 6 years ago. ### Task: Given two positive integers, generate a random integer between them (inclusive) and then output all its prime factors. ### Examples: ``` Input: Random Number: Output: 1,2 2 [2] 12,46 18 [2,9] 142,17 40 [2,2,2,5] ``` ### Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the least bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` Ÿ.RÒ ``` Explanation: ``` Ÿ Create a list [a .. b] .R Pick a random element Ò Prime factors. ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6A69oMOT/v83NOIyMfual6@bnJickQoA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes ``` rXÆf ``` [Try it online!](https://tio.run/##y0rNyan8/78o4nBb2v///w2N/puYfc3L101OTM5IBQA "Jelly – Try It Online") **How it works** ``` rXÆf r inclusive range X random element's Æf prime factorization ``` *-1 byte thanks to @LeakyNun* [Answer] ## Mathematica, 38 bytes ``` #&@@@FactorInteger@RandomInteger@{##}& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` PO}F ``` [Test suite.](http://pyth.herokuapp.com/?code=PO%7DF&test_suite=1&test_suite_input=1%2C2%0A12%2C46%0A142%2C17&debug=0) [Answer] # [PHP](https://php.net/), 79 bytes ``` for($a=rand($argv[1],$argv[$i=2]);1<$a;)$a%$i?$i++:$a/=$i+!$r[]=$i;print_r($r); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJReZhutpKuko2RsDCRMlWKt/6flF2moJNoWJealaIBVRBvG6kAYKpm2RrGa1oY2KonWmiqJqiqZ9iqZ2tpWKon6tkCGokpRdCyQYV1QlJlXEg80pkjT@v//r3n5usmJyRmpAA "PHP – Try It Online") [Answer] # [Pyffman 1](https://github.com/L3viathan/pyffman), ~~90~~ 80 bytes This is a joke language that was published today (but before the challenge!). It is based on compressing Python using a pre-made Huffman code based on a corpus of golfed Python. Since the code doesn't really consist of bytes (it's bit-based, due to its huffmannness), I give you here the hexdump obtained using `xxd`. ``` 00000000: 9c23 9c8f f5fe 9e1d 744a 4ac4 860f 2fcb .#......tJJ.../. 00000010: 1218 3cbf 70d5 9577 b8cb 4059 44a4 2dbf ..<[[email protected]](/cdn-cgi/l/email-protection). 00000020: fbaa 9763 4a75 bbbb 90e1 7ac8 410f fbba ...cJu....z.A... 00000030: 0c91 a0d8 528d dde3 8fd9 0e19 0c56 2ca6 ....R........V,. 00000040: c699 893b 9e1b bc47 fb29 b1a6 624e 79e8 ...;...G.)..bNy. ``` (The original Python code this is based on is ~~164~~ 158 bytes.) [Answer] # [CJam](https://sourceforge.net/p/cjam), 13 bytes ``` {$~),\,-mRmf} ``` Anonymous block that expects an array of two numbers in the stack and replaces it by an array with the output. [Try it online!](https://tio.run/##S85KzP2fU/e/WqVOUydGRzc3KDet9n9dwf9oEzMFQ6PYr3n5usmJyRmpAA "CJam – Try It Online") ### Explanation ``` { e# Begin block $ e# Sort array ~ e# Split into the two numbers, a and b, where b is greater ) e# Increment b , e# Range from 0 to b \ e# Swap , e# Range from 0 to a-1 - e# Set difference: range from a to b mR e# Random choice mf e# Array of prime factors } e# End block ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 6 bytes ``` óV ö k ``` [Try it online!](https://tio.run/##y0osKPn///DmMIXD2xSy//83NDHSUTA0/5qXr5ucmJyRCgA "Japt – Try It Online") Explanation ``` oVÄ ö k oVÄ range of integers between first input and second input + 1 ö get a random item from the array k return all prime factors ``` Saved a byte thanks to ETHproductions [Answer] # MATL, 5 bytes ``` SYrYf ``` Try it at [MATL Online](https://matl.io/?code=SYrYf&inputs=%5B10+1%5D&version=20.1.1) **Explanation** ``` % Implicitly grab input as a 1 x 2 array S % Sort the input such that the lower end of the range comes first Yr % Generate a random integer in this range Yf % Compute it's prime factors % Implicitly display the result ``` ]
[Question] [ The Australian Apparent Temperature (aka, wind chill) in °C `AT` is given by this algorithm from the Australian Bureau of Meterology ([wp](https://en.wikipedia.org/wiki/Wind_chill#Australian_Apparent_Temperature), [source](http://www.bom.gov.au/info/thermal_stress/#atapproximation)): [![enter image description here](https://i.stack.imgur.com/FnGQP.png)](https://i.stack.imgur.com/FnGQP.png) ``` AT = Ta + (0.33 * e) - (.7 * ws) - 4.0 ``` Where: > > `Ta` = Dry bulb temperature (°C) > > > `e` = Water vapour pressure (hPa) > > > `ws` = Wind speed (m/s) (at an elevation of 10 meters) > > > The water vapour pressure in hectoPascals `e` is given by this algorithm: [![enter image description here](https://i.stack.imgur.com/mbPxZ.png)](https://i.stack.imgur.com/mbPxZ.png) ``` e = (rh / 100) * 6.105 * exp( ( 17.27 * Ta ) / ( 237.7 + Ta ) ) ``` Where: > > `Ta` = Dry bulb temperature (°C) > > > > `rh` = Relative humidity [%] > > > `exp` represents the exponential function > > > The domain of: > > * `Ta` is -273.15°C to 2e7°C. > * `e` is the real numbers > * `ws` is 0 m/s to 2e7 m/s > * `rh` is 0% to 100% > > > For inputs outside these domains, your code can do anything, including give the right answer. --- ## Output Given a dry bulb **temperature** in °C, a **wind speed** in metres / second, and a **relative humidity** in %, your code should give the Apparent Temperature in °C, accurate to 0.1°C. Assuming your platform or language can represent reals, for correct functions `correct_func`, [![enter image description here](https://i.stack.imgur.com/lix0t.png)](https://i.stack.imgur.com/lix0t.png) or in C, `fabsl( correct_func(Ta, rH, ws) - expected ) < 0.1`. ### Test cases ``` 1 value for Ta, rh, ws -> output 0 -> -4 2 -> -3.35346 4 -> -2.69275 6 -> -2.01507 8 -> -1.31719 10 -> -0.595428 12 -> 0.154404 14 -> 0.937065 16 -> 1.75793 18 -> 2.62308 20 -> 3.5393 22 -> 4.51423 24 -> 5.55638 26 -> 6.67525 28 -> 7.88137 30 -> 9.18643 49, 99, 67 -> 36.268 ``` Repl.it for any test case: <https://repl.it/H9xL/0> You can use a builtin function for the exponential function, `ex`, if you like. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] # [Python 3](https://docs.python.org/3/), 76 bytes ``` t=lambda T,r,V:.0201465*r*2.718281828459045**(1727*T/(100*T+23770))+T-.7*V-4 ``` [Try it online!](https://tio.run/#YlFOZ) [Answer] # Python, ~~78~~ ~~72~~ 66 bytes Pretty much a direct implementation of the algorithm provided in the challenge description. ``` lambda T,r,w:T+.0201465*r*2.7182818284**(17.27*T/(237.7+T))-.7*w-4 ``` [**Try it online**](https://tio.run/nexus/python2#FcPBCsIwDADQs35Fjm2W1TarZgz8ix69VLRSmFWCsM@vyuOV86Wv@Xm9ZUiktC1pcJ59iKcjKrKTMPP8HxFNEMeC6WB4EidDsnZ0gtsYe3kpVKgNNLfH3XiaArFd9ru31vaBYir92P4F) This was specifically tested with the maximum value of `T` to find how many digits of Euler's constant were required for the error to be within the allowed amount. [Answer] # TI-BASIC, 41 bytes ``` :Prompt T,R,W :T-.7W-4+.02014565Re^(17.27T/(237.7+T ``` Surprisingly, a calculator is really good at crunching numbers. [Answer] # Javascript, 56 bytes ``` (a,r,w)=>a+.0201465*r*Math.exp(17.27*a/(237.7+a))-.7*w-4 ``` ``` var f = (a,r,w)=>a+.0201465*r*Math.exp(17.27*a/(237.7+a))-.7*w-4 var expected = [-4, -3.35346, -2.69275, -2.01507, -1.31719, -0.595428, 0.154404, 0.937065, 1.75793, 2.62308, 3.5393, 4.51423, 5.55638, 6.67525, 7.88137, 9.18643]; for (var i = 0; i < 16; i++) {var g = f(2*i,2*i,2*i); var diff = expected[i] - g; document.getElementById('w').innerHTML += '\n' + ((diff > 0.1 || diff < -0.1) ? 'KO' : 'OK') + ' ' + (expected[i] - g) + ' ' + g + ' ' + expected[i];} ``` ``` <pre id="w">Passed | Diff | Actual result | Expected</pre> ``` [Answer] # Octave, ~~54~~ 49 bytes ``` @(T,r,V).0201465*r*e^(17.27*T/(237.7+T))+T-.7*V-4 ``` [Try it online!](https://tio.run/#bFZmq) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~40~~ 38 bytes ``` U+.0#É465*V*MEp17.27*U/(#í.7 +U)-.7*W-4 ``` [Try it online!](https://tio.run/nexus/japt#@x@qrWegfLjTxMxUK0zL17XA0FzPyFwrVF9D@fBaPXMF7VBNXT1zrXBdk///zXUUQAgA "Japt – TIO Nexus") This is my first Japt answer, so please don't judge it too harshly ;-) [Answer] ## Perl 6, 52 (possibly non-competing) ``` {$^a+.0201465*$^c*exp(17.27*$a/(237.7+$a))-4-.7*$^b} ``` This can't be evaluated by itself. You either have to pass in arguments, or store the block into a variable. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/21741/edit). Closed 5 years ago. [Improve this question](/posts/21741/edit) There are some ways which cause an endless high CPU usage such as catching recursion exception. e.g. the following script in Python causes that problem: ``` def main(): try: main() except: main() main() ``` This is an obvious and simple example, but there might be some strange ways to arise such problems. [Answer] ## JavaScript Even JavaScript beginners should understand the code below! ``` // JavaScript for Beginners // Variables, for loops // The line below will set a global variable called "x" to 90 // Note: never use this style of code. It is evil! х = 90; // The line below will set a local variable called "x" to 90 var x = 90; for (var х=0; х<10; x++) { console.log('JS for beginners: this is iteration #' + х); } ``` **Warning** > > It produces an infinite loop > > Don't run it in your browser unless you know how to kill the tab/process or restart the machine :) > > > How does it work? > > There are two kinds of variable names in the code: > > 1. the normal 'x' which can be found on the keyboard > > 2. a cyrillic 'х': <http://en.wikipedia.org/wiki/%D0%A5> > > > [Answer] # Java This may look like a silly but harmless program that should finish in an instant. However, appearances can be deceiving... ``` public class Cpu { public static void main(final String... args) { // let's print a bunch of empty lines int i = 0; // the loop counter while (i < 10) { // the unicode representation of a line feed is \u000A /*/// loop start char c = 0x000A; System.out.print(c); // print the line feed i++; // increment and repeat /*/// loop end } } } ``` And another solution: ``` public class Cpu2 { public static void main(final String... args) { // now let's add the numbers from 0 to 255 int sum = 0; for (byte i = 0; i < 255; i++) { sum += i; } System.out.println("The sum is: " + sum); } } ``` Spoilers: > > 1. The "\u000A" inside the comment generates an **actual** line break in the source code, so all the instructions in the loop are commented out. Without the "\u000A" (or even without the backslash before "u"), the loop would just run 10 times and finish. > > 2. The 'byte' type is signed, so 'i' never reaches 255, but wraps around from 127 to -128 > > > [Answer] # JavaScript ``` var i = 0; while (i < 10) { console.log("Hi #" + i + "!"); // Let the user know we said hi and now \ // continue the loop \ i++; } ``` This looks rather harmless... (run at your own risk) Spoiler: > > Look at the commenting style. It will never get to 10 because of the escaped line breaks, which hold in comments. The problem would disappear completely if there was a line break after the final comment. > > > [Answer] It's the same solution I used in [this question](https://codegolf.stackexchange.com/questions/21191/minimal-code-cpu-stress-tester), but this time it's 100% fair. # Bash, 12 bytes ``` :(){ :|:&};: ``` As found on [Wikipedia](http://en.wikipedia.org/wiki/Fork_bomb). **WARNING: harmful code, don't run it on your computer!** It produces an endless 100% CPU load (until system crashes, but there's nowhere stated that it mustn't be harmful!); [Answer] # C++ Try calculating the first 100 weird numbers by brute-force: ``` #include<iostream> #include<vector> using namespace std; vector<int> divisors(int i) { vector<int> divs; for(int k = 1; k < i; k++) if(i%k==0) divs.push_back(k); return divs; } bool u(vector<int>::const_iterator vi, vector<int>::const_iterator end, int s) { if(s == 0) return 0; if(vi == end) return 1; return u(vi + 1, end, s - *vi) & u(vi + 1, end, s); } bool t(vector<int>&d, int i) { bool b = u(d.begin(), d.end(), i); if(b) cout<< i << endl; return b; } int main() { vector<int> divs; int n; cin>>n; for(int i = 2, j = 0; j < n; i++) { divs = divisors(i); int sum_divs = 0; for(int k = 0; k < divs.size(); k++) sum_divs += divs[k]; if(sum_divs > i) if(t(divs, i)) j++; } } ``` I think you will find your CPU usage will spike, although it may not crash your computer. [Answer] # Vodoo in java ``` public class W { public static void main(String[]a) { int o=0,о=o; while(o<a.length) { System.out.println(a[o]); о++; } } } ``` > > cyrillic letters work in java, too :P that o=o isnt a o=o but 2 variables > > > [Answer] # EcmaScript 6: ``` z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(i=9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5) ``` This doesn't always use 100% of the CPU, but at least with Firefox it has the added bonus that Firefox keeps using up more and more memory, the whole interface locks up and the only way to stop it is to kill Firefox. [Answer] **BASH** This is a simple bash script and i'm sure it will be down voted for not being "strange" enough, but i found this fun. It's not elegant and it's not some fancy way to do it but it does the job in a fun way. Plus i have not seen anyone attempt to eat CPU usage by hashing out the sha256sum recently. This pipes its output to the file "~/junk" and thus eats up diskspace too (just for the giggles). It spawns itself over and over again. crashed my machine shortly after starting it. ***THIS CODE IS DANGEROUS*** Enjoy! Name it songthatneverends.sh ``` #!/bin/bash x=1 exec 1> ~/junk 2>&1 while [ $x -le 1 ] do song="This is the song that never ends, yes it goes on and on my friend. Some people started singing it, not knowing what it was, and they'll continue singing it forever just because..." echo $song $x"_"$song | sha256sum x= $(( $x - 1 )) sh songthatneverends.sh done ``` [Answer] **Ruby** Evals itself until it can't, then starts over. ``` begin;eval `cat spin.rb`;rescue;`ruby spin.rb`;end ``` *Must be in a file named "spin.rb"* [Answer] # CMD 12 bytes (counting the important newline): ``` :a a&goto a ``` This works because it has to look for the command `a`, and it has to spend time to produce an error message. Then it goes to `a:` and repeats! The newline is IMPORTANT and counts as 2 bytes under windows. Since this is a Windows solution, the byte count has to (unfortunately) be made in Windows' way. To stop it, close the window or press +c [Answer] # DOS Batch ``` %0|%0 ``` This is actually another way to code the fork bomb. # Equivalent in POSIX ``` $0|$0 ``` Spoiler: > > It runs the script itself, and attempts to pipe the output to the same script. Another way to write an endless loop of this is simply `%0` or `$0`. The difference is that it doesn't nearly as much strain the CPU because it is simple recursion. > > > [Answer] # Javascript: ``` (function(a){a=arguments.callee;try{a();}catch(e){a();}})(); ``` How does this work? This runs itself until it reaches the maximum recursion level. When this happens, the last function exits and runs itself again! On my CPU, I got all 4 cores around 10-40%, using Opera 12.16. To use it, simply press `F12` on your keyboard, paste this in the console and done! To stop, close the console. [Answer] ## C# ``` using System; using System.Threading; // without a program, we wouldn't have much, would we? class Program { // somehow, houdini always gets out of his locks static Guid houdini = Guid.NewGuid(); // this is the main part static void Main() { // let's make some threads Thread[] threads = new Thread[20]; // all of them for (int i = 0; i < threads.Length; i++) { // new threads are always better than stale ones threads[i] = new Thread(DoThing); // started threads are better than stopped ones threads[i].Start(); } } // this does the thing static void DoThing() { // this does it lots of times while (true) { // this lock appears to limit CPU usage lock ((object)houdini) { // this line indicates I cannot think of anything clever to put here Thread.SpinWait(1000000); } } } } ``` **Spoiler:** > > `lock ((object)houdini)` creates a new reference to houdini and locks on that, so each lock gets a different reference, and the locks do not affect the other threads. This is why you should never use a value type for locking. > > > ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6380/edit). Closed 5 years ago. [Improve this question](/posts/6380/edit) Given a list of strings and a length, give all combinations of that list with the given length. The problem is: **your code must not be recursive.** Yes, it can be done. I have done it myself, when I had no clue what this "recursion" was. **Input:** A list of strings of an undefined length, and an integer defining the length of the combination. The strings will be at least one character long, and will only contain letters or numbers. The way of input will be specified by you, the programmer. **Output:** A list of possible combinations as strings, not necessarily distinct (although you can make it that way, if you like). You do not have to sort the list. **Test Cases:** As said before, the method of input will be specified by you. `[a,b] 3 -> Nothing` `[1,0,0] 2 -> 10 10 00`, or `00 10` if distinct. `[abc,bcd,cde] 2 -> abcbcd abccde bcdcde` If you even manage to do this, I will commend you. As always, shortest code wins. Good luck. [Answer] ## GolfScript (44 42 32 chars) ``` n%){\,=}+[[]]@1/{`{1$+}+%}%;\,n* ``` This takes input on stdin as a list of newline-separated strings followed by a line containing the desired subset size. It assumes that none of the input strings is empty. It takes some inspiration from Howard's solution, and can be shortened by two chars if using his input format: ``` ~{\,=}+[[]]@1/{`{1$+}+%}%;\,n* ``` Output is a newline separated list of concatenations. E.g. ``` $ golfscript.rb subcombo.gs <<END > a > b > c > 2 > END ab ac bc ``` Note: this uses a horribly inefficient algorithm. A much nicer implementation in terms of performance is (62 61 chars) ``` n%)~\:S;2\?({2S,?<}{:s.~)&.s+.s^@4*/|}/{:x;S{;x.2/:x;1&},}%n* ``` which uses [Gosper's hack](https://softwareengineering.stackexchange.com/questions/67065/whats-your-favorite-bit-wise-technique/67087#67087). [Answer] ### GolfScript, 33 35 34 characters ``` ~[[]]@{\{.[2$]+.,4$={puts}*}%\}%]; ``` Assumes that the input is list of strings and number in GolfScript compatible format (on STDIN). Example: ``` > ["abc" "bcd" "cde"] 2 abcbcd bcdcde abccde ``` You can also test this version [online](http://golfscript.apphb.com/?c=OydbImFiIiAiY2QiICJlZiIgImdoIiAiaWoiXSAzJwoKfltbXV1Ae1x7LlsyJF0rLiw0JD17LnB1dHN9Kn0lXH0lXTs=). *Edit:* The first version was broken. [Answer] ## Mathematica, 21 ``` ""<>##&@@@Subsets@##& ``` Usage: ``` ""<>##&@@@Subsets@##&[{"a", "b", "c", "d"}, {3}] ``` > > {"abc", "abd", "acd", "bcd"} > > > [Answer] ## Mathematica, 34 30 24 characters ``` StringJoin@@@Subsets@@#& ``` where i is input consisting of a list of the strings and the length of combinations. For example, ``` k = {{"abc", "bcd", "cde"},{2}}; StringJoin@@@Subsets@@#&[k] (* out *) {"abcbcd", "abccde", "bcdcde"} ``` --- Additional examples: ``` d = {"a", "b", "cd", "e", "fgh"} m = {d, {2}} n = {d, {3}} p = {d, {4}} StringJoin@@@Subsets@@#&[m] StringJoin@@@Subsets@@#&[n] StringJoin@@@Subsets@@#&[p] (* out *) {"ab", "acd", "ae", "afgh", "bcd", "be", "bfgh", "cde", "cdfgh", "efgh"} {"abcd", "abe", "abfgh", "acde", "acdfgh", "aefgh", "bcde", "bcdfgh", "befgh", "cdefgh"} {"abcde", "abcdfgh", "abefgh", "acdefgh", "bcdefgh"} ``` [Answer] ## J, 50 48 46 44 43 41 35 characters ``` ;"1(>@{:{."1(i.@!@#A.])@}:)".1!:1[1 ``` Takes input from the keyboard. I've changed the input format from previous answers. Strings should come first, single-quoted, and separated by semi-colons, followed by the integer. ``` ;"1(>@{:{."1(i.@!@#A.])@}:)".1!:1[1 'hello';'mr';'wibble';2 hellomr hellowibble mrhello mrwibble wibblehello wibblemr ``` Entering a number larger than the largest possible combination just gives the largest possible combination: ``` ;"1(>@{:{."1(i.@!@#A.])@}:)".1!:1[1 hello mr wibble 8 hellomrwibble hellowibblemr mrhellowibble mrwibblehello wibblehellomr wibblemrhello ``` [Answer] ### Scala 52 Not a challenge - know your API: ``` def c(l:Seq[_],n:Int)=l combinations n mkString "\n" ``` invocation sample: ``` scala> c(Seq("foo", "bar", "foobar"), 2) res199: String = List(foo, bar) List(foo, foobar) List(bar, foobar) ``` Now beary605 observes that he didn't thought about library methods *combinations*, so I come up with this one, which doesn't use *combinations*, but maybe he now will come up with a permutation prohibition. ### Scala 63 (without literal combinations method): ``` def c(l:Seq[_],n:Int)=l.permutations.map(_.take(2).toSet).toSet ``` [Answer] # Java, 208 characters **No imports, two method calls**, so it should be pretty guaranteed that there are no *implisit* recursive calls neither. ``` class S{public static void main(String[]a){int n=a.length-1,k=Integer.parseInt(a[0]),i=0,j;while(++i<1<<n)if(Integer.bitCount(i)==k){String s="";for(j=0;j<n;)if((i&1<<j++)!=0)s+=a[j];System.out.println(s);}}} ``` Slightly more readable: ``` class S{ public static void main(String[]a){ int n=a.length-1,k=Integer.parseInt(a[0]),i=0,j; while(++i<1<<n) if(Integer.bitCount(i)==k){ String s=""; for(j=0;j<n;) if((i&1<<j++)!=0) s+=a[j]; System.out.println(s); } } } ``` Takes input from command line arguments. First arg is the length and the rest is the strings. Outputs each combination on a separate line: ``` $ java S 3 A B C D ABC ABD ACD BCD ``` ]
[Question] [ Given \$a\$ and \$b\$, both odd \$n+1\$-bit integers, compute \$a/b\$ to a precision of \$n+1\$ bits in the 2-adic integers. That is, compute \$c\$ such that \$a = bc\, (\mathop{\rm mod} 2^{n+1})\$. \$n\$ should be your language's native integer size, or if native integers are bigints, take it as a parameter. If your language uses trits (and presumably is either Setun assembly, TriINTERCAL, or Malbolge), you may instead compute in the 3-adics, in which case \$a\$ and \$b\$ should be multiples of 3 plus 1. Inputs should be \$(a-1)/2\$ and \$(b-1)/2\$ (trits: \$(x-1)/3\$). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (per language) wins. **Test cases:** All test cases are truncatable; if the last \$n\$ bits match the inputs, the last \$n\$ bits of the outputs match. Test cases (in hex, 32bit): (apologies for poor vinculum placement) ``` | (a-1)/2 | (b-1)/2 | (a/b-1)/2 | |-----------+-----------+-----------| | …00000000 | …00000001 | …55555555 | (1/3 = A̅B) | …00000000 | …00000002 | …66666666 | (1/5 = C̅D) | …00000001 | …00000002 | …33333333 | (3/5 = 6̅7) | …00000000 | …00000003 | …DB6DB6DB | (1/7 = 6̅D̅B̅7) | …FFFFFFFF | …00000003 | …24924924 | (-1/7 = 2̅4̅9̅) | …4620BA27 | …1876DCBC | …48CAF903 | (random) ``` More test cases may be generated by multiplying random \$n+1\$-bit odd integers and taking the last \$n+1\$ bits of the result (then shifting right by 1). A few test cases for ternary computers (nonary this time): ``` | (a-1)/3 | (b-1)/3 | (a/b-1)/3 | |-----------+-----------+-----------| | …00000000 | …00000002 | …51251251 | (1/7 = 3̅7̅6̅4) | …23472148 | …12435871 | …65732854 | (random again) ``` Similarly, do the same with \$n+1\$-trit integers ending with a 1 trit. [Answer] # [Python](https://www.python.org), 45 bytes ``` lambda a,b,n:(a-~a)*pow(b-~b,-1,2<<n)//2%2**n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZDfSsMwFMbxtk-RG1lSTrr1zzpX1ot2w5dQGalrsdCloa2IMIY3fQfBm4G4p-kL6KVPYpsEVJh-nJzwwfnlO-TlKB6bu5IfXrPw-u2-yejFOy3YNtkwxCABHmBG94yYonzACd0nQG1wFgtOxmPn3DFNrqHnrKxQgXKOSpFyPCFWlbJNkfO0xiQw0BoiiGEJ63DLBK6byupPLqCwalHkDR7tRoQYMvNWjuS8ARxd2cENxLIvh04A2z7IGsZ56JlFHxcR6hlIVD2E5ROQyZsTovY7fJzhHfp8Ok600E9nKzfV6h22xy4KUdS1MTH-Bh3lfC0FTntw2bWr36B9CnS1BtCVoN-1s_8SXeVWsS9LJc4UuOq3_cYvtU7hjjeXNeBU8U7Xel0771r9Y18) Beginning with Python 3.8 the builtin `pow` can directly compute the modular inverse. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 32 bytes ``` f(a,b,n)=(2*a+1)/(2*b+1)%2^n++\2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNxXSNBJ1knTyNG01jLQStQ019YF0EpBWNYrL09aOMYKo21BQlJlXopGmYaBjqGNsqKkJEYYZAwA) PARI/GP has a built-in p-adic type, but using the `%` operator is shorter. [Answer] # [C (gcc)](https://gcc.gnu.org/), 48 bytes ``` c;i;f(a,b){for(i=32;i;--i)c=a-b-2*b*c;return c;} ``` [Try it online!](https://tio.run/##bdDRasIwFAbg@z7FQRkkXbMm6WaFqDDdQ3ixm@TUaMBFidUJ4qsvs@hNMbc/3/l/OMjWiDGicsoSXRh6sbtA3LSSt4QxR3GqmWEyNzmqsGqPwQOqaxw6j9tjs4LJoW3c7m0zy5xv4Uc7TyhcMoB9uAWWDERZAZvBCx8vc/kqvv2gAEt4AYJS1XMfaSf7rko68eREWaf7qr5jacjEkyTvI8nnn7LuGIUSiBjXo6/FfHEPEmvn7sRoWRfAz51u0OC99fFMrrJr/EO71etDZPY36P3pHw "C (gcc) – Try It Online") Explanation: since \$(2b+1) (2c+1) = 2(2bc+b+c)+1\$ should end up equal to \$2a+1\$, we want to find a root of \$f(c) = 2bc+b+c-a\$. We do so using Newton's method (as in the proof of Hensel's lemma), with the optimization that \$f'(c) = 2b+1 \equiv 1\pmod{2}\$, so it suffices to divide by 1 instead of by \$f'(c)\$. So, we iterate to find a fixed point of \$c \mapsto c - \frac{f(c)}{1} = a-b-2bc\$. (And since each iteration increases the number of correct binary digits by at least one, and we are working with 32-bit integers, then 32 iterations suffices.) Note that it's interesting we do not need to initialize `c` to any particular starting value, since whatever the starting value is, we converge to the unique fixed point anyway. [Answer] # [C (gcc)](https://gcc.gnu.org/), 41 bytes ``` f(a,b){return b?f(2*a*b+a+b,b*b+b<<1):a;} ``` [Try it online!](https://tio.run/##VZDRSsMwFIbv8xTHiZCsmSRVOrGd4uYr7KrmImmbLTBTaTMplDx7TdaB7Nx88PHzn8OpVoeqmiaNJVVk7Bp37iyod43TpVyqRCaKqkBVFJy8ytxP98ZWp3PdQNG72rSPxzd0o05GRYeMdfAtjcW/rakJGhGEidI1vatk3/RlJspUwAZGNDLKPYWANILPYPQpYsVnsuE5S9n2I13vKbCBv6yzz912t/fg80u7bjvAcYUJpSwPuNtAFpgk5BKI89OFhMaLh@HLLiho/H@PESUTFG4EF4TM7dffsBz56Q8 "C (gcc) – Try It Online") This uses the same method as my previous answer: apply \$a/b = ab/b^2\$ repeatedly until \$b=1\$, and then \$a/1=a\$. Because \$(\mathbb{Z}/2^{33}\mathbb{Z})^{\times}\$ is a group of order \$2^{32}\$, this finishes after at most 32 iterations. [Answer] # x86 opcode, 17 bytes ``` f: sub edi, esi lea esi, [esi*2+1] .a: inc ecx mov eax, ecx mul esi cmp eax, edi jnz .a xchg eax, ecx ret ``` [Try it online!](https://tio.run/##TY8xT8MwEIVn3684VUxQIoc0UpUuLIWFqStC6OxeSpHdIttBhj8f7CSlucF@J7/7fI@8Z6vMz31L3vZ9e3aWAm5fnpAj6y6QMowVwLsP5EIDwp6/kf1xieWk90nLSeu4xJt6KClxg88dew9CkzHYptt@IdPVU9cgPk@MBTs3EfLrhaziQD6eAsq4lpBtzdW2mtnK2QKF9YfLbqmtRsJQAwYhO8Re4WK72y1AbPCxXFXQNsJ3agyUEoIwTGPU13TePtyVb1BQk2g6fzRbeOw6M479p0yknO8XCwIR9cdh5nYc@v4P "Assembly (fasm, x64, Linux) – Try It Online") # x86 opcode, 19 bytes ``` xchg eax, edi f: lea ecx, [esi+1] lea eax, [esi+ecx] mul edi add eax, esi imul esi, ecx shl esi, 1 jnz f-1 ret ``` # [C (gcc)](https://gcc.gnu.org/), 41 bytes ``` i;f(a,b){for(;a-b+--i*(~b-b););return i;} ``` [Try it online!](https://tio.run/##bdDRasIwFAbg@z7FQRES7VmT1FkhIqzuIXaxmyQ1LqBRYt0E6R592Yq7Keb25zv/D8fgzpgYnbRE5Zre7DEQqVDPEN2UfGvUVFIZtu0leHCyi2Pnzf7SbGF1bht3fPpYZ863cFDOEwq3DOAU/gJLRrwoAdcwYcu3qZjxdz/KwRKWA6dUDtxz2omhK5OOPzheVOm@cugwDZE/SDJfCFa/iKpnFAogfFktXjf15h4k1q79iVaiyoFde90Ybe6t/89kMuvij7F7tTtHtF9BnT5/AQ "C (gcc) – Try It Online") To make it comparable with the other a few [Answer] # ARM T32 machine code, 16 bytes ``` 004a 3201 4350 1840 3201 4351 d1f8 4770 ``` In assembly: ``` f: lsls r2, r1, #1 @ Set r2 to b-1 ((b-1)/2 is in r1). adds r2, #1 @ r2 becomes b. muls r0, r2 @ r0 (which was (a-1)/2) becomes b(a-1)/2. adds r0, r1 @ r0 becomes b(a-1)/2 + (b-1)/2 = (ab-1)/2. adds r2, #1 @ r2 becomes b+1. muls r1, r2 @ r1 becomes (b+1)(b-1)/2 = (b²-1)/2. bne.n f @ Jump back if that is nonzero. bx lr @ Return. ``` This applies \$a/b = ab/b^2\$ repeatedly until \$b=1\$, and then \$a/1=a\$. Because \$(\mathbb{Z}/2^{33}\mathbb{Z})^{\times}\$ is a group of order \$2^{32}\$, this finishes after at most 32 iterations. [Answer] # [R](https://www.r-project.org), 36 bytes ``` \(a,b){while((b*F)%%2^32-a)F=F+1;+F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH23PyU0pzEovjE-JTMssyU1JT4pMr4JNulpSVpuhY3VWI0EnWSNKvLMzJzUjU0krTcNFVVjeKMjXQTNd1s3bQNrbXdaqFqgxJtjczMzY0sLYyNTbmSbA2NjE1MzcwtLA0MuZJtsdsDNp0rmUtZITkjNTnbigtoRTLUClvbRIjJCxZAaAA) or [try the first few test-cases with `n` set to 15](https://ato.pxeger.com/run?1=rdHPTsIwHAfweKRPMaMLreuAbtnwT3rxwNGTN4Sl7Qou2TrcBm4hPokXPPhQePPqU1iYCiSEROMuXX79_b6ftH1-yRbL90gVt-k1y-UNHU2VKKJUwRIr6uCQCti5vMCxLAqZ5QgnkQrCaBwVOSVoDhoJjdlkEle6_2e0Qpmc6bGElXDTbxMcp2NYWccV5tqiCukPNPJ6PpcPAYtTNYYl2o6asLyQMOyX_Wpgtk01TPr6b2CayiIDLNJY-zqs2UToCYAkDacxywKm0VkUyjDgVcDp67QY2efL0zvIMEfzx_solhDysx4yTWdIfJuhHu1Z5MrqPdW9b0cfjBLjxIDMJqjtGNToAE7dVYV_VwgQdL-4dsDmXqHAxEd6mDHGt-tQrMO-dlutlud5AOyjvR3a-T0thAgP0r7vr2h3hyb_Qevk7kHadd39p-7u0O4f6JAfpnVD_eSLRb1-Ag) Input `a` and `b`, outputs `c` = `a/b`(modulo `2^32`). Uses floating-point calculations to try each multiple of `b` until it finds the first one that equals `a` mod `2^32` (corresponding to R's integer size). Note that this means that some inputs may be subject to floating-point rounding errors when `c*b` exceeds `2^53`. --- # [R](https://www.r-project.org), 40 bytes ``` \(a,b){while((F=(F+b)%%2^32)-a)T=T+1;+T} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH23PyU0pzEovjE-JTMssyU1JT4pMr4JNulpSVpuhY3NWI0EnWSNKvLMzJzUjU03Gw13LSTNFVVjeKMjTR1EzVDbEO0Da21Q2qh6oMSbY3MzM2NLC2MjU25kmwNjYxNTM3MLSwNDLmSbbHbBbaBK5lLWSE5IzU524pLI0krGWqHrW0ixOQFCyA0AA) or [try the first 2 test-cases with `n` set to 15](https://ato.pxeger.com/run?1=lZC7bsIwGIVn_BSpqghbcQROBepFXjowdspGIfINaslxaGJoIsSTdKFDH4qRN-gj1AVaqESH_out43POp9-vb-V6s9XWpcU9q9QDncytcLqwsMaWJlhSAbu3N9go51RZIZxrm0k91a6iBC1BK6eGzWam8f6faINKtfCxnNXw6I8JNsUUNtFFg7lnUYv8gFa1z1fqOWOmsFNYo9OqGaucgnJYD5tR2AntOB_62ygMbURGWBTG831Zu43QCoC8kHPDyox56EJLJTPeZJy-z90kvt7AR8gwR8uXJ20UhAMKBxFHYZiMSR_FDKU0jchdlK4O_g9GSXAZQBYT1EkCGnQBp70vhX8rCRD0PHSHAsevhQJ7ig8LIeSpDsWu7PDa9wPAOfDVLzD5P5gxxv8G9_zs916v9-cn) This also uses floating-point calculations to successively increment by `b` until the total mod `2^32` equals `a`, but here they are limited to a maximum of `2^33`, which is easily within the range that is representable without loss-of-precision, so output for all inputs is exact. It's *much* slower, though. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` €Mo%`^2→⁰*N ``` [Try it online!](https://tio.run/##yygtzv7//1HTGt981YQ4o0dtkx41btDy@///v7Hhf0MjYxNTM3MLSwPD/0Zm5uZGlhbGxqYA "Husk – Try It Online") or [try the first test-case with `n` set to 15](https://tio.run/##yygtzv6fq5Fsr21hrm1iYWep6WRo9qip8f@jpjW@@aoJcUaP2iY9atyg5ff//39D0//G/w0B) Input is `n`, `b`, `a`; output is `c` = `a/b` (modulo `2^(n+1)`). [One byte less](https://tio.run/##yygtzv7//1HTGt981YQ4o0eNG7T8/v//b2z039DI2MTUzNzC0sDwv5GZubmRpYWxsSkA) (remove the `→`) it it's acceptable to input the number of bits of the modulus (`n+1`) directly. [4 bytes less](https://tio.run/##yygtzv7//1HTGt981UeNG7T8/v//b2JkaWJpZm5kafbf0MjYxNTM3MLSwPC/kZk5UMzC2NgUAA) if it's acceptable to input the modulus itself directly. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` NθNηFN«⊞υ﹪θ²≧⁻×η﹪θ²θ≦⊘θ»I↨⮌υ² ``` [Try it online!](https://tio.run/##XYuxDsIgFEXn8hWMjwQHdTKd1EWHmqbxB7BFIaHQ8nhdjN@OjS7V6eacnNsaFdugXM5nP1C6UH/TEUZRsiWbme8hclhKIfiTFTWhAZK8Ch25AKPkGzHXRaWGPaJ9@MY@TILKekLJr7bXCOYvl3z8ucBJuUl3X/1idbQ@wVFhgoNCDY2edJyXxOctypzXbMt2eTW5Nw "Charcoal – Try It Online") Link is to verbose version of code. Takes `a`, `b` and `n+1` as input and outputs `c=a/b`. Explanation: This is like long division in reverse; to get the `i+1`th bit you compute `c` to `i` bits and see whether you want to add a `0` or `1` bit to `c`. Rather than calculating `b*c` each time, `a` is reduced each time a `1` bit is added to `c`, and also a power of `2` is eliminated by dividing `a` by `2` each step. ``` NθNηFN« ``` Input `a`, `b` and `n+1` and repeat that many times. ``` ⊞υ﹪θ² ``` Save the LSB of `a` into `c`. ``` ≧⁻×η﹪θ²θ ``` If `a` was odd then subtract `b` from it. ``` ≦⊘θ ``` Divide `a` by `2`. ``` »I↨⮌υ² ``` Convert `c` from binary. [Answer] # MMIX, 44 bytes (11 instructions) (n = 64) Call sequence: get \$a\$ in `$(X+1)`, \$b\$ in `$(X+2)`, `PUSHJ $X,div2ad`, quotient is now in `$X`, and as a bonus `$(X+2)` is unchanged and `$(X+1)` contains a sort of remainder that can be used again starting an instruction later to get more bits. Hexdump (jxd -T): ``` 00000000: 26000001 e3020000 e3030001 76ff0003 &¡¡¢ẉ£¡¡ẉ¤¡¢v”¡¤ 00000010: 3b030301 c00202ff 76ff0001 3f000001 ;¤¤¢Ċ££”v”¡¢?¡¡¢ 00000020: 260000ff 5b03fffa f8030000 &¡¡”[¤”«ẏ¤¡¡ ``` Dissassembled: ``` div2ad SUBU $0,$0,$1 // r = a - b SET $2,0 // q = 0 SET $3,1 // holds 2^i 0H ZSOD $255,$0,$3 // loop: tmp = (r&1)? 2^i : 0 SLU $3,$3,1 // increment i OR $2,$2,$255 // q |= tmp ZSOD $255,$0,$2 // tmp = (r&1)? b : 0 SRU $0,$0,1 // r >>= 1 SUBU $0,$0,$255 // r -= tmp PBNZ $3,0B // if(i <= 64) goto loop (that 1 bit got shifted off the high end) POP 3,0 // return q,r,b in that order ``` [Answer] # Z80, 14 bytes (n=8) Input is \$(a-1)/2\$ in `a`, \$(b-1)/2\$ in `c`; output is in `d`. Trashes `a`, `b`, `f`. (Well, everything trashes `f`.) ``` 91 06 08 CB 38 1F 30 03 91 CB FA 10 F6 C9 ``` Disassembled: ``` f: sub c // 91 r = n - d ld b,8 // 06 08 do 8 times: l: srl d // CB 38 q >>= 1 rra // 1F r >>= 1 jr nc,ns // 30 03 Was r even? sub c // 91 N: r -= d set 7,d // CB FA N: q |= 1 << 7 ns: djnz l // 10 F6 in any case: jump back first 7 times. ret // C9 return ``` ]